feat: add send file function

This commit is contained in:
2026-09-18 01:58:44 +08:00
parent 6e852ab224
commit 9792e49123
13 changed files with 288 additions and 95 deletions
+10 -7
View File
@@ -2,7 +2,7 @@
// ==UserScript== // ==UserScript==
// @name WhatsApp Web Bridge // @name WhatsApp Web Bridge
// @namespace https://rul.sh/ // @namespace https://rul.sh/
// @version 0.0.7 // @version 0.0.8
// @description WhatsApp Web WebSocket bridge // @description WhatsApp Web WebSocket bridge
// @match https://web.whatsapp.com/* // @match https://web.whatsapp.com/*
// @updateURL https://git.rul.sh/khairul169/whatsapp-bridge/raw/branch/main/dist/whatsapp-bridge.user.js // @updateURL https://git.rul.sh/khairul169/whatsapp-bridge/raw/branch/main/dist/whatsapp-bridge.user.js
@@ -267,7 +267,7 @@
ok: false, ok: false,
error: { error: {
code: "ERROR", code: "ERROR",
message: err instanceof Error ? err.message : String(err) message: typeof err === "object" && "message" in err ? err.message : String(err)
} }
}); });
} }
@@ -309,12 +309,15 @@
const result = await WPP.chat.sendTextMessage( const result = await WPP.chat.sendTextMessage(
request.params.chatId, request.params.chatId,
request.params.text, request.params.text,
{ request.params.options
delay: request.params.options?.delay, );
quotedMsg: request.params.options?.quotedMsg, return serialize(result);
mentionedList: request.params.options?.mentionedList,
waitForAck: request.params.options?.waitForAck
} }
case "sendFile": {
const result = await WPP.chat.sendFileMessage(
request.params.chatId,
request.params.data,
request.params.options
); );
return serialize(result); return serialize(result);
} }
+2 -2
View File
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -1,6 +1,7 @@
import * as esbuild from "esbuild"; import * as esbuild from "esbuild";
import pkgInfo from "./package.json";
const VERSION = "0.0.7"; const VERSION = pkgInfo.version;
const IS_DIST = const IS_DIST =
process.argv.indexOf("--prod") !== -1 || process.argv.indexOf("-p") !== -1; process.argv.indexOf("--prod") !== -1 || process.argv.indexOf("-p") !== -1;
const WS_URL = IS_DIST ? process.env.WS_URL : "ws://127.0.0.1:8787"; const WS_URL = IS_DIST ? process.env.WS_URL : "ws://127.0.0.1:8787";
+1
View File
@@ -2,6 +2,7 @@
"name": "whatsapp-bridge", "name": "whatsapp-bridge",
"module": "index.ts", "module": "index.ts",
"type": "module", "type": "module",
"version": "0.0.8",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "bun run esbuild.mjs", "build": "bun run esbuild.mjs",
+5
View File
@@ -1,6 +1,7 @@
import type { import type {
GetMessagesParams, GetMessagesParams,
ListChatsParams, ListChatsParams,
SendFileParams,
SendTextParams, SendTextParams,
} from "../shared/protocol"; } from "../shared/protocol";
import type { import type {
@@ -158,6 +159,10 @@ export class WhatsAppClient {
return this.request<any>("sendText", params); return this.request<any>("sendText", params);
} }
sendFile(params: SendFileParams) {
return this.request<any>("sendFile", params);
}
getMedia(msgId: string) { getMedia(msgId: string) {
return this.request<string>("getMedia", msgId); return this.request<string>("getMedia", msgId);
} }
+1
View File
@@ -214,6 +214,7 @@ wss.on("connection", (ws) => {
case "listGroups": case "listGroups":
case "getMessages": case "getMessages":
case "sendText": case "sendText":
case "sendFile":
case "getMedia": case "getMedia":
case "exec": case "exec":
result = await call(wa, request.method, request.params); result = await call(wa, request.method, request.params);
+17 -6
View File
@@ -40,16 +40,26 @@ export interface GetMessagesParams {
id?: string; id?: string;
} }
export interface SendTextParams { export interface SendTextOptions {
chatId: string;
text: string;
options?: {
delay?: number; delay?: number;
quotedMsg?: string; quotedMsg?: string;
mentionedList?: string[]; mentionedList?: string[];
waitForAck?: boolean; waitForAck?: boolean;
}; caption?: string;
filename?: string;
mimetype?: string;
}
export interface SendTextParams {
chatId: string;
text: string;
options?: SendTextOptions;
}
export interface SendFileParams {
chatId: string;
data: string;
options?: SendTextOptions;
} }
export interface GetContactsParams { export interface GetContactsParams {
@@ -64,5 +74,6 @@ export type BridgeRequest =
| RpcRequest<"listGroups"> | RpcRequest<"listGroups">
| RpcRequest<"getMessages", GetMessagesParams> | RpcRequest<"getMessages", GetMessagesParams>
| RpcRequest<"sendText", SendTextParams> | RpcRequest<"sendText", SendTextParams>
| RpcRequest<"sendFile", SendFileParams>
| RpcRequest<"getMedia", string> | RpcRequest<"getMedia", string>
| RpcRequest<"exec", string>; | RpcRequest<"exec", string>;
+11 -6
View File
@@ -110,12 +110,17 @@ async function handleRequest(request: BridgeRequest) {
const result = await WPP.chat.sendTextMessage( const result = await WPP.chat.sendTextMessage(
request.params.chatId, request.params.chatId,
request.params.text, request.params.text,
{ request.params.options,
delay: request.params.options?.delay, );
quotedMsg: request.params.options?.quotedMsg,
mentionedList: request.params.options?.mentionedList, return serialize(result);
waitForAck: request.params.options?.waitForAck, }
},
case "sendFile": {
const result = await WPP.chat.sendFileMessage(
request.params.chatId,
request.params.data,
request.params.options,
); );
return serialize(result); return serialize(result);
+22 -10
View File
@@ -1,5 +1,20 @@
declare const __WS_URL__: string; declare const __WS_URL__: string;
type SendMessageOptions = {
delay?: number;
detectMentioned?: boolean;
markIsRead?: boolean;
mentionedList?: string[];
messageId?: string;
quotedMsg?: string;
quotedMsgPayload?: string;
waitForAck?: boolean;
isViewOnce?: boolean;
filename?: string;
mimetype?: string;
type?: string;
};
declare const WPP: { declare const WPP: {
isReady: boolean; isReady: boolean;
@@ -38,16 +53,13 @@ declare const WPP: {
sendTextMessage( sendTextMessage(
chatId: string, chatId: string,
text: string, text: string,
options?: { options?: SendMessageOptions,
delay?: number; ): Promise<any>;
detectMentioned?: boolean;
markIsRead?: boolean; sendFileMessage(
mentionedList?: string[]; chatId: string,
messageId?: string; data: string,
quotedMsg?: string; options?: SendMessageOptions,
quotedMsgPayload?: string;
waitForAck?: boolean;
},
): Promise<any>; ): Promise<any>;
downloadMedia(msgId: string): Promise<Blob>; downloadMedia(msgId: string): Promise<Blob>;
+1
View File
@@ -18,6 +18,7 @@
"cn": "^0.3.0", "cn": "^0.3.0",
"dayjs": "^1.11.23", "dayjs": "^1.11.23",
"lucide-react": "^1.46.0", "lucide-react": "^1.46.0",
"nanoid": "^6.0.1",
"react": "^19.2.8", "react": "^19.2.8",
"react-dom": "^19.2.8", "react-dom": "^19.2.8",
"shadcn": "^4.21.0", "shadcn": "^4.21.0",
+10
View File
@@ -32,6 +32,9 @@ importers:
lucide-react: lucide-react:
specifier: ^1.46.0 specifier: ^1.46.0
version: 1.46.0([email protected]) version: 1.46.0([email protected])
nanoid:
specifier: ^6.0.1
version: 6.0.1
react: react:
specifier: ^19.2.8 specifier: ^19.2.8
version: 19.3.0 version: 19.3.0
@@ -1488,6 +1491,11 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true hasBin: true
[email protected]:
resolution: {integrity: sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==}
engines: {node: ^22 || ^24 || >=26}
hasBin: true
[email protected]: [email protected]:
resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==} resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==}
engines: {node: '>=18'} engines: {node: '>=18'}
@@ -3216,6 +3224,8 @@ snapshots:
[email protected]: {} [email protected]: {}
[email protected]: {}
[email protected]: [email protected]:
dependencies: dependencies:
content-type: 2.1.0 content-type: 2.1.0
+159 -28
View File
@@ -1,5 +1,5 @@
import { useWAClient } from "./context"; import { useWAClient } from "./context";
import { getFormattedName, getId } from "@/lib/utils"; import { getFilesAsBase64, getFormattedName, getId } from "@/lib/utils";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query"; import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { cn } from "cn"; import { cn } from "cn";
import { import {
@@ -10,8 +10,9 @@ import {
PaperclipIcon, PaperclipIcon,
PhoneCallIcon, PhoneCallIcon,
SendIcon, SendIcon,
XIcon,
} from "lucide-react"; } from "lucide-react";
import { useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import dayjs from "dayjs"; import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime"; import relativeTime from "dayjs/plugin/relativeTime";
import MessageMedia from "@/components/message-media"; import MessageMedia from "@/components/message-media";
@@ -22,6 +23,7 @@ import { useChats } from "@/hooks/useChats";
import Avatar from "@/components/ui/avatar"; import Avatar from "@/components/ui/avatar";
import { useIntersection } from "@/hooks/useIntersection"; import { useIntersection } from "@/hooks/useIntersection";
import Paragraph from "@/components/paragraph"; import Paragraph from "@/components/paragraph";
import { nanoid } from "nanoid";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@@ -33,8 +35,6 @@ type Props = {
export default function MessagesSection({ chatId, maxCount = 50 }: Props) { export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
const { client, isReady } = useWAClient(); const { client, isReady } = useWAClient();
const router = useHashRouter(); const router = useHashRouter();
const [message, setMessage] = useState("");
const [isPending, setPending] = useState(false);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { data: chats } = useChats(); const { data: chats } = useChats();
@@ -121,22 +121,6 @@ export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
}); });
}, [messages, contacts]); }, [messages, contacts]);
async function sendMessage() {
const text = message.trim();
if (!text || !chatId) return;
try {
setPending(true);
await client.sendText({ chatId, text, options: { waitForAck: true } });
setTimeout(refetch, 100);
setMessage("");
} catch (err) {
alert((err as Error).message);
} finally {
setPending(false);
}
}
return ( return (
<section <section
className={`flex min-w-0 flex-1 flex-col bg-muted ${chatId ? "flex" : "hidden md:flex"}`} className={`flex min-w-0 flex-1 flex-col bg-muted ${chatId ? "flex" : "hidden md:flex"}`}
@@ -235,7 +219,7 @@ export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
} }
}} }}
className={cn( className={cn(
"bg-card/30 px-2 py-1.5 rounded-lg mb-2 mt-1 cursor-pointer block", "bg-card/30 px-2 py-1.5 rounded-lg mb-2 mt-1 cursor-pointer block text-left",
!item.fromMe && "bg-[#d8f5e8]/30 dark:bg-[#26855c]/30", !item.fromMe && "bg-[#d8f5e8]/30 dark:bg-[#26855c]/30",
)} )}
> >
@@ -315,14 +299,119 @@ export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
</div> </div>
</div> </div>
<div className="border-t border-border bg-card px-3 py-3 sm:px-6 sm:py-4"> <MessageInputSection chatId={chatId} refetch={refetch} />
<div className="mx-auto flex max-w-2xl items-end gap-2"> </section>
);
}
function MessageInputSection({
chatId,
refetch,
}: {
chatId?: string | null;
refetch: () => void;
}) {
const { client, isReady } = useWAClient();
const [message, setMessage] = useState("");
const [files, setFiles] = useState<{ id: string; file: File }[]>([]);
const [isPending, setPending] = useState(false);
useEffect(() => {
function onDragOver(e: DragEvent) {
e.preventDefault();
}
function onDrop(e: DragEvent) {
const fileList = e.dataTransfer?.files || [];
if (fileList) {
e.preventDefault();
onFileAttached([...fileList]);
}
}
document.addEventListener("dragover", onDragOver);
document.addEventListener("drop", onDrop);
return () => {
document.removeEventListener("dragover", onDragOver);
document.removeEventListener("drop", onDrop);
};
}, []);
function onFileAttached(files: File[]) {
setFiles((f) => [...f, ...files.map((file) => ({ id: nanoid(), file }))]);
}
function onPaste(e: React.ClipboardEvent<HTMLTextAreaElement>) {
const fileList = e.clipboardData?.files || [];
if (fileList.length > 0) {
e.preventDefault();
onFileAttached([...fileList]);
}
}
async function sendMessage() {
const text = message.trim();
if ((!text && !files.length) || !chatId || !isReady) return;
try {
setPending(true);
const options = { waitForAck: true };
if (files.length > 0) {
const fileList = await getFilesAsBase64(files.map((f) => f.file));
for (let i = 0; i < fileList.length; i++) {
const file = fileList[i];
await client.sendFile({
chatId,
data: file,
options: {
...options,
caption: i === 0 ? text : undefined,
filename: files[i].file.name,
mimetype: files[i].file.type,
},
});
}
} else {
await client.sendText({ chatId, text, options });
}
setTimeout(refetch, 1000);
setFiles([]);
setMessage("");
} catch (err) {
alert((err as Error).message);
} finally {
setPending(false);
}
}
function onRemoveAttachment(id: string) {
setFiles((f) => f.filter((file) => file.id !== id));
}
return (
<div className="border-t border-border bg-card px-3 py-3 sm:py-4">
{files.length > 0 && (
<div className="flex items-center gap-2 mb-3 overflow-x-auto">
{files.map((i) => (
<AttachmentPreview
key={i.id}
file={i.file}
onRemove={() => onRemoveAttachment(i.id)}
/>
))}
</div>
)}
<div className="flex items-end gap-2">
<button <button
aria-label="Add attachment" aria-label="Add attachment"
className="grid size-10 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-muted-foreground" className="grid size-10 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-muted-foreground"
> >
<PaperclipIcon size={19} /> <PaperclipIcon size={19} />
</button> </button>
<div className="flex min-h-10 flex-1 items-center gap-2 rounded-2xl bg-muted px-3"> <div className="flex min-h-10 flex-1 items-center gap-2 rounded-2xl bg-muted px-3">
{/* <button {/* <button
aria-label="Add emoji" aria-label="Add emoji"
@@ -334,6 +423,7 @@ export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
<textarea <textarea
value={message} value={message}
onChange={(event) => setMessage(event.target.value)} onChange={(event) => setMessage(event.target.value)}
onPaste={onPaste}
onKeyDown={(event) => { onKeyDown={(event) => {
if ( if (
event.key === "Enter" && event.key === "Enter" &&
@@ -354,15 +444,56 @@ export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
aria-label="Send message" aria-label="Send message"
onClick={sendMessage} onClick={sendMessage}
className="grid size-10 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground shadow-sm transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50" className="grid size-10 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground shadow-sm transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"
disabled={!message.trim() || isPending} disabled={!isReady || (!message.trim() && !files.length) || isPending}
> >
<SendIcon size={17} /> <SendIcon size={17} />
</button> </button>
</div> </div>
{/* <div className="mx-auto mt-2 hidden max-w-2xl items-center justify-center gap-1 text-[10px] text-muted-foreground sm:flex">
<CircleHelpIcon size={12} /> Press Enter to send
</div> */}
</div> </div>
</section> );
}
function AttachmentPreview({
file,
onRemove,
}: {
file: File;
onRemove?: () => void;
}) {
const [img, setImg] = useState<string | null>(null);
useEffect(() => {
if (!file.type.startsWith("image/")) return;
const blob = URL.createObjectURL(file);
setImg(blob);
return () => URL.revokeObjectURL(blob);
}, [file]);
return (
<div
className={cn(
"flex items-center gap-2 rounded-2xl bg-muted px-3 py-2 shrink-0",
img != null && "rounded-sm",
)}
>
{img ? (
<a href={img} target="_blank" rel="noopener noreferrer">
<img
src={img}
alt={file.name}
className="h-10 aspect-video object-cover"
/>
</a>
) : (
<p className="text-xs">{file.name}</p>
)}
<button
aria-label="Remove attachment"
className="shrink-0 text-muted-foreground cursor-pointer hover:bg-muted hover:text-white"
onClick={onRemove}
>
<XIcon size={16} />
</button>
</div>
); );
} }
+12
View File
@@ -33,3 +33,15 @@ export function getFormattedName(
? name.user || "" ? name.user || ""
: ""; : "";
} }
export async function getFilesAsBase64(files: File[]) {
return Promise.all(
files.map((file) => {
return new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve((reader.result as string) || "");
reader.readAsDataURL(file);
});
}),
);
}