ProjectsNode.jsTelegramBot
Build a Telegram Bot with Node.js in 10 Minutes
4.165 min read
Md Nasim Sheikh
Telegram bots are superior to Discord bots for personal utility because they live in your pocket. You can text your bot "Add $5 for coffee" or "Remind me to buy milk".
Advertisement
The Setup
- Open Telegram and message @BotFather.
- Send
/newbot. - Name it (e.g.,
MyToDoBot). - Copy the HTTP API Token.
The Code
We use the telegraf library, which is a modern wrapper around the Telegram API.
npm install telegraf dotenv
require('dotenv').config();
const { Telegraf } = require('telegraf');
const bot = new Telegraf(process.env.BOT_TOKEN);
// 1. Start Command
bot.start((ctx) => ctx.reply('Welcome! I am your personal assistant.'));
// 2. Help Command
bot.help((ctx) => ctx.reply('Send me a sticker'));
// 3. Handling specific text
bot.on('sticker', (ctx) => ctx.reply('👍'));
bot.hears('hi', (ctx) => ctx.reply('Hey there'));
// 4. Echo function
bot.on('text', (ctx) => {
// Access user message
const userMessage = ctx.message.text;
ctx.reply(`You said: ${userMessage}`);
});
bot.launch();
// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
Middleware (The Power Feature)
Telegraf uses middleware (like Express.js). You can run logic before every message.
bot.use(async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
console.log('Response time: %sms', ms);
});
Advertisement
Deployment
Don't run this on your laptop. Deploy it to a $5 VPS using Docker (see our DevOps course!).
Quiz
Quick Quiz
What is the role of @BotFather in the Telegram ecosystem?
Conclusion
This is just the "Hello World". You can connect this to OpenAI to make a ChatGPT wrapper, or to Google Sheets to track spending. The API is limitless.
Written by
Md Nasim Sheikh
Software Developer at softexForge
Verified Author150+ Projects
Published: