-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
130 lines (107 loc) · 3.84 KB
/
Copy pathbot.js
File metadata and controls
130 lines (107 loc) · 3.84 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
'use strict';
require('dotenv/config');
const path = require('node:path');
const TelegramBot = require('node-telegram-bot-api');
const { CopilotClient } = require('@github/copilot-sdk');
const stayAwake = require('./services/stayAwake');
const { loadCommands, runCommand } = require('./lib/commands');
const { sendLongMessage } = require('./lib/telegram');
const TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const ALLOWED_CHAT_ID = process.env.ALLOWED_CHAT_ID;
const MODEL = process.env.MODEL || 'gpt-4o-mini';
const COPILOT_ENABLED = process.env.COPILOT_ENABLED === 'true';
if (!TOKEN) {
console.error('❌ TELEGRAM_BOT_TOKEN mancante: configuralo nel file .env');
process.exit(1);
}
const bot = new TelegramBot(TOKEN, { polling: { params: { allowed_updates: ['message'] } } });
const commands = loadCommands(path.join(__dirname, 'commands'));
const copilot = { client: null, session: null };
const ctx = {
keepAliveProcess: { value: null },
powercfgBackup: { value: {} },
commands,
sendLongMessage: (chatId, text, options) => sendLongMessage(bot, chatId, text, options),
};
const isAuthorized = (chatId) => Boolean(ALLOWED_CHAT_ID) && String(chatId) === ALLOWED_CHAT_ID;
async function sendAccessInfo(msg) {
const { id: userId, username } = msg.from;
const text = `
📋 **Accesso non configurato**
🆔 Il tuo Chat ID: \`${msg.chat.id}\`
👤 User ID: \`${userId}\`
📝 Username: ${username ? '@' + username : 'Nessuno'}
⚙️ Per autorizzarti, aggiungi nel file .env:
\`ALLOWED_CHAT_ID=${msg.chat.id}\`
`.trim();
await bot.sendMessage(msg.chat.id, text, { parse_mode: 'Markdown' });
}
async function askCopilot(chatId, prompt) {
if (!COPILOT_ENABLED || !copilot.session) {
await bot.sendMessage(chatId, '❌ Copilot non disponibile (COPILOT_ENABLED=false)');
return;
}
await bot.sendChatAction(chatId, 'typing');
const response = await copilot.session.sendAndWait({ prompt });
const content = response?.data?.content;
if (content) {
await ctx.sendLongMessage(chatId, content);
} else {
await bot.sendMessage(chatId, '⚠️ Nessuna risposta da Copilot');
}
}
bot.on('message', async (msg) => {
const chatId = msg.chat.id;
const text = msg.text?.trim();
if (!text) return;
console.log(`📩 [Chat ${chatId}] ${text}`);
if (!isAuthorized(chatId)) {
await sendAccessInfo(msg);
return;
}
const [name, ...rest] = text.split(' ');
const args = rest.join(' ').trim();
const cmd = commands.get(name);
try {
if (cmd) {
await runCommand(cmd, bot, msg, args, ctx);
} else {
await askCopilot(chatId, text);
}
} catch (error) {
console.error('Errore gestione messaggio:', error);
await bot.sendMessage(chatId, `❌ Errore: ${error.message}`);
}
});
bot.on('polling_error', (error) => console.error('Polling error:', error.message));
async function initCopilot() {
copilot.client = new CopilotClient();
await copilot.client.start();
console.log('✅ Copilot SDK avviato');
copilot.session = await copilot.client.createSession({
model: MODEL,
onPermissionRequest: async () => ({ kind: 'approve-once' }),
});
console.log('✅ Sessione Copilot creata');
}
async function main() {
if (COPILOT_ENABLED) {
await initCopilot();
} else {
console.log('⏸️ Copilot disabilitato da COPILOT_ENABLED=false');
}
stayAwake.start();
console.log('🤖 SwissKnifeBot in ascolto...');
}
async function shutdown() {
stayAwake.stop();
if (copilot.session) await copilot.session.disconnect();
if (copilot.client) await copilot.client.stop();
process.exit(0);
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
main().catch((error) => {
console.error('Avvio fallito:', error);
process.exit(1);
});