-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
243 lines (201 loc) · 6.98 KB
/
bot.js
File metadata and controls
243 lines (201 loc) · 6.98 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
import dotenv from 'dotenv';
import TelegramBot from 'node-telegram-bot-api';
import { createOpencodeClient } from '@opencode-ai/sdk';
import path from 'path';
dotenv.config();
// Load bot token from .env file
const token = process.env.TELEGRAM_BOT_API_KEY;
if (!token) {
console.error('Error: TELEGRAM_BOT_API_KEY not found in .env file');
process.exit(1);
}
// Initialize Opencode client
const opencodeServerUrl = process.env.OPENCODE_SERVER_URL || 'http://localhost:4096';
let opencodeClient = null;
async function initOpencode() {
try {
const config = {
baseUrl: opencodeServerUrl,
throwOnError: false,
directory: process.cwd(),
};
opencodeClient = createOpencodeClient(config);
console.log('✓ Opencode client initialized');
return true;
} catch (error) {
console.error('Failed to initialize Opencode client:', error.message);
return false;
}
}
// Create bot with polling enabled
const bot = new TelegramBot(token, { polling: true });
console.log('Bot is starting...');
// Initialize Opencode
initOpencode().then(() => {
console.log('Opencode integration ready');
});
const jokes = [
"Why do programmers prefer dark mode? Because light attracts bugs! 🐛",
"Why did the developer go broke? Because he used up all his cache! 💸",
"How many programmers does it take to change a light bulb? None, that's a hardware problem! 💡",
"Why do Java developers wear glasses? Because they can't C#! 👓",
"What's a programmer's favorite place to hang out? Foo Bar! 🍻",
"Why was the JavaScript developer sad? Because he didn't know how to 'null' his feelings! 😢",
"What do you call a programmer from Finland? Nerdic! 🇫🇮",
"Why did the programmer quit his job? Because he didn't get arrays! 📊"
];
// Single message handler for all commands
bot.on('message', async (msg) => {
const chatId = msg.chat.id;
const text = msg.text || '';
// Command handlers
if (/^\/start$/.test(text)) {
const welcomeMessage = `
🤖 Hello! I'm your Telegram bot integrated with Opencode.
Available commands:
/start - Start the bot
/help - Show this help message
/echo <text> - Repeat your text
/time - Get current date and time
/random - Get a random number (1-100)
/joke - Get a random joke
/opencode <prompt> - Ask Opencode AI something
/health - Check Opencode server status
Just send me a message and I'll echo it back!
`.trim();
bot.sendMessage(chatId, welcomeMessage);
return;
}
if (/^\/help$/.test(text)) {
const helpMessage = `
📋 Available Commands:
/start - Start the bot
/help - Show this help message
/echo <text> - Repeat your text
/time - Get current date and time
/random - Get a random number (1-100)
/joke - Get a random joke
/opencode <prompt> - Ask Opencode AI something
/health - Check Opencode server status
💡 Tip: You can also just send any message and I'll echo it back!
`.trim();
bot.sendMessage(chatId, helpMessage);
return;
}
const echoMatch = text.match(/^\/echo (.+)/);
if (echoMatch) {
bot.sendMessage(chatId, `🔁 ${echoMatch[1]}`);
return;
}
if (/^\/time$/.test(text)) {
const now = new Date();
const timeString = now.toLocaleString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
});
bot.sendMessage(chatId, `🕐 Current time:\n${timeString}`);
return;
}
if (/^\/random$/.test(text)) {
const randomNum = Math.floor(Math.random() * 100) + 1;
bot.sendMessage(chatId, `🎲 Your random number: ${randomNum}`);
return;
}
if (/^\/joke$/.test(text)) {
const randomJoke = jokes[Math.floor(Math.random() * jokes.length)];
bot.sendMessage(chatId, `😄 ${randomJoke}`);
return;
}
// Opencode integration command
const opencodeMatch = text.match(/^\/opencode\s+(.+)/);
if (opencodeMatch) {
if (!opencodeClient) {
bot.sendMessage(chatId, '❌ Opencode client not initialized. Please wait a moment and try again.');
return;
}
const prompt = opencodeMatch[1];
bot.sendMessage(chatId, '🤖 Processing with Opencode...');
try {
// Create a new session
const session = await opencodeClient.session.create({
body: { title: `Telegram: ${prompt.substring(0, 30)}...` }
});
if (session.error) {
const errMsg = typeof session.error === 'string' ? session.error :
session.error?.message || JSON.stringify(session.error);
throw new Error(`Session creation failed: ${errMsg}`);
}
const sessionId = session.data?.id;
if (!sessionId) {
throw new Error('Failed to create session - no ID returned');
}
// Send prompt and get response
const result = await opencodeClient.session.prompt({
path: { id: sessionId },
body: {
parts: [{ type: 'text', text: prompt }],
},
});
if (result.error) {
throw new Error(typeof result.error === 'string' ? result.error : result.error.message || JSON.stringify(result.error));
}
// Extract response text
let response = 'No response received';
if (result.data?.parts) {
const textParts = result.data.parts
.filter(part => part.type === 'text')
.map(part => part.text);
response = textParts.join('\n') || response;
}
// Clean up: delete the session
await opencodeClient.session.delete({ path: { id: sessionId } });
bot.sendMessage(chatId, `📝 Response:\n\n${response}`);
} catch (error) {
console.error('Opencode error:', error);
bot.sendMessage(chatId, `❌ Opencode error: ${error.message || 'Unknown error'}`);
}
return;
}
// Health check command
if (/^\/health$/.test(text)) {
if (!opencodeClient) {
bot.sendMessage(chatId, '❌ Opencode client not initialized');
return;
}
try {
const sessions = await opencodeClient.session.list();
if (sessions.error) {
bot.sendMessage(chatId, `❌ Server health check failed: ${typeof sessions.error === 'string' ? sessions.error : JSON.stringify(sessions.error)}`);
} else {
const count = Array.isArray(sessions.data) ? sessions.data.length : 0;
bot.sendMessage(chatId, `✅ Opencode server is healthy\nActive sessions: ${count}`);
}
} catch (error) {
bot.sendMessage(chatId, `❌ Server health check failed: ${error.message}`);
}
return;
}
// Unknown command
if (text.startsWith('/')) {
bot.sendMessage(chatId, "❓ Unknown command. Type /help to see available commands.");
return;
}
// Echo non-command messages
if (msg.text) {
bot.sendMessage(chatId, `You said: "${msg.text}"`);
}
});
// Error handling
bot.on('polling_error', (error) => {
console.error('Polling error:', error.message);
});
bot.on('error', (error) => {
console.error('Bot error:', error.message);
});
console.log('Bot is running and ready to receive messages!');