-
-
Notifications
You must be signed in to change notification settings - Fork 80.9k
Expand file tree
/
Copy pathsend.outbound.ts
More file actions
510 lines (489 loc) · 16.7 KB
/
Copy pathsend.outbound.ts
File metadata and controls
510 lines (489 loc) · 16.7 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// Discord plugin module implements send.outbound behavior.
import type { APIChannel, APIGuildForumChannel, APIGuildMediaChannel } from "discord-api-types/v10";
import { ChannelType } from "discord-api-types/v10";
import { recordChannelActivity } from "openclaw/plugin-sdk/channel-activity-runtime";
import type { MarkdownTableMode, OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
import type { OutboundMediaAccess, PollInput } from "openclaw/plugin-sdk/media-runtime";
import { requireRuntimeConfig } from "openclaw/plugin-sdk/plugin-config-runtime";
import { resolveChunkMode, type ChunkMode } from "openclaw/plugin-sdk/reply-chunking";
import type { RetryConfig } from "openclaw/plugin-sdk/retry-runtime";
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import { convertMarkdownTables } from "openclaw/plugin-sdk/text-chunking";
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
import { resolveDiscordAccount } from "./accounts.js";
import { createChannelMessage, createThread, type RequestClient } from "./internal/discord.js";
import { rewriteDiscordKnownMentions } from "./mentions.js";
import { parseAndResolveChannelRecipient } from "./recipient-resolution.js";
import {
createReusableDiscordReplyReference,
type DiscordReplyReference,
} from "./reply-reference.js";
import { createDiscordSendResult, type DiscordReceiptResultSource } from "./send.receipt.js";
import {
buildDiscordMessageRequest,
buildDiscordSendError,
buildDiscordTextChunks,
createDiscordClient,
normalizeDiscordPollInput,
normalizeStickerIds,
resolveDiscordMessageFlags,
resolveChannelId,
resolveDiscordChannel,
resolveDiscordSendComponents,
resolveDiscordSendEmbeds,
sendDiscordMedia,
sendDiscordText,
type DiscordAllowedMentions,
type DiscordSendProgress,
type DiscordSendComponents,
type DiscordSendEmbeds,
} from "./send.shared.js";
import type { DiscordSendResult } from "./send.types.js";
type DiscordSendOpts = {
cfg: OpenClawConfig;
token?: string;
accountId?: string;
mediaUrl?: string;
filename?: string;
mediaAccess?: OutboundMediaAccess;
mediaLocalRoots?: readonly string[];
mediaReadFile?: (filePath: string) => Promise<Buffer>;
verbose?: boolean;
rest?: RequestClient;
reply?: DiscordReplyReference;
retry?: RetryConfig;
textLimit?: number;
maxLinesPerMessage?: number;
tableMode?: MarkdownTableMode;
chunkMode?: ChunkMode;
components?: DiscordSendComponents;
embeds?: DiscordSendEmbeds;
silent?: boolean;
suppressEmbeds?: boolean;
allowedMentions?: DiscordAllowedMentions;
/** Persist each concrete platform send before any later chunk can fail. */
onDeliveryResult?: (result: DiscordSendResult) => Promise<void> | void;
};
type DiscordClientRequest = ReturnType<typeof createDiscordClient>["request"];
const DEFAULT_DISCORD_MEDIA_MAX_MB = 100;
type DiscordChannelMessageResult = DiscordReceiptResultSource;
async function sendDiscordThreadTextChunks(params: {
rest: RequestClient;
threadId: string;
chunks: readonly string[];
request: DiscordClientRequest;
maxLinesPerMessage?: number;
chunkMode: ReturnType<typeof resolveChunkMode>;
maxChars?: number;
silent?: boolean;
suppressEmbeds?: boolean;
allowedMentions?: DiscordAllowedMentions;
onResult?: DiscordSendProgress;
}): Promise<void> {
for (const chunk of params.chunks) {
await sendDiscordText({
rest: params.rest,
channelId: params.threadId,
text: chunk,
request: params.request,
maxLinesPerMessage: params.maxLinesPerMessage,
chunkMode: params.chunkMode,
silent: params.silent,
suppressEmbeds: params.suppressEmbeds,
allowedMentions: params.allowedMentions,
maxChars: params.maxChars,
onResult: params.onResult,
});
}
}
function resolveDiscordSuppressEmbeds(params: {
configured?: boolean;
override?: boolean;
}): boolean {
return params.override ?? params.configured ?? true;
}
/** Discord thread names are capped at 100 characters. */
const DISCORD_THREAD_NAME_LIMIT = 100;
/** Derive a thread title from the first non-empty line of the message text. */
function deriveForumThreadName(text: string): string {
const firstLine =
normalizeOptionalString(text.split("\n").find((line) => normalizeOptionalString(line))) ?? "";
return (
truncateUtf16Safe(firstLine, DISCORD_THREAD_NAME_LIMIT) || new Date().toISOString().slice(0, 16)
);
}
/** Forum/Media channels cannot receive regular messages; detect them here. */
function isForumLikeChannel(
channel?: APIChannel,
): channel is APIGuildForumChannel | APIGuildMediaChannel {
return channel?.type === ChannelType.GuildForum || channel?.type === ChannelType.GuildMedia;
}
function toDiscordSendResult(
result: DiscordChannelMessageResult,
fallbackChannelId: string,
params: {
kind?: Parameters<typeof createDiscordSendResult>[0]["kind"];
threadId?: string | number;
reply?: DiscordReplyReference;
} = {},
): DiscordSendResult {
const resultParams: Parameters<typeof createDiscordSendResult>[0] = {
result,
fallbackChannelId,
kind: params.kind ?? "text",
};
if (params.threadId != null) {
resultParams.threadId = params.threadId;
}
if (params.reply) {
resultParams.reply = params.reply;
}
return createDiscordSendResult(resultParams);
}
async function resolveDiscordSendTarget(
to: string,
opts: DiscordSendOpts,
): Promise<{ rest: RequestClient; request: DiscordClientRequest; channelId: string }> {
const cfg = requireRuntimeConfig(opts.cfg, "Discord send target resolution");
const { rest, request } = createDiscordClient({ ...opts, cfg });
const recipient = await parseAndResolveChannelRecipient(to, cfg, opts.accountId);
const { channelId } = await resolveChannelId(rest, recipient, request);
return { rest, request, channelId };
}
export async function sendMessageDiscord(
to: string,
text: string,
opts: DiscordSendOpts,
): Promise<DiscordSendResult> {
const cfg = requireRuntimeConfig(opts.cfg, "Discord send");
const accountInfo = resolveDiscordAccount({
cfg,
accountId: opts.accountId,
});
const tableMode = resolveMarkdownTableMode({
cfg,
channel: "discord",
accountId: accountInfo.accountId,
});
const effectiveTableMode = opts.tableMode ?? tableMode;
const chunkMode = opts.chunkMode ?? resolveChunkMode(cfg, "discord", accountInfo.accountId);
const maxLinesPerMessage = opts.maxLinesPerMessage ?? accountInfo.config.maxLinesPerMessage;
const suppressEmbeds = resolveDiscordSuppressEmbeds({
configured: accountInfo.config.suppressEmbeds,
override: opts.suppressEmbeds,
});
const textLimit =
typeof opts.textLimit === "number" && Number.isFinite(opts.textLimit)
? Math.max(1, Math.min(Math.floor(opts.textLimit), 2000))
: undefined;
const mediaMaxBytes =
typeof accountInfo.config.mediaMaxMb === "number"
? accountInfo.config.mediaMaxMb * 1024 * 1024
: DEFAULT_DISCORD_MEDIA_MAX_MB * 1024 * 1024;
const textWithTables = convertMarkdownTables(text ?? "", effectiveTableMode);
const textWithMentions = rewriteDiscordKnownMentions(textWithTables, {
accountId: accountInfo.accountId,
mentionAliases: accountInfo.config.mentionAliases,
});
const { token, rest, request } = createDiscordClient({ ...opts, cfg });
const recipient = await parseAndResolveChannelRecipient(to, cfg, opts.accountId);
const { channelId } = await resolveChannelId(rest, recipient, request);
// Forum/Media channels reject POST /messages; auto-create a thread post instead.
const channel = await resolveDiscordChannel(rest, channelId);
if (isForumLikeChannel(channel)) {
const threadName = deriveForumThreadName(textWithTables);
const chunks = buildDiscordTextChunks(textWithMentions, {
maxLinesPerMessage,
chunkMode,
maxChars: textLimit,
});
const starterContent = chunks[0]?.trim() ? chunks[0] : threadName;
const starterComponents = resolveDiscordSendComponents({
components: opts.components,
text: starterContent,
isFirst: true,
});
const starterEmbeds = resolveDiscordSendEmbeds({ embeds: opts.embeds, isFirst: true });
const starterFlags = resolveDiscordMessageFlags({
silent: opts.silent,
suppressEmbeds: suppressEmbeds && !starterEmbeds?.length,
});
const starterBody = buildDiscordMessageRequest({
text: starterContent,
components: starterComponents,
embeds: starterEmbeds,
flags: starterFlags,
allowedMentions: opts.allowedMentions,
});
let threadRes: { id: string; message?: { id: string; channel_id: string } };
try {
threadRes = (await request(
() =>
createThread<{ id: string; message?: { id: string; channel_id: string } }>(
rest,
channelId,
{
body: {
name: threadName,
// Discord clients preselect the parent default; the REST endpoint otherwise
// falls back to 4320 minutes, so carry the fetched parent value explicitly.
...(channel.default_auto_archive_duration === undefined
? {}
: { auto_archive_duration: channel.default_auto_archive_duration }),
message: starterBody,
},
},
),
"forum-thread",
)) as { id: string; message?: { id: string; channel_id: string } };
} catch (err) {
throw await buildDiscordSendError(err, {
channelId,
cfg,
rest,
token,
hasMedia: Boolean(opts.mediaUrl),
});
}
const threadId = threadRes.id;
const messageId = threadRes.message?.id ?? threadId;
const resultChannelId = threadRes.message?.channel_id ?? threadId;
const remainingChunks = chunks.slice(1);
await opts.onDeliveryResult?.(
toDiscordSendResult(
{
id: messageId,
channel_id: resultChannelId,
},
channelId,
{ kind: "text", threadId },
),
);
const reportThreadResult: DiscordSendProgress = async (result, kind) => {
await opts.onDeliveryResult?.(toDiscordSendResult(result, threadId, { kind, threadId }));
};
try {
if (opts.mediaUrl) {
const [mediaCaption, ...afterMediaChunks] = remainingChunks;
await sendDiscordMedia({
rest,
channelId: threadId,
text: mediaCaption ?? "",
mediaUrl: opts.mediaUrl,
filename: opts.filename,
mediaAccess: opts.mediaAccess,
mediaLocalRoots: opts.mediaLocalRoots,
mediaReadFile: opts.mediaReadFile,
maxBytes: mediaMaxBytes,
request,
maxLinesPerMessage,
chunkMode,
silent: opts.silent,
suppressEmbeds,
allowedMentions: opts.allowedMentions,
maxChars: textLimit,
onResult: reportThreadResult,
});
await sendDiscordThreadTextChunks({
rest,
threadId,
chunks: afterMediaChunks,
request,
maxLinesPerMessage,
chunkMode,
maxChars: textLimit,
silent: opts.silent,
suppressEmbeds,
allowedMentions: opts.allowedMentions,
onResult: reportThreadResult,
});
} else {
await sendDiscordThreadTextChunks({
rest,
threadId,
chunks: remainingChunks,
request,
maxLinesPerMessage,
chunkMode,
maxChars: textLimit,
silent: opts.silent,
suppressEmbeds,
allowedMentions: opts.allowedMentions,
onResult: reportThreadResult,
});
}
} catch (err) {
throw await buildDiscordSendError(err, {
channelId: threadId,
cfg,
rest,
token,
hasMedia: Boolean(opts.mediaUrl),
});
}
recordChannelActivity({
channel: "discord",
accountId: accountInfo.accountId,
direction: "outbound",
});
return toDiscordSendResult(
{
id: messageId,
channel_id: resultChannelId,
},
channelId,
{ kind: opts.mediaUrl ? "media" : "text", threadId },
);
}
let result: DiscordChannelMessageResult;
const reportResult: DiscordSendProgress = async (progressResult, kind, replyToId) => {
await opts.onDeliveryResult?.(
toDiscordSendResult(progressResult, channelId, {
kind,
reply: createReusableDiscordReplyReference(replyToId),
}),
);
};
try {
if (opts.mediaUrl) {
result = await sendDiscordMedia({
rest,
channelId,
text: textWithMentions,
mediaUrl: opts.mediaUrl,
filename: opts.filename,
mediaAccess: opts.mediaAccess,
mediaLocalRoots: opts.mediaLocalRoots,
mediaReadFile: opts.mediaReadFile,
maxBytes: mediaMaxBytes,
reply: opts.reply,
request,
maxLinesPerMessage,
components: opts.components,
embeds: opts.embeds,
chunkMode,
silent: opts.silent,
suppressEmbeds,
allowedMentions: opts.allowedMentions,
maxChars: textLimit,
onResult: reportResult,
});
} else {
result = await sendDiscordText({
rest,
channelId,
text: textWithMentions,
reply: opts.reply,
request,
maxLinesPerMessage,
components: opts.components,
embeds: opts.embeds,
chunkMode,
silent: opts.silent,
suppressEmbeds,
allowedMentions: opts.allowedMentions,
maxChars: textLimit,
onResult: reportResult,
});
}
} catch (err) {
throw await buildDiscordSendError(err, {
channelId,
cfg,
rest,
token,
hasMedia: Boolean(opts.mediaUrl),
});
}
recordChannelActivity({
channel: "discord",
accountId: accountInfo.accountId,
direction: "outbound",
});
return toDiscordSendResult(result, channelId, {
kind: opts.mediaUrl ? "media" : opts.components || opts.embeds ? "card" : "text",
reply: opts.reply,
});
}
export async function sendStickerDiscord(
to: string,
stickerIds: string[],
opts: DiscordSendOpts & { content?: string },
): Promise<DiscordSendResult> {
const { rest, request, channelId, rewrittenContent, suppressEmbeds } =
await resolveDiscordStructuredSendContext(to, opts);
const stickers = normalizeStickerIds(stickerIds);
const flags = resolveDiscordMessageFlags({ suppressEmbeds });
const res = (await request(
() =>
createChannelMessage<{ id: string; channel_id: string }>(rest, channelId, {
body: {
content: rewrittenContent || undefined,
sticker_ids: stickers,
...(flags ? { flags } : {}),
},
}),
"sticker",
)) as { id: string; channel_id: string };
return toDiscordSendResult(res, channelId, { kind: "card" });
}
export async function sendPollDiscord(
to: string,
poll: PollInput,
opts: DiscordSendOpts & { content?: string },
): Promise<DiscordSendResult> {
const { rest, request, channelId, rewrittenContent, suppressEmbeds } =
await resolveDiscordStructuredSendContext(to, opts);
if (poll.durationSeconds !== undefined) {
throw new Error("Discord polls do not support durationSeconds; use durationHours");
}
const payload = normalizeDiscordPollInput(poll);
const flags = resolveDiscordMessageFlags({ silent: opts.silent, suppressEmbeds });
const res = (await request(
() =>
createChannelMessage<{ id: string; channel_id: string }>(rest, channelId, {
body: {
content: rewrittenContent || undefined,
poll: payload,
...(flags ? { flags } : {}),
},
}),
"poll",
)) as { id: string; channel_id: string };
return toDiscordSendResult(res, channelId, { kind: "card" });
}
async function resolveDiscordStructuredSendContext(
to: string,
opts: DiscordSendOpts & { content?: string },
): Promise<{
rest: RequestClient;
request: DiscordClientRequest;
channelId: string;
rewrittenContent?: string;
suppressEmbeds: boolean;
}> {
const cfg = requireRuntimeConfig(opts.cfg, "Discord structured send");
const accountInfo = resolveDiscordAccount({
cfg,
accountId: opts.accountId,
});
const { rest, request, channelId } = await resolveDiscordSendTarget(to, opts);
const content = opts.content?.trim();
const rewrittenContent = content
? rewriteDiscordKnownMentions(content, {
accountId: accountInfo.accountId,
mentionAliases: accountInfo.config.mentionAliases,
})
: undefined;
return {
rest,
request,
channelId,
rewrittenContent,
suppressEmbeds: resolveDiscordSuppressEmbeds({
configured: accountInfo.config.suppressEmbeds,
override: opts.suppressEmbeds,
}),
};
}