- bot.js: 5 retries with 5s delay on init, graceful fallback to null - errorHandler.js: 5 retries on 404 (invalid token), stops polling after max retries but keeps process alive for admin panel - config.js: BOT_TOKEN missing logs warning instead of process.exit - index.js: bot handlers only registered when bot is available, admin panel always starts regardless of bot status
46 lines
1.5 KiB
JavaScript
46 lines
1.5 KiB
JavaScript
import TelegramBot from "node-telegram-bot-api";
|
|
import config from "../config/config.js";
|
|
import logger from "../utils/logger.js";
|
|
|
|
const MAX_RETRIES = 5;
|
|
const RETRY_DELAY_MS = 5000;
|
|
|
|
let bot = null;
|
|
let botAvailable = false;
|
|
|
|
const initBot = async () => {
|
|
if (!config.BOT_TOKEN) {
|
|
logger.warn('No BOT_TOKEN configured. Running in admin-only mode.');
|
|
return null;
|
|
}
|
|
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
|
try {
|
|
const instance = new TelegramBot(config.BOT_TOKEN, {polling: true});
|
|
await new Promise((resolve, reject) => {
|
|
const timeout = setTimeout(() => {
|
|
instance.stopPolling();
|
|
reject(new Error('Bot initialization timeout'));
|
|
}, 15000);
|
|
instance.getMe().then(() => {
|
|
clearTimeout(timeout);
|
|
resolve();
|
|
}).catch(reject);
|
|
});
|
|
logger.info({ attempt }, 'Bot initialized successfully');
|
|
botAvailable = true;
|
|
return instance;
|
|
} catch (error) {
|
|
logger.warn({ attempt, maxRetries: MAX_RETRIES, err: error.message }, 'Bot initialization failed');
|
|
if (attempt < MAX_RETRIES) {
|
|
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
|
|
}
|
|
}
|
|
}
|
|
logger.error({ maxRetries: MAX_RETRIES }, 'All bot initialization attempts failed. Running in admin-only mode.');
|
|
return null;
|
|
};
|
|
|
|
bot = await initBot();
|
|
|
|
export { botAvailable };
|
|
export default bot; |