Hey everyone! I’m struggling with my first Node.js Telegram bot. It just won’t start up!
I set up a new project and installed the needed packages (telegraf and nodemon). My package.json looks like this:
{
"projectName": "telegramBotAttempt",
"version": "0.1.0",
"main": "bot.js",
"scripts": {
"dev": "nodemon bot.js"
},
"dependencies": {
"nodemon": "^4.0.1",
"telegraf": "3.39"
}
}
And here’s my simple bot code in bot.js:
const { TelegramBot } = require('telegraf')
const myBot = new TelegramBot('bot_token_here')
myBot.command('hello', (context) => {
console.log(context);
})
myBot.start()
When I try to run it with npm run dev, I get an error. I even tried switching to a newer Node.js version (20.11.0), but no luck. Any ideas what I’m doing wrong? Thanks in advance for your help!
I’ve run into similar issues when starting out with Telegram bots. Here’s what worked for me:
First, double-check your bot token. Sometimes a typo there can cause silent failures. Also, make sure you’re using the latest Telegraf version - I had problems with older ones.
For the code, try this structure:
const { Telegraf } = require('telegraf');
const bot = new Telegraf('YOUR_BOT_TOKEN');
bot.command('hello', (ctx) => {
ctx.reply('Hello there!');
});
bot.launch().then(() => {
console.log('Bot is running!');
}).catch((err) => {
console.error('Failed to start bot:', err);
});
This setup includes error handling, which can help pinpoint issues. If it still doesn’t work, try running it without nodemon first to isolate the problem. Hope this helps!
hey laura, looks like ur using the wrong import for telegraf. try this instead:
const { Telegraf } = require(‘telegraf’)
const bot = new Telegraf(‘bot_token_here’)
also, use bot.launch() instead of bot.start(). that shud fix it. good luck!
I noticed you’re using an older version of Telegraf (3.39). This could be causing compatibility issues with newer Node.js versions. Try updating to the latest Telegraf version by running ‘npm install telegraf@latest’.
Also, your import statement and bot initialization are incorrect. Here’s the correct syntax:
const { Telegraf } = require(‘telegraf’);
const bot = new Telegraf(‘YOUR_BOT_TOKEN’);
Lastly, use bot.launch() instead of bot.start(). This method properly starts the bot and returns a promise.
If you’re still having trouble, check your bot token and ensure you have a stable internet connection. Sometimes network issues can prevent the bot from connecting to Telegram’s servers.