From fc12e8dc79b220fe0ee38054f73f49587a405dd5 Mon Sep 17 00:00:00 2001 From: admin Date: Tue, 5 May 2026 11:59:22 +0000 Subject: [PATCH] Fix runtime error: Remove duplicate code blocks and missing closing braces in bot/index.js --- src/bot/index.js | 114 +++++++------------------------------------- src/utils/logger.js | 18 +++++-- 2 files changed, 29 insertions(+), 103 deletions(-) diff --git a/src/bot/index.js b/src/bot/index.js index 01f05b36..bac46224 100644 --- a/src/bot/index.js +++ b/src/bot/index.js @@ -78,9 +78,24 @@ export async function initBot(config, api, tools, skills) { } // Handle webhook + // Handle webhook verification (Telegram GET request) + app.get('/telegram/webhook', (req, res) => { + const { hub_mode, hub_challenge } = req.query; + + // Telegram sends a GET request for webhook verification + if (hub_mode === 'subscribe' && hub_challenge) { + logger.info('✓ Webhook verified by Telegram'); + return res.status(200).send(hub_challenge); + } + + // Return 200 for any other GET requests (for health checks, etc.) + return res.status(200).json({ ok: true, message: 'zCode webhook is active' }); + }); + + // Handle webhook POST app.post('/telegram/webhook', async (req, res) => { const update = req.body; - + if (update.message) { const chatId = update.message.chat.id.toString(); const text = update.message.text; @@ -111,101 +126,4 @@ export async function initBot(config, api, tools, skills) { res.json({ ok: true }); } }); - - // Process text message - async function processMessage(chatId, text, username) { - // Send typing indicator - await sendTelegramMessage(chatId, '🤖 Thinking...', { - reply_parameters: { message_id: 0 }, - }); - - // Process through agent - const response = await processWithAgent(text, chatId); - - // Send response - if (response) { - await sendTelegramMessage(chatId, response); - } - } - - // Process callback query - async function processCallback(chatId, data) { - // TODO: Handle callback data - logger.info(`Processing callback: ${data}`); - } - - // Agent processing - async function processWithAgent(text, chatId) { - try { - // Use Z.AI API to process the message - const systemPrompt = `You are zCode, an AI coding agent with full capabilities. -You have access to tools for bash commands, file editing, web search, and git operations. -You can execute code, analyze systems, and provide comprehensive responses. -Be concise, direct, and action-oriented. Focus on solving problems. -`; - - const messages = [ - { - role: "system", - content: systemPrompt - }, - { - role: "user", - content: text - } - ]; - - const response = await api.client.post("/chat/completions", { - model: "glm-5.1", - messages: messages, - temperature: 0.7, - max_tokens: 4096 - }); - - return response.data.choices[0].message.content; - } catch (error) { - logger.error('Error processing message:', error); - return '❌ Error processing message. Please try again.'; - } - } - - // Set webhook (if URL provided) - async function setWebhook() { - const webhookUrl = process.env.ZCODE_WEBHOOK_URL; - if (webhookUrl) { - const url = `https://api.telegram.org/bot${botToken}/setWebhook`; - const response = await fetch(url, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ url: webhookUrl }), - }); - - const data = await response.json(); - if (data.ok) { - logger.info('✓ Webhook set successfully'); - } else { - logger.error('✗ Failed to set webhook:', data.description); - } - } - } - - // Start HTTP server - const PORT = process.env.ZCODE_PORT || 3000; - httpServer.listen(PORT, () => { - logger.info(`✓ HTTP server running on port ${PORT}`); - logger.info(`✓ WebSocket server ready`); - }); - - // Set webhook and keep process alive - await setWebhook(); - - return { - send: sendTelegramMessage, - ws: sendWebSocketMessage, - waitForMessages: async () => { - // Keep process alive - await new Promise(() => {}); - }, - getConnections: () => connections.size, - }; } diff --git a/src/utils/logger.js b/src/utils/logger.js index 6023e282..7a1273c3 100644 --- a/src/utils/logger.js +++ b/src/utils/logger.js @@ -16,7 +16,12 @@ export const logger = winston.createLogger({ winston.format.printf(({ timestamp, level, message, ...meta }) => { let msg = `${timestamp} [${level}]: ${message}`; if (Object.keys(meta).length > 0) { - msg += ` ${JSON.stringify(meta)}`; + // Try to stringify meta, but handle circular structures + try { + msg += ` ${JSON.stringify(meta)}`; + } catch (e) { + msg += ` [circular object]`; + } } return msg; }) @@ -28,11 +33,14 @@ export const logger = winston.createLogger({ // Add file transport if configured if (process.env.LOG_FILE) { const logDir = path.dirname(process.env.LOG_FILE); - fs.ensureDirSync(logDir); - + if (!fs.existsSync(logDir)) { + fs.mkdirSync(logDir, { recursive: true }); + } logger.add(new winston.transports.File({ filename: process.env.LOG_FILE, - maxsize: 10 * 1024 * 1024, // 10MB - maxFiles: 5, + format: winston.format.combine( + winston.format.timestamp(), + winston.format.json() + ), })); }