fix: bot no longer crashes container on invalid token
- 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
This commit is contained in:
@@ -2,17 +2,45 @@ import TelegramBot from "node-telegram-bot-api";
|
||||
import config from "../config/config.js";
|
||||
import logger from "../utils/logger.js";
|
||||
|
||||
const initBot = () => {
|
||||
try {
|
||||
const bot = new TelegramBot(config.BOT_TOKEN, {polling: true});
|
||||
logger.info('Bot initialized successfully');
|
||||
return bot;
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Failed to initialize bot');
|
||||
process.exit(1);
|
||||
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;
|
||||
};
|
||||
|
||||
const bot = initBot();
|
||||
bot = await initBot();
|
||||
|
||||
export { botAvailable };
|
||||
export default bot;
|
||||
Reference in New Issue
Block a user