-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram_bot.js
More file actions
231 lines (202 loc) Β· 7.42 KB
/
telegram_bot.js
File metadata and controls
231 lines (202 loc) Β· 7.42 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
const TelegramBot = require('node-telegram-bot-api');
const express = require('express');
require('dotenv').config();
const app = express();
const token = process.env.BOT_TOKEN;
const webAppUrl = process.env.MINI_APP_URL;
const botUsername = process.env.BOT_USERNAME;
// Validate required environment variables
if (!token) {
console.error('BOT_TOKEN is not set in environment variables');
process.exit(1);
}
if (!botUsername) {
console.error('BOT_USERNAME is not set in environment variables');
process.exit(1);
}
// Add CORS middleware
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
// Add express middleware
app.use(express.json());
// Health check endpoint
app.get('/', (req, res) => {
res.send('Bot is running!');
});
app.get('/health', (req, res) => {
res.status(200).json({ status: 'healthy', timestamp: new Date() });
});
// Initialize bot with polling options
let bot;
try {
bot = new TelegramBot(token, {
polling: {
interval: 300,
autoStart: true,
params: {
timeout: 10
}
},
filepath: false,
request: {
timeout: 30000
}
});
// Add reconnection logic
let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 5;
const RECONNECT_DELAY = 5000;
function handlePollingError(error) {
console.error('Polling error:', error.message);
if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
reconnectAttempts++;
console.log(`Attempting to reconnect (${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})...`);
setTimeout(() => {
bot.startPolling();
}, RECONNECT_DELAY);
} else {
console.error('Max reconnection attempts reached. Please check your bot token and internet connection.');
process.exit(1);
}
}
// Enhanced error handlers
bot.on('polling_error', handlePollingError);
bot.on('error', handlePollingError);
bot.on('webhook_error', handlePollingError);
// Handle successful connection
bot.on('connected', () => {
console.log('Bot successfully connected to Telegram');
reconnectAttempts = 0;
});
// Handle disconnection
bot.on('disconnected', () => {
console.log('Bot disconnected from Telegram');
handlePollingError(new Error('Bot disconnected'));
});
// Handle /start command
bot.onText(/\/start(?:\s+(\w+))?/, async (msg, match) => {
try {
const referralCode = match[1];
const appUrl = referralCode
? `https://t.me/MemeBattleArenaBot/app?startapp=${referralCode}`
: webAppUrl;
const options = {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{
text: 'π Launch App',
url: appUrl
}]
]
}
};
const welcomeMessage = referralCode
? `Welcome ${msg.from.first_name}! π\n\nYou've been invited to join MemeIndex! Click the Launch button below to start your journey and claim your referral bonus! π`
: `Welcome ${msg.from.first_name}! π\n\nI'm your gateway to the MemeIndex Mini App. Click the button below to start exploring the world of meme tokens! π`;
await bot.sendMessage(msg.chat.id, welcomeMessage, options);
} catch (error) {
await bot.sendMessage(
msg.chat.id,
`Welcome ${msg.from.first_name}! π\n\nI'm your gateway to the MemeIndex Mini App. Click the button below to start exploring! π`,
{
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{
text: 'π Launch App',
url: webAppUrl
}]
]
}
}
);
}
});
// Handle inline queries
bot.on('inline_query', async (query) => {
try {
if (!query.query) {
await bot.answerInlineQuery(query.id, [{
type: 'article',
id: '1',
title: 'Error',
description: 'No referral code provided',
input_message_content: {
message_text: 'Sorry, no referral code was provided.'
}
}]);
return;
}
// Extract the referral code from the query
const referralCode = query.query.trim();
if (!referralCode) {
await bot.answerInlineQuery(query.id, [{
type: 'article',
id: '1',
title: 'Error',
description: 'Invalid referral code format',
input_message_content: {
message_text: 'Sorry, the referral code format is invalid.'
}
}]);
return;
}
// Create the share message
const messageText =
`Hidden door to the MemeIndex Treasury found... Let's open it together!`;
// Create the inline keyboard with the referral link
const inlineKeyboard = {
inline_keyboard: [
[{
text: 'Unlock the Treasury',
url: `https://t.me/MemeBattleArenaBot/app?startapp=${referralCode}`
}]
]
};
// Image URL for treasury door - optional
const imageUrl = "https://i.ibb.co/qjzDmnG/treasury-door.jpg";
// Answer the inline query
await bot.answerInlineQuery(query.id, [{
type: 'article',
id: '1',
title: 'Share MemeIndex Invitation',
description: 'Share this invitation with your friends',
thumb_url: imageUrl,
input_message_content: {
message_text: messageText,
parse_mode: 'HTML'
},
reply_markup: inlineKeyboard
}], {
cache_time: 0,
is_personal: false
});
} catch (error) {
await bot.answerInlineQuery(query.id, [{
type: 'article',
id: '1',
title: 'Error',
description: 'Failed to generate invitation message',
input_message_content: {
message_text: 'Sorry, there was an error generating the invitation message.'
}
}]);
}
});
} catch (error) {
console.error('Failed to initialize bot:', error);
process.exit(1);
}
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Bot server is running on port ${PORT}`);
});