
Telegram bots are a powerful way to automate tasks, interact with users, and integrate services. In this guide, we’ll walk you through creating a Telegram bot using Node.js and the node-telegram-bot-api library.
1. Setting Up Your Telegram Bot
Step 1: Create a Bot on Telegram
- Open Telegram and search for @BotFather.
- Start a chat and type /newbot
- Follow the prompts to name your bot and create a unique username.
- Once completed, you’ll receive an API token. Save this for later!
2. Setting Up Your Node.js Project
Step 2: Initialize a Node.js Project
Make sure you have Node.js installed. Then, create a new project
mkdir telegram-bot
cd telegram-bot
npm init -y
Step 3: Install Dependencies
We’ll use node-telegram-bot-api to interact with the Telegram API:
npm install node-telegram-bot-api dotenv
dotenv helps manage environment variables securely.
3. Writing the Bot Code
Step 4: Create an index.js file
Inside your project folder, create a file called index.js and add the following:
require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');
const TOKEN = process.env.BOT_TOKEN;
const bot = new TelegramBot(TOKEN, { polling: true });
bot.on('message', (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(
chatId,
`Hello, ${msg.from.first_name}! How can I help you today?`
);
});
Step 5: Create a .env File
Store your bot’s API token securely by creating a .env file in your project root:
BOT_TOKEN=your-telegram-bot-token-here
4. Running Your Bot
Step 6: Start Your Bot
Run the following command in the terminal:
node index.js
Your bot is now live! Send a message to your bot on Telegram, and it will respond.
5. Adding More Features
Step 7: Handling Commands
Enhance your bot by adding custom commands:
bot.onText(/\/start/, (msg) => {
bot.sendMessage(
msg.chat.id,
'Welcome! Use /help to see available commands.'
);
});
Step 8: Adding Inline Keyboards
Make interactions more engaging with inline keyboards:
const options = {
reply_markup: {
inline_keyboard: [
[{ text: 'Visit Website', url: 'https://example.com' }]
]
}
};
bot.onText(/\/info/, (msg) => {
bot.sendMessage(msg.chat.id, 'Click the button below:', options);
});
Final Thoughts
You’ve just created a functional Telegram bot using Node.js and node-telegram-bot-api ! From here, you can integrate APIs, store user data, or deploy your bot to a cloud server.
What features will you add to your bot next? Let us know in the comments!