Fix runtime error: Remove duplicate code blocks and missing closing braces in bot/index.js
This commit is contained in:
114
src/bot/index.js
114
src/bot/index.js
@@ -78,9 +78,24 @@ export async function initBot(config, api, tools, skills) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Handle webhook
|
// 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) => {
|
app.post('/telegram/webhook', async (req, res) => {
|
||||||
const update = req.body;
|
const update = req.body;
|
||||||
|
|
||||||
if (update.message) {
|
if (update.message) {
|
||||||
const chatId = update.message.chat.id.toString();
|
const chatId = update.message.chat.id.toString();
|
||||||
const text = update.message.text;
|
const text = update.message.text;
|
||||||
@@ -111,101 +126,4 @@ export async function initBot(config, api, tools, skills) {
|
|||||||
res.json({ ok: true });
|
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,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,12 @@ export const logger = winston.createLogger({
|
|||||||
winston.format.printf(({ timestamp, level, message, ...meta }) => {
|
winston.format.printf(({ timestamp, level, message, ...meta }) => {
|
||||||
let msg = `${timestamp} [${level}]: ${message}`;
|
let msg = `${timestamp} [${level}]: ${message}`;
|
||||||
if (Object.keys(meta).length > 0) {
|
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;
|
return msg;
|
||||||
})
|
})
|
||||||
@@ -28,11 +33,14 @@ export const logger = winston.createLogger({
|
|||||||
// Add file transport if configured
|
// Add file transport if configured
|
||||||
if (process.env.LOG_FILE) {
|
if (process.env.LOG_FILE) {
|
||||||
const logDir = path.dirname(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({
|
logger.add(new winston.transports.File({
|
||||||
filename: process.env.LOG_FILE,
|
filename: process.env.LOG_FILE,
|
||||||
maxsize: 10 * 1024 * 1024, // 10MB
|
format: winston.format.combine(
|
||||||
maxFiles: 5,
|
winston.format.timestamp(),
|
||||||
|
winston.format.json()
|
||||||
|
),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user