建立 telegram-codex-bot:串接 Codex CLI 的 Telegram bot(npm 包)
摘要: 用 Telegram 操控本機 Codex CLI 的 bot,附 web 控制台,封裝為 npm 包。 內容: - 零依賴(僅 Node 內建模組);bot 以 codex exec --json 驅動,支援會話延續 (exec resume)、workspace-write 沙盒、圖片輸入、進度回報與 ctx%/tokens footer - web 控制台(pm2 託管,預設 127.0.0.1:3799):Bot 管理分頁(新增/編輯/啟停, token 自動驗證、工作目錄用原生視窗選、模型/推理強度/速度下拉,清單來自 ~/.codex/models_cache.json)+ PM2 檢視分頁(狀態/port/log/啟停) - CLI:start(環境檢查後把控制台掛上 pm2)/ stop / restart / delete / status / logs / web / doctor - Windows 相容:解析 codex.cmd shim 直接以 node 執行、taskkill 整樹砍程序、 資料夾選擇視窗以 TopMost 透明 owner 置中 影響: 新專案初始版本;bot 設定存於 ~/.tgcodex/bots/<name>/,含明文 token 的實例 設定不進版控(.gitignore 已涵蓋 tgcodex.config.json 與 .tgcodex/)。 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
+291
@@ -0,0 +1,291 @@
|
||||
'use strict';
|
||||
// Bot 主邏輯:長輪詢、指令、佇列、進度回報。
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { createTelegram } = require('./telegram');
|
||||
const { runCodex } = require('./codex');
|
||||
const { createSessionStore } = require('./sessions');
|
||||
|
||||
// codex 的模型快取與全域預設(config.toml),給 footer 顯示 ctx% 與模型/強度用
|
||||
function loadModelMeta() {
|
||||
try {
|
||||
const cache = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.codex', 'models_cache.json'), 'utf-8'));
|
||||
const map = {};
|
||||
for (const m of cache.models || []) map[m.slug] = m;
|
||||
return map;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function loadCodexDefaults() {
|
||||
try {
|
||||
const toml = fs.readFileSync(path.join(os.homedir(), '.codex', 'config.toml'), 'utf-8');
|
||||
return {
|
||||
model: toml.match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1] || '',
|
||||
effort: toml.match(/^\s*model_reasoning_effort\s*=\s*"([^"]+)"/m)?.[1] || '',
|
||||
tier: toml.match(/^\s*service_tier\s*=\s*"([^"]+)"/m)?.[1] || '',
|
||||
};
|
||||
} catch {
|
||||
return { model: '', effort: '', tier: '' };
|
||||
}
|
||||
}
|
||||
|
||||
// — ✅ 16:06:32 | ctx 24% +1.2k | gpt-5.6-sol / high / Fast
|
||||
function buildFooter(config, usage, modelMeta, codexDefaults) {
|
||||
const time = new Date().toLocaleTimeString('zh-TW', { hour12: false });
|
||||
const parts = [`— ✅ ${time}`];
|
||||
|
||||
const model = config.model || codexDefaults.model;
|
||||
const meta = modelMeta[model];
|
||||
if (usage) {
|
||||
const used = (usage.input_tokens || 0) + (usage.output_tokens || 0);
|
||||
// 本輪新消耗(扣掉 cache 命中的部分)
|
||||
const fresh = Math.max(0, (usage.input_tokens || 0) - (usage.cached_input_tokens || 0)) + (usage.output_tokens || 0);
|
||||
const freshStr = fresh >= 1000 ? `+${(fresh / 1000).toFixed(1)}k` : `+${fresh}`;
|
||||
const cw = meta?.context_window;
|
||||
parts.push(cw ? `ctx ${Math.round((used / cw) * 100)}% ${freshStr}` : freshStr);
|
||||
}
|
||||
|
||||
if (model) {
|
||||
const effort = config.reasoningEffort || codexDefaults.effort || meta?.default_reasoning_level || '';
|
||||
const tier = config.serviceTier || codexDefaults.tier || '';
|
||||
// 顯示速度層級的名稱(priority → Fast),對照模型快取
|
||||
const tierName = tier
|
||||
? (meta?.service_tiers?.find((t) => t.id === tier)?.name || tier)
|
||||
: '';
|
||||
parts.push([model, effort, tierName].filter(Boolean).join(' / '));
|
||||
}
|
||||
return `\n\n${parts.join(' | ')}`;
|
||||
}
|
||||
|
||||
const NEW_COMMANDS = ['/new', '!clear', '!reset', '!new', '!清除', '!重置', '!新會話'];
|
||||
const STATUS_COMMANDS = ['/status', '!status', '!狀態'];
|
||||
const HELP_COMMANDS = ['/start', '/help', '!help', '!幫助'];
|
||||
|
||||
function startBot(config) {
|
||||
const t = createTelegram(config.telegramToken);
|
||||
const sessions = createSessionStore(config.stateDir);
|
||||
const modelMeta = loadModelMeta();
|
||||
const codexDefaults = loadCodexDefaults();
|
||||
|
||||
let botId = null;
|
||||
let botUsername = null;
|
||||
// 同一個工作目錄不能同時跑兩個 codex(會互相踩檔案),全域串行
|
||||
let queue = Promise.resolve();
|
||||
|
||||
function shouldRespond(message) {
|
||||
if (message.chat.type === 'private') return true;
|
||||
if (message.reply_to_message?.from?.id === botId) return true;
|
||||
const text = message.text || message.caption || '';
|
||||
const entities = message.entities || message.caption_entities || [];
|
||||
return entities.some((e) =>
|
||||
(e.type === 'mention' &&
|
||||
text.slice(e.offset, e.offset + e.length).toLowerCase() === `@${botUsername.toLowerCase()}`) ||
|
||||
(e.type === 'text_mention' && e.user?.id === botId)
|
||||
);
|
||||
}
|
||||
|
||||
function stripMention(text) {
|
||||
if (!botUsername) return text.trim();
|
||||
return text.replace(new RegExp(`@${botUsername}`, 'gi'), '').trim();
|
||||
}
|
||||
|
||||
// 群組指令會帶 @BotName 後綴(例如 /new@MyBot)
|
||||
function matchCommand(text, commands) {
|
||||
const head = text.split(/\s/, 1)[0].replace(new RegExp(`@${botUsername}$`, 'i'), '');
|
||||
return commands.includes(head.toLowerCase());
|
||||
}
|
||||
|
||||
function cleanTmp() {
|
||||
const ttl = 24 * 60 * 60 * 1000;
|
||||
try {
|
||||
for (const f of fs.readdirSync(config.tmpDir)) {
|
||||
const p = path.join(config.tmpDir, f);
|
||||
try {
|
||||
if (Date.now() - fs.statSync(p).mtimeMs > ttl) fs.unlinkSync(p);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// 取出訊息附圖(photo 取最大尺寸;image/* 的 document 也支援)
|
||||
function pickPhoto(message) {
|
||||
if (message.photo?.length) {
|
||||
const largest = message.photo[message.photo.length - 1];
|
||||
return { fileId: largest.file_id, uniqueId: largest.file_unique_id, ext: '.jpg' };
|
||||
}
|
||||
const doc = message.document;
|
||||
if (doc && /^image\//.test(doc.mime_type || '')) {
|
||||
const ext = path.extname(doc.file_name || '') || '.' + (doc.mime_type.split('/')[1] || 'png');
|
||||
return { fileId: doc.file_id, uniqueId: doc.file_unique_id, ext };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildPrompt(message, content) {
|
||||
const from = message.from || {};
|
||||
const name = [from.first_name, from.last_name].filter(Boolean).join(' ') || '未知使用者';
|
||||
const sender = from.username ? `${name}(@${from.username})` : name;
|
||||
const parts = [];
|
||||
const replied = message.reply_to_message;
|
||||
if (replied && replied.from?.id !== botId && (replied.text || replied.caption)) {
|
||||
parts.push(`【被回覆的訊息】\n${replied.text || replied.caption}`);
|
||||
}
|
||||
if (message.quote?.text) {
|
||||
parts.push(`【使用者圈選引用的段落,請聚焦於此】\n${message.quote.text}`);
|
||||
}
|
||||
parts.push(`【來自 Telegram 的 ${sender}】\n${content}`);
|
||||
return parts.join('\n\n');
|
||||
}
|
||||
|
||||
function statusText(chatId) {
|
||||
const s = sessions.get(chatId);
|
||||
return [
|
||||
'📋 目前狀態',
|
||||
`工作目錄:${config.workDir}`,
|
||||
`沙盒模式:${config.sandbox}`,
|
||||
`模型:${config.model || '(codex 預設)'}`,
|
||||
`推理強度:${config.reasoningEffort || '(預設)'}`,
|
||||
`速度:${config.serviceTier || '(預設)'}`,
|
||||
s ? `會話:${s.threadId}\n最後使用:${s.updatedAt}` : '會話:尚未建立(下一則訊息會開新會話)',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const HELP_TEXT = [
|
||||
'🤖 我是 Codex bot,訊息直接丟給我就會在專案目錄裡動工。',
|
||||
'',
|
||||
'指令:',
|
||||
'/new — 開新會話(清除目前對話記憶)',
|
||||
'/status — 查看會話與設定',
|
||||
'/help — 顯示這則說明',
|
||||
'',
|
||||
'群組中要 @我 或回覆我的訊息才會觸發。可以直接傳圖片(附文字說明)。',
|
||||
].join('\n');
|
||||
|
||||
async function handleMessage(message) {
|
||||
if (!message || message.from?.id === botId) return;
|
||||
const chatId = message.chat.id;
|
||||
const text = message.text || message.caption || '';
|
||||
const photo = pickPhoto(message);
|
||||
if (!text && !photo) return;
|
||||
if (!shouldRespond(message)) return;
|
||||
|
||||
const content = stripMention(text);
|
||||
|
||||
if (matchCommand(content, HELP_COMMANDS)) {
|
||||
await t.sendMessage(chatId, HELP_TEXT, { replyTo: message.message_id });
|
||||
return;
|
||||
}
|
||||
if (matchCommand(content, NEW_COMMANDS)) {
|
||||
sessions.clear(chatId);
|
||||
await t.sendMessage(chatId, '🆕 已開新會話,之前的對話記憶已清除。', { replyTo: message.message_id });
|
||||
return;
|
||||
}
|
||||
if (matchCommand(content, STATUS_COMMANDS)) {
|
||||
await t.sendMessage(chatId, statusText(chatId), { replyTo: message.message_id });
|
||||
return;
|
||||
}
|
||||
if (!content && !photo) {
|
||||
await t.sendMessage(chatId, HELP_TEXT, { replyTo: message.message_id });
|
||||
return;
|
||||
}
|
||||
|
||||
await t.react(chatId, message.message_id, '👀');
|
||||
const statusMsg = await t.sendMessage(chatId, '🤔 Codex 處理中...', { replyTo: message.message_id });
|
||||
|
||||
// Telegram 對 editMessageText 限流很兇:至少隔 3 秒、且不重疊
|
||||
let lastEdit = 0;
|
||||
let editing = false;
|
||||
const onProgress = (progressText) => {
|
||||
const now = Date.now();
|
||||
if (editing || now - lastEdit < 3000) return;
|
||||
editing = true;
|
||||
lastEdit = now;
|
||||
const body = `🚧 Codex 處理中...\n\n${progressText}`;
|
||||
t.tg('editMessageText', {
|
||||
chat_id: chatId,
|
||||
message_id: statusMsg.message_id,
|
||||
text: body.length > 3900 ? body.slice(0, 3900) + '...' : body,
|
||||
}).catch(() => {}).finally(() => { editing = false; });
|
||||
};
|
||||
|
||||
try {
|
||||
const images = [];
|
||||
if (photo) {
|
||||
cleanTmp();
|
||||
const dest = path.join(config.tmpDir, `${Date.now()}-${photo.uniqueId}${photo.ext}`);
|
||||
await t.downloadFile(photo.fileId, dest);
|
||||
images.push(dest);
|
||||
}
|
||||
|
||||
const prompt = buildPrompt(message, content || '(使用者只傳了圖片,請描述並依上下文處理)');
|
||||
const existing = sessions.get(chatId);
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await runCodex({ config, prompt, threadId: existing?.threadId || null, images, onProgress });
|
||||
} catch (err) {
|
||||
// 舊會話可能已被 codex 清掉,找不到就自動開新會話重試一次
|
||||
if (existing && /session|thread|conversation/i.test(err.message) && /not.*found|找不到|no .*(session|thread)/i.test(err.message)) {
|
||||
sessions.clear(chatId);
|
||||
result = await runCodex({ config, prompt, threadId: null, images, onProgress });
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.threadId) sessions.set(chatId, result.threadId);
|
||||
|
||||
const footer = buildFooter(config, result.usage, modelMeta, codexDefaults);
|
||||
const html = t.mdToTgHtml((result.text || '(Codex 沒有回覆文字)') + footer);
|
||||
await t.editOrSplit(chatId, statusMsg.message_id, html, { html: true });
|
||||
await t.react(chatId, message.message_id, '👍');
|
||||
} catch (error) {
|
||||
console.error('處理訊息失敗:', error);
|
||||
await t.editOrSplit(chatId, statusMsg.message_id, `❌ 發生錯誤:${error.message}`).catch(() => {});
|
||||
await t.react(chatId, message.message_id, '');
|
||||
}
|
||||
}
|
||||
|
||||
async function pollLoop() {
|
||||
let offset = 0;
|
||||
for (;;) {
|
||||
try {
|
||||
const updates = await t.tg('getUpdates', { offset, timeout: 50, allowed_updates: ['message'] });
|
||||
for (const update of updates) {
|
||||
offset = update.update_id + 1;
|
||||
queue = queue
|
||||
.then(() => handleMessage(update.message))
|
||||
.catch((err) => console.error('處理訊息錯誤:', err));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('輪詢錯誤:', err.message);
|
||||
await new Promise((r) => setTimeout(r, 5000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const me = await t.tg('getMe', {});
|
||||
botId = me.id;
|
||||
botUsername = me.username;
|
||||
await t.tg('setMyCommands', {
|
||||
commands: [
|
||||
{ command: 'new', description: '開新會話(清除對話記憶)' },
|
||||
{ command: 'status', description: '查看會話與設定' },
|
||||
{ command: 'help', description: '使用說明' },
|
||||
],
|
||||
}).catch(() => {});
|
||||
|
||||
console.log(`✅ @${botUsername} 已啟動`);
|
||||
console.log(` 工作目錄:${config.workDir}`);
|
||||
console.log(` 沙盒模式:${config.sandbox}`);
|
||||
await pollLoop();
|
||||
}
|
||||
|
||||
return { start };
|
||||
}
|
||||
|
||||
module.exports = { startBot, buildFooter, loadModelMeta, loadCodexDefaults };
|
||||
Reference in New Issue
Block a user