-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathsend.ts
More file actions
1827 lines (1711 loc) · 59 KB
/
Copy pathsend.ts
File metadata and controls
1827 lines (1711 loc) · 59 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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as grammy from "grammy";
import { type ApiClientOptions, Bot, HttpError } from "grammy";
import type { ReactionType, ReactionTypeEmoji } from "grammy/types";
import { recordChannelActivity } from "openclaw/plugin-sdk/channel-activity-runtime";
import { isDiagnosticFlagEnabled } from "openclaw/plugin-sdk/diagnostic-runtime";
import { formatUncaughtError } from "openclaw/plugin-sdk/error-runtime";
import { redactSensitiveText } from "openclaw/plugin-sdk/logging-core";
import { createTelegramRetryRunner, type RetryConfig } from "openclaw/plugin-sdk/retry-runtime";
import { createSubsystemLogger, logVerbose } from "openclaw/plugin-sdk/runtime-env";
import { formatErrorMessage } from "openclaw/plugin-sdk/ssrf-runtime";
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import { getOrCreateAccountThrottler } from "./account-throttler.js";
import { type ResolvedTelegramAccount, resolveTelegramAccount } from "./accounts.js";
import { withTelegramApiErrorLogging } from "./api-logging.js";
import { normalizeTelegramApiRoot } from "./api-root.js";
import { buildTypingThreadParams } from "./bot/helpers.js";
import type { TelegramInlineButtons } from "./button-types.js";
import { splitTelegramCaption } from "./caption.js";
import { asTelegramClientFetch, createTelegramClientFetch } from "./client-fetch.js";
import { resolveTelegramTransport } from "./fetch.js";
import {
renderTelegramHtmlText,
splitTelegramHtmlChunks,
telegramHtmlToPlainTextFallback,
} from "./format.js";
import { buildInlineKeyboard } from "./inline-keyboard.js";
import {
isRecoverableTelegramNetworkError,
isSafeToRetrySendError,
isTelegramRateLimitError,
isTelegramServerError,
} from "./network-errors.js";
import { makeProxyFetch } from "./proxy.js";
import {
buildTelegramThreadReplyParams,
resolveTelegramSendThreadSpec,
} from "./reply-parameters.js";
import {
buildOutboundMediaLoadOptions,
getImageMetadata,
isGifMedia,
kindFromMime,
loadWebMedia,
type MediaKind,
normalizePollInput,
probeVideoDimensions,
type OpenClawConfig,
type PollInput,
requireRuntimeConfig,
resolveMarkdownTableMode,
} from "./send.runtime.js";
import { recordSentMessage } from "./sent-message-cache.js";
import { maybePersistResolvedTelegramTarget } from "./target-writeback.js";
import {
normalizeTelegramChatId,
normalizeTelegramLookupTarget,
parseTelegramTarget,
} from "./targets.js";
import { resolveTelegramVoiceSend } from "./voice.js";
export { buildInlineKeyboard } from "./inline-keyboard.js";
type TelegramApi = Bot["api"];
export type TelegramApiOverride = Partial<TelegramApi>;
type TelegramSendMessageParams = Parameters<TelegramApi["sendMessage"]>[2];
type TelegramSendPollParams = Parameters<TelegramApi["sendPoll"]>[3];
type TelegramEditMessageTextParams = Parameters<TelegramApi["editMessageText"]>[3];
type TelegramCreateForumTopicParams = NonNullable<Parameters<TelegramApi["createForumTopic"]>[2]>;
type TelegramThreadScopedParams = {
message_thread_id?: number;
};
const InputFileCtor = grammy.InputFile;
const MAX_TELEGRAM_PHOTO_DIMENSION_SUM = 10_000;
const MAX_TELEGRAM_PHOTO_ASPECT_RATIO = 20;
type TelegramSendOpts = {
cfg: OpenClawConfig;
token?: string;
accountId?: string;
verbose?: boolean;
mediaUrl?: string;
mediaLocalRoots?: readonly string[];
mediaReadFile?: (filePath: string) => Promise<Buffer>;
gatewayClientScopes?: readonly string[];
maxBytes?: number;
api?: TelegramApiOverride;
retry?: RetryConfig;
textMode?: "markdown" | "html";
plainText?: string;
/** Send audio as voice message instead of audio file. Defaults to false. */
asVoice?: boolean;
/** Send video as video note instead of regular video. Defaults to false. */
asVideoNote?: boolean;
/** Send message silently (no notification). Defaults to false. */
silent?: boolean;
/** Message ID to reply to (for threading) */
replyToMessageId?: number;
/** Quote text for Telegram reply_parameters. */
quoteText?: string;
/** Forum topic thread ID (for forum supergroups) */
messageThreadId?: number;
/** Inline keyboard buttons (reply markup). */
buttons?: TelegramInlineButtons;
/** Send image as document to avoid Telegram compression. Defaults to false. */
forceDocument?: boolean;
};
type TelegramSendResult = {
messageId: string;
chatId: string;
};
type TelegramMessageLike = {
message_id?: number;
chat?: { id?: string | number };
};
type TelegramOutboundSuccessLogParams = {
accountId: string;
chatId: string;
messageId: string;
operation: string;
deliveryKind?: string;
messageThreadId?: number;
replyToMessageId?: number;
silent?: boolean;
chunkCount?: number;
};
type TelegramReactionOpts = {
cfg: OpenClawConfig;
token?: string;
accountId?: string;
api?: TelegramApiOverride;
remove?: boolean;
verbose?: boolean;
retry?: RetryConfig;
gatewayClientScopes?: readonly string[];
};
type TelegramTypingOpts = {
cfg: OpenClawConfig;
token?: string;
accountId?: string;
verbose?: boolean;
api?: TelegramApiOverride;
retry?: RetryConfig;
messageThreadId?: number;
};
function resolveTelegramMessageIdOrThrow(
result: TelegramMessageLike | null | undefined,
context: string,
): number {
if (typeof result?.message_id === "number" && Number.isFinite(result.message_id)) {
return Math.trunc(result.message_id);
}
throw new Error(`Telegram ${context} returned no message_id`);
}
function splitTelegramPlainTextChunks(text: string, limit: number): string[] {
if (!text) {
return [];
}
const normalizedLimit = Math.max(1, Math.floor(limit));
const chunks: string[] = [];
for (let start = 0; start < text.length; start += normalizedLimit) {
chunks.push(text.slice(start, start + normalizedLimit));
}
return chunks;
}
function splitTelegramPlainTextFallback(text: string, chunkCount: number, limit: number): string[] {
if (!text) {
return [];
}
const normalizedLimit = Math.max(1, Math.floor(limit));
const fixedChunks = splitTelegramPlainTextChunks(text, normalizedLimit);
if (chunkCount <= 1 || fixedChunks.length >= chunkCount) {
return fixedChunks;
}
const chunks: string[] = [];
let offset = 0;
for (let index = 0; index < chunkCount; index += 1) {
const remainingChars = text.length - offset;
const remainingChunks = chunkCount - index;
const nextChunkLength =
remainingChunks === 1
? remainingChars
: Math.min(normalizedLimit, Math.ceil(remainingChars / remainingChunks));
chunks.push(text.slice(offset, offset + nextChunkLength));
offset += nextChunkLength;
}
return chunks;
}
function logTelegramOutboundSendOk(params: TelegramOutboundSuccessLogParams): void {
const parts = [
"telegram outbound send ok",
`accountId=${params.accountId}`,
`chatId=${params.chatId}`,
`messageId=${params.messageId}`,
`operation=${params.operation}`,
];
if (params.deliveryKind) {
parts.push(`deliveryKind=${params.deliveryKind}`);
}
if (typeof params.messageThreadId === "number") {
parts.push(`threadId=${params.messageThreadId}`);
}
if (typeof params.replyToMessageId === "number") {
parts.push(`replyToMessageId=${params.replyToMessageId}`);
}
if (params.silent === true) {
parts.push("silent=true");
}
if (typeof params.chunkCount === "number") {
parts.push(`chunkCount=${params.chunkCount}`);
}
sendLogger.info(parts.join(" "));
}
const PARSE_ERR_RE = /can't parse entities|parse entities|find end of the entity/i;
const THREAD_NOT_FOUND_RE = /400:\s*Bad Request:\s*message thread not found/i;
const MESSAGE_NOT_MODIFIED_RE =
/400:\s*Bad Request:\s*message is not modified|MESSAGE_NOT_MODIFIED/i;
const MESSAGE_DELETE_NOOP_RE =
/message to delete not found|message can't be deleted|MESSAGE_ID_INVALID|MESSAGE_DELETE_FORBIDDEN/i;
const CHAT_NOT_FOUND_RE = /400: Bad Request: chat not found/i;
const sendLogger = createSubsystemLogger("telegram/send");
const diagLogger = createSubsystemLogger("telegram/diagnostic");
const telegramClientOptionsCache = new Map<string, ApiClientOptions | undefined>();
const MAX_TELEGRAM_CLIENT_OPTIONS_CACHE_SIZE = 64;
export function resetTelegramClientOptionsCacheForTests(): void {
telegramClientOptionsCache.clear();
}
function createTelegramHttpLogger(cfg: OpenClawConfig) {
const enabled = isDiagnosticFlagEnabled("telegram.http", cfg);
if (!enabled) {
return () => {};
}
return (label: string, err: unknown) => {
if (!(err instanceof HttpError)) {
return;
}
const detail = redactSensitiveText(formatUncaughtError(err.error ?? err));
diagLogger.warn(`telegram http error (${label}): ${detail}`);
};
}
function shouldUseTelegramClientOptionsCache(): boolean {
return !process.env.VITEST && process.env.NODE_ENV !== "test";
}
function buildTelegramClientOptionsCacheKey(params: {
account: ResolvedTelegramAccount;
timeoutSeconds?: number;
}): string {
const proxyKey = params.account.config.proxy?.trim() ?? "";
const autoSelectFamily = params.account.config.network?.autoSelectFamily;
const autoSelectFamilyKey =
typeof autoSelectFamily === "boolean" ? String(autoSelectFamily) : "default";
const dnsResultOrderKey = params.account.config.network?.dnsResultOrder ?? "default";
const apiRootKey = params.account.config.apiRoot?.trim() ?? "";
const timeoutSecondsKey =
typeof params.timeoutSeconds === "number" ? String(params.timeoutSeconds) : "default";
return `${params.account.accountId}::${proxyKey}::${autoSelectFamilyKey}::${dnsResultOrderKey}::${apiRootKey}::${timeoutSecondsKey}`;
}
function setCachedTelegramClientOptions(
cacheKey: string,
clientOptions: ApiClientOptions | undefined,
): ApiClientOptions | undefined {
telegramClientOptionsCache.set(cacheKey, clientOptions);
if (telegramClientOptionsCache.size > MAX_TELEGRAM_CLIENT_OPTIONS_CACHE_SIZE) {
const oldestKey = telegramClientOptionsCache.keys().next().value;
if (oldestKey !== undefined) {
telegramClientOptionsCache.delete(oldestKey);
}
}
return clientOptions;
}
function resolveTelegramClientOptions(
account: ResolvedTelegramAccount,
): ApiClientOptions | undefined {
const timeoutSeconds =
typeof account.config.timeoutSeconds === "number" &&
Number.isFinite(account.config.timeoutSeconds)
? Math.max(1, Math.floor(account.config.timeoutSeconds))
: undefined;
const cacheEnabled = shouldUseTelegramClientOptionsCache();
const cacheKey = cacheEnabled
? buildTelegramClientOptionsCacheKey({
account,
timeoutSeconds,
})
: null;
if (cacheKey && telegramClientOptionsCache.has(cacheKey)) {
return telegramClientOptionsCache.get(cacheKey);
}
const proxyUrl = normalizeOptionalString(account.config.proxy);
const proxyFetch = proxyUrl ? makeProxyFetch(proxyUrl) : undefined;
const apiRoot = normalizeOptionalString(account.config.apiRoot);
const normalizedApiRoot = apiRoot ? normalizeTelegramApiRoot(apiRoot) : undefined;
const transport = resolveTelegramTransport(proxyFetch, {
network: account.config.network,
});
const fetchImpl = createTelegramClientFetch({
fetchImpl: asTelegramClientFetch(transport.fetch),
timeoutSeconds,
transport,
});
const clientOptions =
fetchImpl || timeoutSeconds || normalizedApiRoot
? {
...(fetchImpl ? { fetch: asTelegramClientFetch(fetchImpl) } : {}),
...(timeoutSeconds ? { timeoutSeconds } : {}),
...(normalizedApiRoot ? { apiRoot: normalizedApiRoot } : {}),
}
: undefined;
if (cacheKey) {
return setCachedTelegramClientOptions(cacheKey, clientOptions);
}
return clientOptions;
}
function resolveToken(explicit: string | undefined, params: { accountId: string; token: string }) {
if (explicit?.trim()) {
return explicit.trim();
}
if (!params.token) {
throw new Error(
`Telegram bot token missing for account "${params.accountId}" (set channels.telegram.accounts.${params.accountId}.botToken/tokenFile or TELEGRAM_BOT_TOKEN for default).`,
);
}
return params.token.trim();
}
async function resolveChatId(
to: string,
params: { api: TelegramApiOverride; verbose?: boolean },
): Promise<string> {
const numericChatId = normalizeTelegramChatId(to);
if (numericChatId) {
return numericChatId;
}
const lookupTarget = normalizeTelegramLookupTarget(to);
const getChat = params.api.getChat;
if (!lookupTarget || typeof getChat !== "function") {
throw new Error("Telegram recipient must be a numeric chat ID");
}
try {
const chat = await getChat.call(params.api, lookupTarget);
const resolved = normalizeTelegramChatId(String(chat?.id ?? ""));
if (!resolved) {
throw new Error(`resolved chat id is not numeric (${String(chat?.id ?? "")})`);
}
if (params.verbose) {
sendLogger.warn(`telegram recipient ${lookupTarget} resolved to numeric chat id ${resolved}`);
}
return resolved;
} catch (err) {
const detail = formatErrorMessage(err);
throw new Error(
`Telegram recipient ${lookupTarget} could not be resolved to a numeric chat ID (${detail})`,
{ cause: err },
);
}
}
async function resolveAndPersistChatId(params: {
cfg: OpenClawConfig;
api: TelegramApiOverride;
lookupTarget: string;
persistTarget: string;
verbose?: boolean;
gatewayClientScopes?: readonly string[];
}): Promise<string> {
const chatId = await resolveChatId(params.lookupTarget, {
api: params.api,
verbose: params.verbose,
});
await maybePersistResolvedTelegramTarget({
cfg: params.cfg,
rawTarget: params.persistTarget,
resolvedChatId: chatId,
verbose: params.verbose,
gatewayClientScopes: params.gatewayClientScopes,
});
return chatId;
}
function normalizeMessageId(raw: string | number): number {
if (typeof raw === "number" && Number.isFinite(raw)) {
return Math.trunc(raw);
}
if (typeof raw === "string") {
const value = raw.trim();
if (!value) {
throw new Error("Message id is required for Telegram actions");
}
const parsed = Number.parseInt(value, 10);
if (Number.isFinite(parsed)) {
return parsed;
}
}
throw new Error("Message id is required for Telegram actions");
}
function isTelegramThreadNotFoundError(err: unknown): boolean {
return THREAD_NOT_FOUND_RE.test(formatErrorMessage(err));
}
function isTelegramMessageNotModifiedError(err: unknown): boolean {
return MESSAGE_NOT_MODIFIED_RE.test(formatErrorMessage(err));
}
function isTelegramMessageDeleteNoopError(err: unknown): boolean {
return MESSAGE_DELETE_NOOP_RE.test(formatErrorMessage(err));
}
function hasMessageThreadIdParam(params?: TelegramThreadScopedParams): boolean {
if (!params) {
return false;
}
const value = params.message_thread_id;
if (typeof value === "number") {
return Number.isFinite(value);
}
return false;
}
function removeMessageThreadIdParam<TParams extends TelegramThreadScopedParams | undefined>(
params: TParams,
): TParams {
if (!params || !hasMessageThreadIdParam(params)) {
return params;
}
const next = { ...params };
delete next.message_thread_id;
return (Object.keys(next).length > 0 ? next : undefined) as TParams;
}
function isTelegramHtmlParseError(err: unknown): boolean {
return PARSE_ERR_RE.test(formatErrorMessage(err));
}
async function withTelegramHtmlParseFallback<T>(params: {
label: string;
verbose?: boolean;
requestHtml: (label: string) => Promise<T>;
requestPlain: (label: string) => Promise<T>;
}): Promise<T> {
try {
return await params.requestHtml(params.label);
} catch (err) {
if (!isTelegramHtmlParseError(err)) {
throw err;
}
if (params.verbose) {
sendLogger.warn(
`telegram ${params.label} failed with HTML parse error, retrying as plain text: ${formatErrorMessage(
err,
)}`,
);
}
return await params.requestPlain(`${params.label}-plain`);
}
}
type TelegramApiContext = {
cfg: OpenClawConfig;
account: ResolvedTelegramAccount;
api: TelegramApi;
};
function resolveTelegramApiContext(opts: {
token?: string;
accountId?: string;
api?: TelegramApiOverride;
cfg: OpenClawConfig;
}): TelegramApiContext {
const cfg = requireRuntimeConfig(opts.cfg, "Telegram API context");
const account = resolveTelegramAccount({
cfg,
accountId: opts.accountId,
});
const token = resolveToken(opts.token, account);
const client = resolveTelegramClientOptions(account);
let api: TelegramApi;
if (opts.api) {
api = opts.api as TelegramApi;
} else {
const bot = new Bot(token, client ? { client } : undefined);
bot.api.config.use(getOrCreateAccountThrottler(token));
api = bot.api;
}
return { cfg, account, api };
}
type TelegramRequestWithDiag = <T>(
fn: () => Promise<T>,
label?: string,
options?: { shouldLog?: (err: unknown) => boolean },
) => Promise<T>;
function createTelegramRequestWithDiag(params: {
cfg: OpenClawConfig;
account: ResolvedTelegramAccount;
retry?: RetryConfig;
verbose?: boolean;
shouldRetry?: (err: unknown) => boolean;
/** When true, the shouldRetry predicate is used exclusively without the TELEGRAM_RETRY_RE fallback. */
strictShouldRetry?: boolean;
useApiErrorLogging?: boolean;
}): TelegramRequestWithDiag {
const request = createTelegramRetryRunner({
retry: params.retry,
configRetry: params.account.config.retry,
verbose: params.verbose,
...(params.shouldRetry ? { shouldRetry: params.shouldRetry } : {}),
...(params.strictShouldRetry ? { strictShouldRetry: true } : {}),
});
const logHttpError = createTelegramHttpLogger(params.cfg);
return <T>(
fn: () => Promise<T>,
label?: string,
options?: { shouldLog?: (err: unknown) => boolean },
) => {
const runRequest = () => request(fn, label);
const call =
params.useApiErrorLogging === false
? runRequest()
: withTelegramApiErrorLogging({
operation: label ?? "request",
fn: runRequest,
...(options?.shouldLog ? { shouldLog: options.shouldLog } : {}),
});
return call.catch((err) => {
logHttpError(label ?? "request", err);
throw err;
});
};
}
function wrapTelegramChatNotFoundError(err: unknown, params: { chatId: string; input: string }) {
const errorMsg = formatErrorMessage(err);
// Check for 403 "bot is not a member" or "bot was blocked" errors
if (/403.*(bot.*not.*member|bot.*blocked|bot.*kicked)/i.test(errorMsg)) {
return new Error(
[
`Telegram send failed: bot is not a member of the chat, was blocked, or was kicked (chat_id=${params.chatId}).`,
`Telegram API said: ${errorMsg}.`,
"Fix: Add the bot to the channel/group, or ensure it has not been removed/blocked/kicked by the user.",
`Input was: ${JSON.stringify(params.input)}.`,
].join(" "),
);
}
if (!CHAT_NOT_FOUND_RE.test(errorMsg)) {
return err;
}
return new Error(
[
`Telegram send failed: chat not found (chat_id=${params.chatId}).`,
"Likely: bot not started in DM, bot removed from group/channel, group migrated (new -100… id), or wrong bot token.",
`Input was: ${JSON.stringify(params.input)}.`,
].join(" "),
);
}
async function withTelegramThreadFallback<
T,
TParams extends TelegramThreadScopedParams | undefined,
>(
params: TParams,
label: string,
verbose: boolean | undefined,
allowThreadlessRetry: boolean,
attempt: (effectiveParams: TParams, effectiveLabel: string) => Promise<T>,
): Promise<T> {
try {
return await attempt(params, label);
} catch (err) {
// Do not widen this fallback to cover "chat not found".
// chat-not-found is routing/auth/membership/token; stripping thread IDs hides root cause.
if (
!allowThreadlessRetry ||
!hasMessageThreadIdParam(params) ||
!isTelegramThreadNotFoundError(err)
) {
throw err;
}
if (verbose) {
sendLogger.warn(
`telegram ${label} failed with message_thread_id, retrying without thread: ${formatErrorMessage(err)}`,
);
}
const retriedParams = removeMessageThreadIdParam(params);
return await attempt(retriedParams, `${label}-threadless`);
}
}
function createRequestWithChatNotFound(params: {
requestWithDiag: TelegramRequestWithDiag;
chatId: string;
input: string;
}) {
return async <T>(fn: () => Promise<T>, label: string) =>
params.requestWithDiag(fn, label).catch((err) => {
throw wrapTelegramChatNotFoundError(err, {
chatId: params.chatId,
input: params.input,
});
});
}
function createTelegramNonIdempotentRequestWithDiag(params: {
cfg: OpenClawConfig;
account: ResolvedTelegramAccount;
retry?: RetryConfig;
verbose?: boolean;
useApiErrorLogging?: boolean;
}): TelegramRequestWithDiag {
return createTelegramRequestWithDiag({
cfg: params.cfg,
account: params.account,
retry: params.retry,
verbose: params.verbose,
useApiErrorLogging: params.useApiErrorLogging,
shouldRetry: (err) => isSafeToRetrySendError(err) || isTelegramRateLimitError(err),
strictShouldRetry: true,
});
}
export async function sendMessageTelegram(
to: string,
text: string,
opts: TelegramSendOpts,
): Promise<TelegramSendResult> {
const { cfg, account, api } = resolveTelegramApiContext(opts);
const target = parseTelegramTarget(to);
const chatId = await resolveAndPersistChatId({
cfg,
api,
lookupTarget: target.chatId,
persistTarget: to,
verbose: opts.verbose,
gatewayClientScopes: opts.gatewayClientScopes,
});
const mediaUrl = opts.mediaUrl?.trim();
const mediaMaxBytes =
opts.maxBytes ??
(typeof account.config.mediaMaxMb === "number" ? account.config.mediaMaxMb : 100) * 1024 * 1024;
const replyMarkup = buildInlineKeyboard(opts.buttons);
const threadParams = buildTelegramThreadReplyParams({
thread: resolveTelegramSendThreadSpec({
targetMessageThreadId: target.messageThreadId,
messageThreadId: opts.messageThreadId,
chatType: target.chatType,
}),
replyToMessageId: opts.replyToMessageId,
replyQuoteText: opts.quoteText,
useReplyIdAsQuoteSource: true,
});
const hasThreadParams = Object.keys(threadParams).length > 0;
const requestWithDiag = createTelegramNonIdempotentRequestWithDiag({
cfg,
account,
retry: opts.retry,
verbose: opts.verbose,
});
const requestWithChatNotFound = createRequestWithChatNotFound({
requestWithDiag,
chatId,
input: to,
});
const textMode = opts.textMode ?? "markdown";
const tableMode = resolveMarkdownTableMode({
cfg,
channel: "telegram",
accountId: account.accountId,
});
const renderHtmlText = (value: string) => renderTelegramHtmlText(value, { textMode, tableMode });
// Resolve link preview setting from config (default: enabled).
const linkPreviewEnabled = account.config.linkPreview ?? true;
const linkPreviewOptions = linkPreviewEnabled ? undefined : { is_disabled: true };
type TelegramTextChunk = {
plainText: string;
htmlText?: string;
};
const sendTelegramTextChunk = async (
chunk: TelegramTextChunk,
params?: TelegramSendMessageParams,
) => {
return await withTelegramThreadFallback(
params,
"message",
opts.verbose,
target.chatType !== "direct",
async (effectiveParams, label) => {
const baseParams = effectiveParams ? { ...effectiveParams } : {};
if (linkPreviewOptions) {
baseParams.link_preview_options = linkPreviewOptions;
}
const plainParams: TelegramSendMessageParams = {
...baseParams,
...(opts.silent === true ? { disable_notification: true } : {}),
};
const hasPlainParams = Object.keys(plainParams).length > 0;
const requestPlain = (retryLabel: string) =>
requestWithChatNotFound(
() =>
hasPlainParams
? api.sendMessage(chatId, chunk.plainText, plainParams)
: api.sendMessage(chatId, chunk.plainText),
retryLabel,
);
if (!chunk.htmlText) {
return await requestPlain(label);
}
const htmlText = chunk.htmlText;
const htmlParams: TelegramSendMessageParams = {
parse_mode: "HTML" as const,
...plainParams,
};
return await withTelegramHtmlParseFallback({
label,
verbose: opts.verbose,
requestHtml: (retryLabel) =>
requestWithChatNotFound(
() => api.sendMessage(chatId, htmlText, htmlParams),
retryLabel,
),
requestPlain,
});
},
);
};
const buildTextParams = (isLastChunk: boolean) =>
hasThreadParams || (isLastChunk && replyMarkup)
? {
...threadParams,
...(isLastChunk && replyMarkup ? { reply_markup: replyMarkup } : {}),
}
: undefined;
const sendTelegramTextChunks = async (
chunks: TelegramTextChunk[],
context: string,
): Promise<{ messageId: string; chatId: string }> => {
let lastMessageId = "";
let lastChatId = chatId;
let sentChunkCount = 0;
for (let index = 0; index < chunks.length; index += 1) {
const chunk = chunks[index];
if (!chunk) {
continue;
}
const res = await sendTelegramTextChunk(chunk, buildTextParams(index === chunks.length - 1));
const messageId = resolveTelegramMessageIdOrThrow(res, context);
recordSentMessage(chatId, messageId, cfg);
lastMessageId = String(messageId);
lastChatId = String(res?.chat?.id ?? chatId);
sentChunkCount += 1;
}
if (lastMessageId) {
logTelegramOutboundSendOk({
accountId: account.accountId,
chatId: lastChatId,
messageId: lastMessageId,
operation: "sendMessage",
deliveryKind: "text",
messageThreadId: threadParams.message_thread_id,
replyToMessageId: opts.replyToMessageId,
silent: opts.silent,
chunkCount: sentChunkCount,
});
}
return { messageId: lastMessageId, chatId: lastChatId };
};
const buildChunkedTextPlan = (rawText: string, context: string): TelegramTextChunk[] => {
const htmlText = renderHtmlText(rawText);
const fallbackText =
opts.plainText ?? (textMode === "html" ? telegramHtmlToPlainTextFallback(htmlText) : rawText);
let htmlChunks: string[];
try {
htmlChunks = splitTelegramHtmlChunks(htmlText, 4000);
} catch (error) {
logVerbose(
`telegram ${context} failed HTML chunk planning, retrying as plain text: ${formatErrorMessage(
error,
)}`,
);
return splitTelegramPlainTextChunks(fallbackText, 4000).map((plainText) => ({ plainText }));
}
const fixedPlainTextChunks = splitTelegramPlainTextChunks(fallbackText, 4000);
if (fixedPlainTextChunks.length > htmlChunks.length) {
logVerbose(
`telegram ${context} plain-text fallback needs more chunks than HTML; sending plain text`,
);
return fixedPlainTextChunks.map((plainText) => ({ plainText }));
}
const plainTextChunks = splitTelegramPlainTextFallback(fallbackText, htmlChunks.length, 4000);
return htmlChunks.map((htmlText, index) => ({
htmlText,
plainText: plainTextChunks[index] ?? htmlText,
}));
};
const sendChunkedText = async (rawText: string, context: string) =>
await sendTelegramTextChunks(buildChunkedTextPlan(rawText, context), context);
async function shouldSendTelegramImageAsPhoto(buffer: Buffer): Promise<boolean> {
try {
const metadata = await getImageMetadata(buffer);
const width = metadata?.width;
const height = metadata?.height;
if (typeof width !== "number" || typeof height !== "number") {
sendLogger.warn("Photo dimensions are unavailable. Sending as document instead.");
return false;
}
const shorterSide = Math.min(width, height);
const longerSide = Math.max(width, height);
const isValidPhoto =
width + height <= MAX_TELEGRAM_PHOTO_DIMENSION_SUM &&
shorterSide > 0 &&
longerSide <= shorterSide * MAX_TELEGRAM_PHOTO_ASPECT_RATIO;
if (!isValidPhoto) {
sendLogger.warn(
`Photo dimensions (${width}x${height}) are not valid for Telegram photos. Sending as document instead.`,
);
return false;
}
return true;
} catch (err) {
sendLogger.warn(
`Failed to validate photo dimensions: ${formatErrorMessage(err)}. Sending as document instead.`,
);
return false;
}
}
if (mediaUrl) {
const media = await loadWebMedia(
mediaUrl,
buildOutboundMediaLoadOptions({
maxBytes: mediaMaxBytes,
mediaLocalRoots: opts.mediaLocalRoots,
mediaReadFile: opts.mediaReadFile,
optimizeImages: opts.forceDocument ? false : undefined,
}),
);
const kind = kindFromMime(media.contentType ?? undefined);
const isGif = isGifMedia({
contentType: media.contentType,
fileName: media.fileName,
});
let sendImageAsPhoto = true;
const deliveryKind =
opts.forceDocument === true && (kind === "image" || kind === "video") ? "document" : kind;
if (deliveryKind === "image" && !isGif) {
sendImageAsPhoto = await shouldSendTelegramImageAsPhoto(media.buffer);
}
const isVideoNote = deliveryKind === "video" && opts.asVideoNote === true;
const fileName =
media.fileName ?? (isGif ? "animation.gif" : inferFilename(kind ?? "document")) ?? "file";
const file = new InputFileCtor(media.buffer, fileName);
let caption: string | undefined;
let followUpText: string | undefined;
if (isVideoNote) {
caption = undefined;
followUpText = text.trim() ? text : undefined;
} else {
const split = splitTelegramCaption(text);
caption = split.caption;
followUpText = split.followUpText;
}
const htmlCaption = caption ? renderHtmlText(caption) : undefined;
// If text exceeds Telegram's caption limit, send media without caption
// then send text as a separate follow-up message.
const needsSeparateText = Boolean(followUpText);
// When splitting, put reply_markup only on the follow-up text (the "main" content),
// not on the media message.
const baseMediaParams = {
...(hasThreadParams ? threadParams : {}),
...(!needsSeparateText && replyMarkup ? { reply_markup: replyMarkup } : {}),
};
const videoDimensions =
deliveryKind === "video" && !isVideoNote
? await probeVideoDimensions(media.buffer)
: undefined;
const mediaParams = {
...(htmlCaption ? { caption: htmlCaption, parse_mode: "HTML" as const } : {}),
...baseMediaParams,
...(opts.silent === true ? { disable_notification: true } : {}),
...(videoDimensions ? { width: videoDimensions.width, height: videoDimensions.height } : {}),
};
const sendMedia = async (
label: string,
sender: (
effectiveParams: TelegramThreadScopedParams | undefined,
) => Promise<TelegramMessageLike>,
) =>
await withTelegramThreadFallback(
mediaParams,
label,
opts.verbose,
target.chatType !== "direct",
async (effectiveParams, retryLabel) =>
requestWithChatNotFound(() => sender(effectiveParams), retryLabel),
);
const mediaSender = (() => {
if (isGif && deliveryKind !== "document") {
return {
label: "animation",
sender: (effectiveParams: TelegramThreadScopedParams | undefined) =>
api.sendAnimation(
chatId,
file,
effectiveParams as Parameters<typeof api.sendAnimation>[2],
) as Promise<TelegramMessageLike>,
};
}
if (deliveryKind === "image" && !isGif && sendImageAsPhoto) {
return {
label: "photo",
sender: (effectiveParams: TelegramThreadScopedParams | undefined) =>
api.sendPhoto(
chatId,
file,
effectiveParams as Parameters<typeof api.sendPhoto>[2],
) as Promise<TelegramMessageLike>,
};
}
if (deliveryKind === "video") {
if (isVideoNote) {
return {
label: "video_note",
sender: (effectiveParams: TelegramThreadScopedParams | undefined) =>
api.sendVideoNote(
chatId,
file,
effectiveParams as Parameters<typeof api.sendVideoNote>[2],
) as Promise<TelegramMessageLike>,
};
}
return {
label: "video",
sender: (effectiveParams: TelegramThreadScopedParams | undefined) =>
api.sendVideo(
chatId,
file,
effectiveParams as Parameters<typeof api.sendVideo>[2],
) as Promise<TelegramMessageLike>,
};
}
if (kind === "audio") {
const { useVoice } = resolveTelegramVoiceSend({
wantsVoice: opts.asVoice === true, // default false (backward compatible)
contentType: media.contentType,
fileName,
logFallback: logVerbose,
});
if (useVoice) {
return {
label: "voice",
sender: (effectiveParams: TelegramThreadScopedParams | undefined) =>
api.sendVoice(
chatId,
file,
effectiveParams as Parameters<typeof api.sendVoice>[2],
) as Promise<TelegramMessageLike>,
};
}
return {
label: "audio",
sender: (effectiveParams: TelegramThreadScopedParams | undefined) =>
api.sendAudio(
chatId,
file,