-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathtelegram.ts
More file actions
858 lines (753 loc) · 29.9 KB
/
telegram.ts
File metadata and controls
858 lines (753 loc) · 29.9 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
import { ensureProjectClaudeMd, run, runUserMessage } from "../runner";
import { getSettings, loadSettings } from "../config";
import { resetSession } from "../sessions";
import { transcribeAudioToText } from "../whisper";
import { resolveSkillPrompt, listSkills } from "../skills";
import { mkdir } from "node:fs/promises";
import { existsSync } from "node:fs";
import { extname, join } from "node:path";
// --- Markdown → Telegram HTML conversion (ported from nanobot) ---
function markdownToTelegramHtml(text: string): string {
if (!text) return "";
// 1. Extract and protect code blocks
const codeBlocks: string[] = [];
text = text.replace(/```[\w]*\n?([\s\S]*?)```/g, (_m, code) => {
codeBlocks.push(code);
return `\x00CB${codeBlocks.length - 1}\x00`;
});
// 2. Extract and protect inline code
const inlineCodes: string[] = [];
text = text.replace(/`([^`]+)`/g, (_m, code) => {
inlineCodes.push(code);
return `\x00IC${inlineCodes.length - 1}\x00`;
});
// 3. Strip markdown headers
text = text.replace(/^#{1,6}\s+(.+)$/gm, "$1");
// 4. Strip blockquotes
text = text.replace(/^>\s*(.*)$/gm, "$1");
// 5. Escape HTML special characters
text = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
// 6. Links [text](url) — before bold/italic to handle nested cases
text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
// 7. Bold **text** or __text__
text = text.replace(/\*\*(.+?)\*\*/g, "<b>$1</b>");
text = text.replace(/__(.+?)__/g, "<b>$1</b>");
// 8. Italic _text_ (avoid matching inside words like some_var_name)
text = text.replace(/(?<![a-zA-Z0-9])_([^_]+)_(?![a-zA-Z0-9])/g, "<i>$1</i>");
// 9. Strikethrough ~~text~~
text = text.replace(/~~(.+?)~~/g, "<s>$1</s>");
// 10. Bullet lists
text = text.replace(/^[-*]\s+/gm, "• ");
// 11. Restore inline code with HTML tags
for (let i = 0; i < inlineCodes.length; i++) {
const escaped = inlineCodes[i].replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
text = text.replace(`\x00IC${i}\x00`, `<code>${escaped}</code>`);
}
// 12. Restore code blocks with HTML tags
for (let i = 0; i < codeBlocks.length; i++) {
const escaped = codeBlocks[i].replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
text = text.replace(`\x00CB${i}\x00`, `<pre><code>${escaped}</code></pre>`);
}
return text;
}
// --- Telegram Bot API (raw fetch, zero deps) ---
const API_BASE = "https://api.telegram.org/bot";
const FILE_API_BASE = "https://api.telegram.org/file/bot";
interface TelegramUser {
id: number;
first_name: string;
username?: string;
}
interface TelegramMessage {
message_id: number;
from?: TelegramUser;
reply_to_message?: { message_id?: number; from?: TelegramUser };
chat: { id: number; type: string };
message_thread_id?: number;
text?: string;
caption?: string;
photo?: TelegramPhotoSize[];
document?: TelegramDocument;
voice?: TelegramVoice;
audio?: TelegramAudio;
entities?: Array<{
type: "mention" | "bot_command" | string;
offset: number;
length: number;
}>;
caption_entities?: Array<{
type: "mention" | "bot_command" | string;
offset: number;
length: number;
}>;
}
interface TelegramPhotoSize {
file_id: string;
width: number;
height: number;
file_size?: number;
}
interface TelegramDocument {
file_id: string;
file_name?: string;
mime_type?: string;
file_size?: number;
}
interface TelegramVoice {
file_id: string;
mime_type?: string;
duration?: number;
file_size?: number;
}
interface TelegramAudio {
file_id: string;
mime_type?: string;
duration?: number;
file_name?: string;
file_size?: number;
}
interface TelegramChatMember {
user: TelegramUser;
status: "creator" | "administrator" | "member" | "restricted" | "left" | "kicked";
}
interface TelegramMyChatMemberUpdate {
chat: { id: number; type: string; title?: string };
from: TelegramUser;
old_chat_member: TelegramChatMember;
new_chat_member: TelegramChatMember;
}
interface TelegramCallbackQuery {
id: string;
from: TelegramUser;
message?: TelegramMessage;
data?: string;
}
interface TelegramUpdate {
update_id: number;
message?: TelegramMessage;
edited_message?: TelegramMessage;
channel_post?: TelegramMessage;
edited_channel_post?: TelegramMessage;
my_chat_member?: TelegramMyChatMemberUpdate;
callback_query?: TelegramCallbackQuery;
}
interface TelegramMe {
id: number;
username?: string;
can_read_all_group_messages?: boolean;
}
interface TelegramFile {
file_path?: string;
}
let telegramDebug = false;
function debugLog(message: string): void {
if (!telegramDebug) return;
console.log(`[Telegram][debug] ${message}`);
}
function normalizeTelegramText(text: string): string {
return text.replace(/[\u2010-\u2015\u2212]/g, "-");
}
function getMessageTextAndEntities(message: TelegramMessage): {
text: string;
entities: TelegramMessage["entities"];
} {
if (message.text) {
return {
text: normalizeTelegramText(message.text),
entities: message.entities,
};
}
if (message.caption) {
return {
text: normalizeTelegramText(message.caption),
entities: message.caption_entities,
};
}
return { text: "", entities: [] };
}
function isImageDocument(document?: TelegramDocument): boolean {
return Boolean(document?.mime_type?.startsWith("image/"));
}
function isAudioDocument(document?: TelegramDocument): boolean {
return Boolean(document?.mime_type?.startsWith("audio/"));
}
function pickLargestPhoto(photo: TelegramPhotoSize[]): TelegramPhotoSize {
return [...photo].sort((a, b) => {
const sizeA = a.file_size ?? a.width * a.height;
const sizeB = b.file_size ?? b.width * b.height;
return sizeB - sizeA;
})[0];
}
function extensionFromMimeType(mimeType?: string): string {
switch (mimeType) {
case "image/jpeg":
return ".jpg";
case "image/png":
return ".png";
case "image/webp":
return ".webp";
case "image/gif":
return ".gif";
case "image/bmp":
return ".bmp";
default:
return "";
}
}
function extensionFromAudioMimeType(mimeType?: string): string {
switch (mimeType) {
case "audio/mpeg":
return ".mp3";
case "audio/mp4":
case "audio/x-m4a":
return ".m4a";
case "audio/ogg":
return ".ogg";
case "audio/wav":
case "audio/x-wav":
return ".wav";
case "audio/webm":
return ".webm";
default:
return "";
}
}
function extractTelegramCommand(text: string): string | null {
const firstToken = text.trim().split(/\s+/, 1)[0];
if (!firstToken.startsWith("/")) return null;
return firstToken.split("@", 1)[0].toLowerCase();
}
async function callApi<T>(token: string, method: string, body?: Record<string, unknown>): Promise<T> {
const res = await fetch(`${API_BASE}${token}/${method}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
if (!res.ok) {
throw new Error(`Telegram API ${method}: ${res.status} ${res.statusText}`);
}
return (await res.json()) as T;
}
async function sendMessage(token: string, chatId: number, text: string, threadId?: number): Promise<void> {
const normalized = normalizeTelegramText(text).replace(/\[react:[^\]\r\n]+\]/gi, "");
const html = markdownToTelegramHtml(normalized);
const MAX_LEN = 4096;
for (let i = 0; i < html.length; i += MAX_LEN) {
try {
await callApi(token, "sendMessage", {
chat_id: chatId,
text: html.slice(i, i + MAX_LEN),
parse_mode: "HTML",
...(threadId ? { message_thread_id: threadId } : {}),
});
} catch {
// Fallback to plain text if HTML parsing fails
await callApi(token, "sendMessage", {
chat_id: chatId,
text: normalized.slice(i, i + MAX_LEN),
...(threadId ? { message_thread_id: threadId } : {}),
});
}
}
}
async function sendTyping(token: string, chatId: number, threadId?: number): Promise<void> {
await callApi(token, "sendChatAction", {
chat_id: chatId,
action: "typing",
...(threadId ? { message_thread_id: threadId } : {}),
}).catch(() => {});
}
function extractReactionDirective(text: string): { cleanedText: string; reactionEmoji: string | null } {
let reactionEmoji: string | null = null;
const cleanedText = text
.replace(/\[react:([^\]\r\n]+)\]/gi, (_match, raw) => {
const candidate = String(raw).trim();
if (!reactionEmoji && candidate) reactionEmoji = candidate;
return "";
})
.replace(/[ \t]+\n/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
return { cleanedText, reactionEmoji };
}
const VOICE_DIRECTIVE_RE = /\[voice:(\/[^\]\r\n]+)\]/gi;
function extractVoiceDirectives(text: string): { cleanedText: string; voicePaths: string[] } {
const voicePaths: string[] = [];
const cleanedText = text
.replace(VOICE_DIRECTIVE_RE, (_match, path) => {
const p = String(path).trim();
if (p && existsSync(p)) voicePaths.push(p);
return "";
})
.replace(/[ \t]+\n/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
return { cleanedText, voicePaths };
}
async function sendVoiceMessage(token: string, chatId: number, voicePath: string, threadId?: number): Promise<void> {
const form = new FormData();
form.append("chat_id", String(chatId));
if (threadId) form.append("message_thread_id", String(threadId));
const file = Bun.file(voicePath);
form.append("voice", file, voicePath.split("/").pop() ?? "voice.ogg");
const res = await fetch(`${API_BASE}${token}/sendVoice`, {
method: "POST",
body: form,
});
if (!res.ok) {
const body = await res.text();
throw new Error(`Telegram sendVoice: ${res.status} ${res.statusText} — ${body}`);
}
}
async function sendReaction(token: string, chatId: number, messageId: number, emoji: string): Promise<void> {
await callApi(token, "setMessageReaction", {
chat_id: chatId,
message_id: messageId,
reaction: [{ type: "emoji", emoji }],
});
}
let botUsername: string | null = null;
let botId: number | null = null;
function groupTriggerReason(message: TelegramMessage): string | null {
if (botId && message.reply_to_message?.from?.id === botId) return "reply_to_bot";
const { text, entities } = getMessageTextAndEntities(message);
if (!text) return null;
const lowerText = text.toLowerCase();
if (botUsername && lowerText.includes(`@${botUsername.toLowerCase()}`)) return "text_contains_mention";
for (const entity of entities ?? []) {
const value = text.slice(entity.offset, entity.offset + entity.length);
if (entity.type === "mention" && botUsername && value.toLowerCase() === `@${botUsername.toLowerCase()}`) {
return "mention_entity_matches_bot";
}
if (entity.type === "mention" && !botUsername) return "mention_entity_before_botname_loaded";
if (entity.type === "bot_command") {
if (!value.includes("@")) return "bare_bot_command";
if (!botUsername) return "scoped_command_before_botname_loaded";
if (botUsername && value.toLowerCase().endsWith(`@${botUsername.toLowerCase()}`)) return "scoped_command_matches_bot";
}
}
return null;
}
async function downloadImageFromMessage(token: string, message: TelegramMessage): Promise<string | null> {
const photo = message.photo && message.photo.length > 0 ? pickLargestPhoto(message.photo) : null;
const imageDocument = isImageDocument(message.document) ? message.document : null;
const fileId = photo?.file_id ?? imageDocument?.file_id;
if (!fileId) return null;
const fileMeta = await callApi<{ ok: boolean; result: TelegramFile }>(token, "getFile", { file_id: fileId });
if (!fileMeta.ok || !fileMeta.result.file_path) return null;
const remotePath = fileMeta.result.file_path;
const downloadUrl = `${FILE_API_BASE}${token}/${remotePath}`;
const response = await fetch(downloadUrl);
if (!response.ok) throw new Error(`Telegram file download failed: ${response.status} ${response.statusText}`);
const dir = join(process.cwd(), ".claude", "claudeclaw", "inbox", "telegram");
await mkdir(dir, { recursive: true });
const remoteExt = extname(remotePath);
const docExt = extname(imageDocument?.file_name ?? "");
const mimeExt = extensionFromMimeType(imageDocument?.mime_type);
const ext = remoteExt || docExt || mimeExt || ".jpg";
const filename = `${message.chat.id}-${message.message_id}-${Date.now()}${ext}`;
const localPath = join(dir, filename);
const bytes = new Uint8Array(await response.arrayBuffer());
await Bun.write(localPath, bytes);
return localPath;
}
async function downloadVoiceFromMessage(token: string, message: TelegramMessage): Promise<string | null> {
const audioDocument = isAudioDocument(message.document) ? message.document : null;
const audioLike = message.voice ?? message.audio ?? audioDocument;
const fileId = audioLike?.file_id;
if (!fileId) return null;
const fileMeta = await callApi<{ ok: boolean; result: TelegramFile }>(token, "getFile", { file_id: fileId });
if (!fileMeta.ok || !fileMeta.result.file_path) return null;
const remotePath = fileMeta.result.file_path;
const downloadUrl = `${FILE_API_BASE}${token}/${remotePath}`;
debugLog(
`Voice download: fileId=${fileId} remotePath=${remotePath} mime=${audioLike.mime_type ?? "unknown"} expectedSize=${audioLike.file_size ?? "unknown"}`
);
const response = await fetch(downloadUrl);
if (!response.ok) throw new Error(`Telegram file download failed: ${response.status} ${response.statusText}`);
const dir = join(process.cwd(), ".claude", "claudeclaw", "inbox", "telegram");
await mkdir(dir, { recursive: true });
const remoteExt = extname(remotePath);
const docExt = extname(message.document?.file_name ?? "");
const audioExt = extname(message.audio?.file_name ?? "");
const mimeExt = extensionFromAudioMimeType(audioLike.mime_type);
const ext = remoteExt || docExt || audioExt || mimeExt || ".ogg";
const filename = `${message.chat.id}-${message.message_id}-${Date.now()}${ext}`;
const localPath = join(dir, filename);
const bytes = new Uint8Array(await response.arrayBuffer());
await Bun.write(localPath, bytes);
const header = Array.from(bytes.slice(0, 8))
.map((b) => b.toString(16).padStart(2, "0"))
.join(" ");
const oggMagic =
bytes.length >= 4 &&
bytes[0] === 0x4f &&
bytes[1] === 0x67 &&
bytes[2] === 0x67 &&
bytes[3] === 0x53;
debugLog(
`Voice download: wrote ${bytes.length} bytes to ${localPath} ext=${ext} header=${header || "empty"} oggMagic=${oggMagic}`
);
return localPath;
}
async function handleMyChatMember(update: TelegramMyChatMemberUpdate): Promise<void> {
const config = getSettings().telegram;
const chat = update.chat;
if (!botUsername && update.new_chat_member.user.username) botUsername = update.new_chat_member.user.username;
if (!botId) botId = update.new_chat_member.user.id;
const oldStatus = update.old_chat_member.status;
const newStatus = update.new_chat_member.status;
const isGroup = chat.type === "group" || chat.type === "supergroup";
const wasOut = oldStatus === "left" || oldStatus === "kicked";
const isIn = newStatus === "member" || newStatus === "administrator";
if (!isGroup || !wasOut || !isIn) return;
const chatName = chat.title ?? String(chat.id);
console.log(`[Telegram] Added to ${chat.type}: ${chatName} (${chat.id}) by ${update.from.id}`);
const addedBy = update.from.username ?? `${update.from.first_name} (${update.from.id})`;
const eventPrompt =
`[Telegram system event] I was added to a ${chat.type}.\n` +
`Group title: ${chatName}\n` +
`Group id: ${chat.id}\n` +
`Added by: ${addedBy}\n` +
"Write a short first message for the group. It should confirm I was added and explain how to trigger me.";
try {
const result = await run("telegram", eventPrompt);
if (result.exitCode !== 0) {
await sendMessage(config.token, chat.id, "I was added to this group. Mention me with a command to start.");
return;
}
await sendMessage(config.token, chat.id, result.stdout || "I was added to this group.");
} catch (err) {
console.error(`[Telegram] group-added event error: ${err instanceof Error ? err.message : err}`);
await sendMessage(config.token, chat.id, "I was added to this group. Mention me with a command to start.");
}
}
// --- Message handler ---
async function handleMessage(message: TelegramMessage): Promise<void> {
const config = getSettings().telegram;
const userId = message.from?.id;
const chatId = message.chat.id;
const threadId = message.message_thread_id;
const { text } = getMessageTextAndEntities(message);
const chatType = message.chat.type;
const isPrivate = chatType === "private";
const isGroup = chatType === "group" || chatType === "supergroup";
const hasImage = Boolean((message.photo && message.photo.length > 0) || isImageDocument(message.document));
const hasVoice = Boolean(message.voice || message.audio || isAudioDocument(message.document));
if (!isPrivate && !isGroup) return;
const triggerReason = isGroup ? groupTriggerReason(message) : "private_chat";
if (isGroup && !triggerReason) {
debugLog(
`Skip group message chat=${chatId} from=${userId ?? "unknown"} reason=no_trigger text="${(text ?? "").slice(0, 80)}"`
);
return;
}
debugLog(
`Handle message chat=${chatId} type=${chatType} from=${userId ?? "unknown"} reason=${triggerReason} text="${(text ?? "").slice(0, 80)}"`
);
if (userId && config.allowedUserIds.length > 0 && !config.allowedUserIds.includes(userId)) {
if (isPrivate) {
await sendMessage(config.token, chatId, "Unauthorized.");
} else {
console.log(`[Telegram] Ignored group message from unauthorized user ${userId} in chat ${chatId}`);
debugLog(`Skip group message chat=${chatId} from=${userId} reason=unauthorized_user`);
}
return;
}
if (!text.trim() && !hasImage && !hasVoice) {
debugLog(`Skip message chat=${chatId} from=${userId ?? "unknown"} reason=empty_text`);
return;
}
const command = text ? extractTelegramCommand(text) : null;
if (command === "/start") {
await sendMessage(
config.token,
chatId,
"Hello! Send me a message and I'll respond using Claude.\nUse /reset to start a fresh session.",
threadId
);
return;
}
if (command === "/reset") {
await resetSession();
await sendMessage(config.token, chatId, "Global session reset. Next message starts fresh.", threadId);
return;
}
// Secretary: detect reply to a bot alert message → treat as custom reply
const replyToMsgId = message.reply_to_message?.message_id;
if (replyToMsgId && text && botId && message.reply_to_message?.from?.id === botId) {
try {
const lookupResp = await fetch(`http://127.0.0.1:9999/pending/by-bot-msg/${replyToMsgId}`);
if (lookupResp.ok) {
const item = await lookupResp.json() as { id?: string } | null;
if (item?.id) {
await fetch(`http://127.0.0.1:9999/confirm/${item.id}/custom`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text }),
});
await sendMessage(config.token, chatId, `✅ Sent custom reply + pattern learned.`, threadId);
return;
}
}
} catch {
// fall through to normal handling if secretary endpoint unreachable
}
}
const label = message.from?.username ?? String(userId ?? "unknown");
const mediaParts = [hasImage ? "image" : "", hasVoice ? "voice" : ""].filter(Boolean);
const mediaSuffix = mediaParts.length > 0 ? ` [${mediaParts.join("+")}]` : "";
console.log(
`[${new Date().toLocaleTimeString()}] Telegram ${label}${mediaSuffix}: "${text.slice(0, 60)}${text.length > 60 ? "..." : ""}"`
);
// Keep typing indicator alive while queued/running
const typingInterval = setInterval(() => sendTyping(config.token, chatId, threadId), 4000);
try {
await sendTyping(config.token, chatId, threadId);
let imagePath: string | null = null;
let voicePath: string | null = null;
let voiceTranscript: string | null = null;
if (hasImage) {
try {
imagePath = await downloadImageFromMessage(config.token, message);
} catch (err) {
console.error(`[Telegram] Failed to download image for ${label}: ${err instanceof Error ? err.message : err}`);
}
}
if (hasVoice) {
try {
voicePath = await downloadVoiceFromMessage(config.token, message);
} catch (err) {
console.error(`[Telegram] Failed to download voice for ${label}: ${err instanceof Error ? err.message : err}`);
}
if (voicePath) {
try {
debugLog(`Voice file saved: path=${voicePath}`);
voiceTranscript = await transcribeAudioToText(voicePath, {
debug: telegramDebug,
log: (message) => debugLog(message),
});
} catch (err) {
console.error(`[Telegram] Failed to transcribe voice for ${label}: ${err instanceof Error ? err.message : err}`);
}
}
}
// Skill routing: resolve slash commands to SKILL.md prompts
let skillContext: string | null = null;
if (command && command !== "/start" && command !== "/reset") {
try {
skillContext = await resolveSkillPrompt(command);
if (skillContext) {
debugLog(`Skill resolved for ${command}: ${skillContext.length} chars`);
}
} catch (err) {
debugLog(`Skill resolution failed for ${command}: ${err instanceof Error ? err.message : err}`);
}
}
const promptParts = [`[Telegram from ${label}]`];
if (threadId) promptParts.push(`[thread:${threadId}]`);
if (skillContext) {
// Strip the slash command from the message text and pass remaining args
const args = text.trim().slice(command!.length).trim();
promptParts.push(`<command-name>${command}</command-name>`);
promptParts.push(skillContext);
if (args) promptParts.push(`User arguments: ${args}`);
} else if (text.trim()) {
promptParts.push(`Message: ${text}`);
}
if (imagePath) {
promptParts.push(`Image path: ${imagePath}`);
promptParts.push("The user attached an image. Inspect this image file directly before answering.");
} else if (hasImage) {
promptParts.push("The user attached an image, but downloading it failed. Respond and ask them to resend.");
}
if (voiceTranscript) {
promptParts.push(`Voice transcript: ${voiceTranscript}`);
promptParts.push("The user attached voice audio. Use the transcript as their spoken message.");
} else if (hasVoice) {
promptParts.push(
"The user attached voice audio, but it could not be transcribed. Respond and ask them to resend a clearer clip."
);
}
const prefixedPrompt = promptParts.join("\n");
const result = await runUserMessage("telegram", prefixedPrompt);
if (result.exitCode !== 0) {
await sendMessage(config.token, chatId, `Error (exit ${result.exitCode}): ${result.stderr || "Unknown error"}`, threadId);
} else {
const { cleanedText: textAfterReact, reactionEmoji } = extractReactionDirective(result.stdout || "");
const { cleanedText, voicePaths } = extractVoiceDirectives(textAfterReact);
if (reactionEmoji) {
await sendReaction(config.token, chatId, message.message_id, reactionEmoji).catch((err) => {
console.error(`[Telegram] Failed to send reaction for ${label}: ${err instanceof Error ? err.message : err}`);
});
}
for (const vp of voicePaths) {
try {
await sendVoiceMessage(config.token, chatId, vp, threadId);
debugLog(`Voice sent: ${vp}`);
} catch (err) {
console.error(`[Telegram] Failed to send voice ${vp} for ${label}: ${err instanceof Error ? err.message : err}`);
}
}
if (cleanedText) {
await sendMessage(config.token, chatId, cleanedText, threadId);
} else if (voicePaths.length === 0) {
await sendMessage(config.token, chatId, "(empty response)", threadId);
}
}
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err);
console.error(`[Telegram] Error for ${label}: ${errMsg}`);
await sendMessage(config.token, chatId, `Error: ${errMsg}`, threadId);
} finally {
clearInterval(typingInterval);
}
}
// --- Callback query handler ---
async function handleCallbackQuery(query: TelegramCallbackQuery): Promise<void> {
const config = getSettings().telegram;
const data = query.data ?? "";
// Secretary pattern: "sec_yes_<8hex>" or "sec_no_<8hex>"
const secMatch = data.match(/^sec_(yes|no)_([0-9a-f]{8})$/);
if (secMatch) {
const action = secMatch[1];
const pendingId = secMatch[2];
let answerText = "⚠️ Server error";
try {
const resp = await fetch(`http://127.0.0.1:9999/confirm/${pendingId}/${action}`);
const result = await resp.json() as { ok: boolean };
answerText = action === "yes" && result.ok ? "✅ Đã gửi!" : result.ok ? "❌ Dismissed" : "⚠️ Not found";
if (query.message) {
const statusLine = action === "yes" ? "\n\n✅ Sent" : "\n\n❌ Dismissed";
const newText = (query.message.text ?? "").replace(/\n\nReply:.*$/s, statusLine);
await callApi(config.token, "editMessageText", {
chat_id: query.message.chat.id,
message_id: query.message.message_id,
text: newText,
}).catch(() => {});
}
} catch {
// server not running or error
}
await callApi(config.token, "answerCallbackQuery", {
callback_query_id: query.id,
text: answerText,
}).catch(() => {});
return;
}
// Default: ack with no text
await callApi(config.token, "answerCallbackQuery", { callback_query_id: query.id }).catch(() => {});
}
// --- Bot command menu registration ---
async function registerBotCommands(token: string): Promise<void> {
try {
const skills = await listSkills();
const commands = [
{ command: "start", description: "Show welcome message" },
{ command: "reset", description: "Reset session and start fresh" },
];
for (const skill of skills) {
// Telegram commands: 1-32 chars, lowercase a-z, 0-9, underscores only
const cmd = skill.name
.toLowerCase()
.replace(/[-.:]/g, "_")
.replace(/[^a-z0-9_]/g, "")
.slice(0, 32);
if (!cmd || cmd === "start" || cmd === "reset") continue;
if (cmd.length > 30) continue;
const desc = skill.description.length >= 3
? skill.description.slice(0, 256)
: `Run ${skill.name} skill`;
commands.push({ command: cmd, description: desc });
}
if (commands.length > 100) commands.length = 100;
await callApi(token, "setMyCommands", { commands });
console.log(` Commands registered: ${commands.length} (${commands.map((c) => "/" + c.command).join(", ")})`);
} catch (err) {
console.error(`[Telegram] Failed to register commands: ${err instanceof Error ? err.message : err}`);
}
}
// --- Polling loop ---
let running = true;
async function poll(): Promise<void> {
const config = getSettings().telegram;
let offset = 0;
try {
const me = await callApi<{ ok: boolean; result: TelegramMe }>(config.token, "getMe");
if (me.ok) {
botUsername = me.result.username ?? null;
botId = me.result.id;
console.log(` Bot: ${botUsername ? `@${botUsername}` : botId}`);
console.log(` Group privacy: ${me.result.can_read_all_group_messages ? "disabled (reads all messages)" : "enabled (commands & mentions only)"}`);
}
} catch (err) {
console.error(`[Telegram] getMe failed: ${err instanceof Error ? err.message : err}`);
}
console.log("Telegram bot started (long polling)");
console.log(` Allowed users: ${config.allowedUserIds.length === 0 ? "all" : config.allowedUserIds.join(", ")}`);
if (telegramDebug) console.log(" Debug: enabled");
// Register available skills as bot command menu (non-blocking)
registerBotCommands(config.token).catch(() => {});
while (running) {
try {
const data = await callApi<{ ok: boolean; result: TelegramUpdate[] }>(
config.token,
"getUpdates",
{ offset, timeout: 30, allowed_updates: ["message", "my_chat_member", "callback_query"] }
);
if (!data.ok || !data.result.length) continue;
for (const update of data.result) {
debugLog(
`Update ${update.update_id} keys=${Object.keys(update).join(",")}`
);
offset = update.update_id + 1;
const incomingMessages = [
update.message,
update.edited_message,
update.channel_post,
update.edited_channel_post,
].filter((m): m is TelegramMessage => Boolean(m));
for (const incoming of incomingMessages) {
handleMessage(incoming).catch((err) => {
console.error(`[Telegram] Unhandled: ${err}`);
});
}
if (update.my_chat_member) {
handleMyChatMember(update.my_chat_member).catch((err) => {
console.error(`[Telegram] my_chat_member unhandled: ${err}`);
});
}
if (update.callback_query) {
handleCallbackQuery(update.callback_query).catch((err) => {
console.error(`[Telegram] callback_query unhandled: ${err}`);
});
}
}
} catch (err) {
if (!running) break;
console.error(`[Telegram] Poll error: ${err instanceof Error ? err.message : err}`);
await Bun.sleep(5000);
}
}
}
// --- Exports ---
/** Send a message to a specific chat (used by heartbeat forwarding) */
export { sendMessage };
process.on("SIGTERM", () => { running = false; });
process.on("SIGINT", () => { running = false; });
/** Start polling in-process (called by start.ts when token is configured) */
export function startPolling(debug = false): void {
telegramDebug = debug;
(async () => {
await ensureProjectClaudeMd();
await poll();
})().catch((err) => {
console.error(`[Telegram] Fatal: ${err}`);
});
}
/** Standalone entry point (bun run src/index.ts telegram) */
export async function telegram() {
await loadSettings();
await ensureProjectClaudeMd();
await poll();
}