1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
|
import fs from 'node:fs';
import path from 'node:path';
import mime from 'mime';
import wweb from 'whatsapp-web.js';
import * as ser from '../serialize.js';
const { MessageMedia } = wweb;
const msgParam = { type: 'string', required: true, description: 'Serialized message ID (the "id" field)' };
const chatParam = { type: 'chat', required: true, description: 'Chat: JID (549...@c.us, ...@g.us), phone number or exact name' };
const MSG_COLUMNS = ['date', 'senderName', 'type', 'body', 'id'];
// Content parameters shared by send and reply.
const contentParams = {
body: { type: 'string', description: 'Text (or caption when there is media)' },
media: { type: 'path', description: 'File to attach' },
mediaUrl: { type: 'string', description: 'URL of a file to attach' },
asDocument: { type: 'boolean', description: 'Send the media as a document' },
asVoice: { type: 'boolean', description: 'Send audio as a voice note' },
asSticker: { type: 'boolean', description: 'Send an image as a sticker' },
viewOnce: { type: 'boolean', description: 'View once' },
linkPreview: { type: 'boolean', description: 'Generate link previews (default true)' },
mentions: { type: 'array', description: 'JIDs to mention (the text must include @number)' },
};
async function buildContent(ctx, p) {
let media;
if (p.media) media = MessageMedia.fromFilePath(p.media);
else if (p.mediaUrl) media = await MessageMedia.fromUrl(p.mediaUrl, { unsafeMime: true });
if (!media && !p.body) throw new ctx.WaError('EINVAL', 'nothing to send: "body", "media" or "mediaUrl" is missing');
const opts = {};
if (media && p.body) opts.caption = p.body;
if (p.asDocument) opts.sendMediaAsDocument = true;
if (p.asVoice) opts.sendAudioAsVoice = true;
if (p.asSticker) opts.sendMediaAsSticker = true;
if (p.viewOnce) opts.isViewOnce = true;
if (p.linkPreview !== undefined) opts.linkPreview = p.linkPreview;
if (p.mentions) opts.mentions = p.mentions;
return [media ?? p.body, opts];
}
// Adds media.data (base64) to the serialized messages that have media.
async function attachMedia(pairs) {
for (const [msg, out] of pairs) {
if (!msg.hasMedia) continue;
try {
const m = await msg.downloadMedia();
if (m) Object.assign(out.media, { mimetype: m.mimetype, filename: m.filename || out.media.filename, data: m.data });
} catch (e) {
out.media.error = e.message;
}
}
}
function uniquePath(p) {
if (!fs.existsSync(p)) return p;
const { dir, name, ext } = path.parse(p);
for (let i = 1; ; i++) {
const c = path.join(dir, `${name}-${i}${ext}`);
if (!fs.existsSync(c)) return c;
}
}
export default {
'messages.list': {
description: 'Messages of a chat, in chronological order (the last `limit`).',
params: {
chatId: chatParam,
limit: { type: 'integer', default: 50, description: 'Maximum count (from the most recent backwards)' },
since: { type: 'integer', description: 'Only messages with timestamp >= since (epoch s). Loads history until covered' },
until: { type: 'integer', description: 'Only messages with timestamp < until (epoch s)' },
fromMe: { type: 'boolean', description: 'true: sent only; false: received only' },
includeMedia: { type: 'boolean', default: false, description: 'Download media and include it as base64 (media.data)' },
},
columns: MSG_COLUMNS,
handler: async (ctx, p) => {
const chat = await ctx.getChat(p.chatId);
const search = p.fromMe === undefined ? {} : { fromMe: p.fromMe };
let limit = p.limit;
let msgs = await chat.fetchMessages({ ...search, limit });
// With `since`, keep loading history until past that date (or exhausted).
if (p.since !== undefined) {
const oldest = () => msgs.reduce((min, m) => Math.min(min, m.timestamp), Infinity);
while (msgs.length >= limit && oldest() >= p.since && limit < 20000) {
limit *= 2;
msgs = await chat.fetchMessages({ ...search, limit });
}
msgs = msgs.filter((m) => m.timestamp >= p.since);
}
if (p.until !== undefined) msgs = msgs.filter((m) => m.timestamp < p.until);
const pairs = msgs.map((m) => [m, ser.message(m, ctx.ser)]);
if (p.includeMedia) await attachMedia(pairs);
return pairs.map(([, out]) => out);
},
},
'messages.get': {
description: 'A message by ID.',
params: {
messageId: msgParam,
includeMedia: { type: 'boolean', default: false, description: 'Download media and include it as base64 (media.data)' },
},
columns: MSG_COLUMNS,
handler: async (ctx, p) => {
const m = await ctx.getMessage(p.messageId);
const out = ser.message(m, ctx.ser);
if (p.includeMedia) await attachMedia([[m, out]]);
return out;
},
},
'messages.search': {
description: 'Searches messages by text (in all chats or in one).',
params: {
query: { type: 'string', required: true, description: 'Text to search for' },
chatId: { ...chatParam, required: false },
page: { type: 'integer', description: 'Results page' },
limit: { type: 'integer', description: 'Results per page' },
},
columns: ['date', 'chatId', 'senderName', 'body', 'id'],
handler: async (ctx, p) => {
const { query, ...opts } = p;
const msgs = await ctx.client.searchMessages(query, opts);
return msgs.map((m) => ser.message(m, ctx.ser));
},
},
'messages.send': {
description: 'Sends a text message or a file.',
params: {
chatId: chatParam,
...contentParams,
quotedMessageId: { type: 'string', description: 'ID of the message to quote (reply to)' },
},
columns: MSG_COLUMNS,
handler: async (ctx, p) => {
const [content, opts] = await buildContent(ctx, p);
if (p.quotedMessageId) opts.quotedMessageId = p.quotedMessageId;
const m = await ctx.client.sendMessage(p.chatId, content, opts);
return ser.message(m, ctx.ser);
},
},
'messages.reply': {
description: 'Replies quoting a message, in the same chat.',
params: { messageId: msgParam, ...contentParams },
columns: MSG_COLUMNS,
handler: async (ctx, p) => {
const orig = await ctx.getMessage(p.messageId);
const [content, opts] = await buildContent(ctx, p);
const m = await orig.reply(content, undefined, opts);
return ser.message(m, ctx.ser);
},
},
'messages.forward': {
description: 'Forwards a message to another chat.',
params: { messageId: msgParam, chatId: chatParam },
handler: async (ctx, p) => {
await (await ctx.getMessage(p.messageId)).forward(p.chatId);
return { ok: true
|