The onLaunch callback of bot.launch(...) called in a wrong order causing "Error: Bot is not running!".
Author: Edgar-P-yanCreated Jul 1, 2024Updated May 5, 2026
Context
- Telegraf.js Version: 4.16.3
- Node.js Version: v22.2.0
- Operating System: macOS 14.5
Minimal Example Code Reproducing the Issue
Both of these snippets reproduce the error:
const bot = new Telegraf(configs.get('BOT_TOKEN'));
bot.launch().catch((err) => console.error(err));
bot.stop();
// Error: Bot is not running!
// at Telegraf.stop (./node_modules/telegraf/lib/telegraf.js:218:19)const bot = new Telegraf(configs.get('BOT_TOKEN'));
new Promise((resolve) => {
bot
.launch(() => resolve(undefined))
.catch((err) => {
console.error(err);
});
}).then(() => {
bot.stop();
});
// Error: Bot is not running!
// at Telegraf.stop (./node_modules/telegraf/lib/telegraf.js:218:19)Expected Behavior
I expected the bot.stop() call not to throw an error. And also the onLaunch callback to be called after the long-polling/webhooks are initialized.
Current Behavior
The onLaunch callback is called before initialising the polling and webhooks https://github.com/telegraf/telegraf/blob/48a475d034ede5e01070a7e2b6b15dc48c3d3f9b/src/telegraf.ts#L286, which is why .stop() method throws an error if called in a little window of time between the onLaunch callback and when the bot actually launches.
An ugly workaround
Right now i do this to wait until the bot is actually launched and established the long polling and webhooks:
await new Promise((resolve, reject) => {
const checkInterval = setInterval(() => {
try {
// check the private properties to determine if the polling and webhooks are initialized
if (bot['polling'] || bot['webhookServer']) {
clearInterval(checkInterval);
resolve(undefined);
}
} catch (e) {
clearInterval(checkInterval);
reject(e);
}
}, 500);
bot.launch().catch((err) => {
clearInterval(checkInterval);
console.error(err);
});
});
console.log('Now bot actually launched and listens to updates');
bot.stop(); // works fine, does not throwError Message and Logs (export DEBUG='telegraf:*')
// Error: Bot is not running!
// at Telegraf.stop (./node_modules/telegraf/lib/telegraf.js:218:19)Source: telegraf/telegraf