-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
530 lines (454 loc) · 16.8 KB
/
Copy pathbot.js
File metadata and controls
530 lines (454 loc) · 16.8 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
#!/usr/bin/env node
/**
* Claude Code <-> Telegram Bridge
*
* Receives Telegram messages, pipes them to Claude Code CLI,
* streams responses back. Runs on your Max subscription.
*
* Usage: BOT_TOKEN=xxx ALLOWED_USER=your_user_id node bot.js
*/
const TelegramBot = require("node-telegram-bot-api");
const { spawn } = require("child_process");
const fs = require("fs");
const path = require("path");
// Config
const BOT_TOKEN = process.env.BOT_TOKEN;
const ALLOWED_USER = process.env.ALLOWED_USER;
const WORKSPACE = process.env.WORKSPACE || process.cwd();
const MAX_MSG_LEN = 4000; // Telegram limit is 4096
const CLAUDE_PATH = process.env.CLAUDE_PATH || "claude";
if (!BOT_TOKEN) {
console.error("BOT_TOKEN required. Set it in .env or environment.");
process.exit(1);
}
if (!ALLOWED_USER) {
console.error("ALLOWED_USER required. Set your Telegram user ID in .env or environment.");
process.exit(1);
}
const bot = new TelegramBot(BOT_TOKEN, { polling: true });
// Track active sessions per chat
const activeSessions = new Map(); // chatId -> { proc, output, messageId }
// Conversation history for context
const HISTORY_FILE = path.join(WORKSPACE, ".claude-telegram-history.json");
const MAX_HISTORY = 20; // Keep last 20 exchanges
function loadHistory() {
try { return JSON.parse(fs.readFileSync(HISTORY_FILE, "utf-8")); } catch { return []; }
}
function saveHistory(history) {
fs.writeFileSync(HISTORY_FILE, JSON.stringify(history, null, 2));
}
function addToHistory(role, text) {
const history = loadHistory();
history.push({ role, text: text.substring(0, 1000), time: new Date().toISOString() });
while (history.length > MAX_HISTORY) history.shift();
saveHistory(history);
}
function getHistoryContext() {
const history = loadHistory();
if (!history.length) return "";
const lines = history.map(h => `[${h.role}]: ${h.text}`).join("\n");
return `\n\nRecent conversation history (for context, do not repeat these):\n${lines}\n\n`;
}
console.log("========================================");
console.log(" Claude Code Telegram Bridge");
console.log(` Workspace: ${WORKSPACE}`);
console.log(` Allowed user: ${ALLOWED_USER}`);
console.log(" Ready for messages.");
console.log("========================================");
// Security: only respond to allowed user
function isAllowed(msg) {
return String(msg.from.id) === String(ALLOWED_USER);
}
// Convert markdown to Telegram-compatible format
function mdToTelegram(text) {
// Convert **bold** to <b>bold</b>
text = text.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>');
// Convert *italic* to <i>italic</i> (but not inside code)
text = text.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, '<i>$1</i>');
// Convert `inline code` to <code>code</code>
text = text.replace(/`([^`\n]+?)`/g, '<code>$1</code>');
// Convert ```code blocks``` to <pre>code</pre>
text = text.replace(/```[\w]*\n?([\s\S]*?)```/g, '<pre>$1</pre>');
// Convert [text](url) to <a href="url">text</a>
text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
// Strip # headers but keep the text bold
text = text.replace(/^#{1,6}\s+(.+)$/gm, '<b>$1</b>');
// Escape remaining HTML special chars that aren't part of our tags
// (Telegram HTML mode requires & < > to be escaped outside tags)
// We skip this since our conversions already handle it
return text;
}
// Send or edit a message (for streaming updates)
async function sendOrEdit(chatId, text, messageId = null, useHtml = true) {
const formatted = useHtml ? mdToTelegram(text) : text;
const truncated = formatted.length > MAX_MSG_LEN
? "..." + formatted.slice(-MAX_MSG_LEN + 3)
: formatted;
const opts = useHtml ? { parse_mode: "HTML" } : {};
try {
if (messageId) {
await bot.editMessageText(truncated, {
chat_id: chatId,
message_id: messageId,
...opts,
});
return messageId;
} else {
const sent = await bot.sendMessage(chatId, truncated, opts);
return sent.message_id;
}
} catch (err) {
if (err.message?.includes("message is not modified")) return messageId;
// If HTML parse fails, retry as plain text
if (err.message?.includes("parse") || err.message?.includes("can't parse")) {
try {
if (messageId) {
await bot.editMessageText(text.length > MAX_MSG_LEN ? "..." + text.slice(-MAX_MSG_LEN + 3) : text, { chat_id: chatId, message_id: messageId });
} else {
const sent = await bot.sendMessage(chatId, text.length > MAX_MSG_LEN ? "..." + text.slice(-MAX_MSG_LEN + 3) : text);
return sent.message_id;
}
return messageId;
} catch { return messageId; }
}
// If edit fails, send new message
if (messageId) {
try {
const sent = await bot.sendMessage(chatId, truncated, opts);
return sent.message_id;
} catch { return messageId; }
}
return messageId;
}
}
// Run claude CLI with an image (uses stream-json input for base64 image)
async function runClaudeWithImage(chatId, caption, imagePath, ext, replyToId) {
// Kill any existing session
if (activeSessions.has(chatId)) {
const old = activeSessions.get(chatId);
try { old.proc.kill("SIGTERM"); } catch {}
activeSessions.delete(chatId);
}
let typingInterval = setInterval(() => {
bot.sendChatAction(chatId, "typing").catch(() => {});
}, 4000);
bot.sendChatAction(chatId, "typing").catch(() => {});
let responseId = null;
addToHistory("user", `[image] ${caption}`);
// Read image as base64
const imageData = fs.readFileSync(imagePath).toString("base64");
const mimeMap = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".gif": "image/gif", ".webp": "image/webp" };
const mediaType = mimeMap[ext.toLowerCase()] || "image/jpeg";
// Build stream-json input message
const inputMsg = {
type: "user",
content: [
{ type: "image", source: { type: "base64", media_type: mediaType, data: imageData } },
{ type: "text", text: caption }
]
};
const args = [
"--print",
"--verbose",
"--output-format", "stream-json",
"--input-format", "stream-json",
"--dangerously-skip-permissions",
];
const proc = spawn(CLAUDE_PATH, args, {
cwd: WORKSPACE,
env: { ...process.env, HOME: process.env.HOME, PATH: process.env.PATH },
stdio: ["pipe", "pipe", "pipe"],
});
let output = "";
let lastUpdate = 0;
const UPDATE_INTERVAL = 2000;
const session = { proc, output: "", messageId: responseId };
activeSessions.set(chatId, session);
let jsonBuffer = "";
proc.stdout.on("data", (data) => {
jsonBuffer += data.toString();
const lines = jsonBuffer.split("\n");
jsonBuffer = lines.pop();
for (const line of lines) {
if (!line.trim()) continue;
try {
const event = JSON.parse(line);
if (event.type === "content_block_delta" && event.delta?.text) {
output += event.delta.text;
} else if (event.type === "result" && event.result) {
if (typeof event.result === "string") { output = event.result; }
else if (event.result.content) {
let text = "";
for (const block of event.result.content) { if (block.type === "text") text += block.text; }
if (text) output = text;
}
}
} catch {}
}
session.output = output;
if (output && typingInterval) { clearInterval(typingInterval); typingInterval = null; }
const now = Date.now();
if (output && now - lastUpdate > UPDATE_INTERVAL) {
lastUpdate = now;
sendOrEdit(chatId, output, responseId).then(id => { responseId = id; });
}
});
proc.stderr.on("data", (data) => {
const err = data.toString();
if (err.includes("error") || err.includes("Error")) output += `\n[stderr] ${err}`;
});
proc.on("close", async (code) => {
if (typingInterval) { clearInterval(typingInterval); typingInterval = null; }
activeSessions.delete(chatId);
if (!output.trim()) output = code === 0 ? "(no output)" : `(claude exited with code ${code})`;
addToHistory("assistant", output);
if (output.length > MAX_MSG_LEN) {
const chunks = [];
let remaining = output;
while (remaining.length > 0) { chunks.push(remaining.slice(0, MAX_MSG_LEN)); remaining = remaining.slice(MAX_MSG_LEN); }
await sendOrEdit(chatId, chunks[0], responseId);
for (let i = 1; i < chunks.length; i++) await bot.sendMessage(chatId, chunks[i]);
} else {
await sendOrEdit(chatId, output, responseId);
}
});
proc.on("error", async (err) => {
if (typingInterval) { clearInterval(typingInterval); typingInterval = null; }
activeSessions.delete(chatId);
await sendOrEdit(chatId, `Error: ${err.message}`, responseId);
});
// Send the image message via stdin then close
proc.stdin.write(JSON.stringify(inputMsg) + "\n");
proc.stdin.end();
setTimeout(() => {
if (activeSessions.has(chatId) && activeSessions.get(chatId).proc === proc) {
proc.kill("SIGTERM");
sendOrEdit(chatId, output + "\n\n(timed out after 30 minutes)", responseId);
}
}, 30 * 60 * 1000);
}
// Run claude CLI with a prompt
async function runClaude(chatId, prompt, replyToId) {
// Kill any existing session for this chat
if (activeSessions.has(chatId)) {
const old = activeSessions.get(chatId);
try { old.proc.kill("SIGTERM"); } catch {}
activeSessions.delete(chatId);
}
// Send typing indicator continuously until response starts
let typingInterval = setInterval(() => {
bot.sendChatAction(chatId, "typing").catch(() => {});
}, 4000);
bot.sendChatAction(chatId, "typing").catch(() => {});
let responseId = null;
// Add to history
addToHistory("user", prompt);
// Build claude command with conversation context
const historyContext = getHistoryContext();
const fullPrompt = historyContext ? `${historyContext}Current message: ${prompt}` : prompt;
// Use --print with stream-json for real-time output
const args = [
"--print",
"--verbose",
"--output-format", "stream-json",
"--dangerously-skip-permissions",
fullPrompt
];
const proc = spawn(CLAUDE_PATH, args, {
cwd: WORKSPACE,
env: {
...process.env,
HOME: process.env.HOME,
PATH: process.env.PATH,
},
stdio: ["pipe", "pipe", "pipe"],
});
let output = "";
let lastUpdate = 0;
const UPDATE_INTERVAL = 2000; // Update message every 2 seconds
const session = { proc, output: "", messageId: responseId };
activeSessions.set(chatId, session);
let jsonBuffer = "";
proc.stdout.on("data", (data) => {
jsonBuffer += data.toString();
// Parse newline-delimited JSON
const lines = jsonBuffer.split("\n");
jsonBuffer = lines.pop(); // keep incomplete line in buffer
for (const line of lines) {
if (!line.trim()) continue;
try {
const event = JSON.parse(line);
// Extract text from different event types
if (event.type === "content_block_delta" && event.delta?.text) {
output += event.delta.text;
} else if (event.type === "result" && event.result) {
// Final result
if (typeof event.result === "string") {
output = event.result;
} else if (event.result.content) {
let text = "";
for (const block of event.result.content) {
if (block.type === "text") text += block.text;
}
if (text) output = text;
}
}
} catch {}
}
session.output = output;
// Stop typing indicator once we have output
if (output && typingInterval) { clearInterval(typingInterval); typingInterval = null; }
const now = Date.now();
if (output && now - lastUpdate > UPDATE_INTERVAL) {
lastUpdate = now;
sendOrEdit(chatId, output, responseId).then(id => { responseId = id; });
}
});
proc.stderr.on("data", (data) => {
const err = data.toString();
// Skip noisy stderr (progress indicators, etc)
if (err.includes("error") || err.includes("Error")) {
output += `\n[stderr] ${err}`;
}
});
proc.on("close", async (code) => {
if (typingInterval) { clearInterval(typingInterval); typingInterval = null; }
activeSessions.delete(chatId);
if (!output.trim()) {
output = code === 0 ? "(no output)" : `(claude exited with code ${code})`;
}
// Save response to history
addToHistory("assistant", output);
// Final update with complete output
// Split into multiple messages if needed
if (output.length > MAX_MSG_LEN) {
// Send as chunks
const chunks = [];
let remaining = output;
while (remaining.length > 0) {
chunks.push(remaining.slice(0, MAX_MSG_LEN));
remaining = remaining.slice(MAX_MSG_LEN);
}
// Edit first message with first chunk
await sendOrEdit(chatId, chunks[0], responseId);
// Send remaining chunks as new messages
for (let i = 1; i < chunks.length; i++) {
await bot.sendMessage(chatId, chunks[i]);
}
} else {
await sendOrEdit(chatId, output, responseId);
}
});
proc.on("error", async (err) => {
if (typingInterval) { clearInterval(typingInterval); typingInterval = null; }
activeSessions.delete(chatId);
await sendOrEdit(chatId, `Error: ${err.message}`, responseId);
});
// Timeout after 30 minutes
setTimeout(() => {
if (activeSessions.has(chatId) && activeSessions.get(chatId).proc === proc) {
proc.kill("SIGTERM");
sendOrEdit(chatId, output + "\n\n(timed out after 30 minutes)", responseId);
}
}, 30 * 60 * 1000);
}
// Handle text messages
bot.on("message", async (msg) => {
if (!isAllowed(msg)) {
bot.sendMessage(msg.chat.id, "Unauthorized.");
return;
}
const text = msg.text?.trim();
if (!text) return;
// Special commands
if (text === "/stop" || text === "/cancel") {
if (activeSessions.has(msg.chat.id)) {
const session = activeSessions.get(msg.chat.id);
session.proc.kill("SIGTERM");
activeSessions.delete(msg.chat.id);
bot.sendMessage(msg.chat.id, "Cancelled.");
} else {
bot.sendMessage(msg.chat.id, "Nothing running.");
}
return;
}
if (text === "/start") {
bot.sendMessage(msg.chat.id,
"Claude Code bridge ready.\n\n" +
"Send any message and it goes straight to Claude Code.\n" +
"/stop - Cancel running task\n" +
"/status - Check if something is running"
);
return;
}
if (text === "/clear") {
saveHistory([]);
bot.sendMessage(msg.chat.id, "Conversation history cleared.");
return;
}
if (text === "/status") {
if (activeSessions.has(msg.chat.id)) {
bot.sendMessage(msg.chat.id, "Claude is working on something. /stop to cancel.");
} else {
bot.sendMessage(msg.chat.id, "Idle. Send a message to start.");
}
return;
}
// Everything else goes to Claude
await runClaude(msg.chat.id, text, msg.message_id);
});
// Handle photos — download and pass as base64 via stream-json input
bot.on("photo", async (msg) => {
if (!isAllowed(msg)) return;
const photo = msg.photo[msg.photo.length - 1]; // highest res
const file = await bot.getFile(photo.file_id);
const url = `https://api.telegram.org/file/bot${BOT_TOKEN}/${file.file_path}`;
// Download to workspace
const ext = path.extname(file.file_path) || ".jpg";
const localPath = path.join(WORKSPACE, `.tmp-photo${ext}`);
const https = require("https");
const fileStream = fs.createWriteStream(localPath);
https.get(url, (response) => {
response.pipe(fileStream);
fileStream.on("finish", () => {
fileStream.close();
const caption = msg.caption || "Describe this image";
// Use runClaudeWithImage for photo messages
runClaudeWithImage(msg.chat.id, caption, localPath, ext, msg.message_id);
});
});
});
// Handle documents
bot.on("document", async (msg) => {
if (!isAllowed(msg)) return;
const doc = msg.document;
const file = await bot.getFile(doc.file_id);
const url = `https://api.telegram.org/file/bot${BOT_TOKEN}/${file.file_path}`;
const localPath = path.join(WORKSPACE, doc.file_name || "uploaded-file");
const https = require("https");
const fileStream = fs.createWriteStream(localPath);
https.get(url, (response) => {
response.pipe(fileStream);
fileStream.on("finish", () => {
fileStream.close();
const caption = msg.caption || `I uploaded a file: ${doc.file_name}`;
runClaude(msg.chat.id, `${caption}\n\n[File saved at: ${localPath}]`, msg.message_id);
});
});
});
// Graceful shutdown
process.on("SIGINT", () => {
console.log("\nShutting down...");
for (const [, session] of activeSessions) {
try { session.proc.kill("SIGTERM"); } catch {}
}
bot.stopPolling();
process.exit(0);
});
process.on("SIGTERM", () => {
for (const [, session] of activeSessions) {
try { session.proc.kill("SIGTERM"); } catch {}
}
bot.stopPolling();
process.exit(0);
});