tududi/backend/modules/telegram/telegramInitializer.js
Chris 828b5ebc0d
fix: prevent Telegram polling errors from blocking container startup (#989) (#1019)
This fix addresses the issue where the container gets stuck in an endless
loop of Telegram connection errors when the bot is configured but Telegram
is unreachable during startup.

Changes:
- Add 10-second startup delay before initializing Telegram polling to allow
  the system to settle
- Implement exponential backoff (5s to 5min) when Telegram connection fails
- Add rate-limited error logging (max once per minute per user) to reduce
  log spam and prevent event loop blocking
- Track error state per user to manage backoff independently
- Auto-reset error state on successful connection
- Update tests to account for new error state tracking

Fixes #989
2026-04-13 20:44:27 +03:00

44 lines
1.5 KiB
JavaScript

const telegramPoller = require('./telegramPoller');
const { User } = require('../../models');
const { setConfig, getConfig } = require('../../config/config');
const config = getConfig();
async function initializeTelegramPolling() {
if (config.environment === 'test' || config.disableTelegram) {
return;
}
// Add a delay before starting Telegram polling to allow the system to settle
// and prevent immediate error floods if Telegram is temporarily unreachable
const startupDelay = 10000; // 10 seconds
setTimeout(async () => {
try {
// Find users with configured Telegram tokens
const usersWithTelegram = await User.findAll({
where: {
telegram_bot_token: {
[require('sequelize').Op.ne]: null,
},
},
});
if (usersWithTelegram.length > 0) {
console.log(
`Initializing Telegram polling for ${usersWithTelegram.length} user(s)...`
);
// Add each user to the polling list
for (const user of usersWithTelegram) {
await telegramPoller.addUser(user);
}
}
} catch (error) {
console.error(
'Error initializing Telegram polling:',
error.message
);
}
}, startupDelay);
}
module.exports = { initializeTelegramPolling };