Introduction to Node Telegram Bot API
Node Telegram Bot API is a powerful platform that allows developers to build Telegram bots using Node.js. It is widely used for creating bots that can respond to messages, perform various tasks, and integrate with other services.
Getting Started
To start using node-telegram-bot-api
, you first need to install it via npm:
npm install node-telegram-bot-api
Let’s set up a basic bot:
const TelegramBot = require('node-telegram-bot-api'); const token = 'YOUR_TELEGRAM_BOT_TOKEN'; const bot = new TelegramBot(token, { polling: true }); bot.on('message', (msg) => { const chatId = msg.chat.id; bot.sendMessage(chatId, 'Hello, welcome to the bot!'); });
Handling Different Types of Messages
Node Telegram Bot API provides various methods to handle different message types:
bot.onText(//start/, (msg) => { bot.sendMessage(msg.chat.id, 'Welcome! Type /help to see available commands.'); }); bot.onText(//help/, (msg) => { bot.sendMessage(msg.chat.id, 'Available commands: /start, /help, /echo [message]'); }); bot.onText(//echo (.+)/, (msg, match) => { const resp = match[1]; bot.sendMessage(msg.chat.id, resp); });
Advanced Features
Here’s how you can use some advanced features such as inline keyboards and sending photos:
bot.onText(//inline/, (msg) => { const opts = { reply_markup: { inline_keyboard: [ [{ text: 'Option 1', callback_data: '1' }], [{ text: 'Option 2', callback_data: '2' }] ] } }; bot.sendMessage(msg.chat.id, 'Choose an option:', opts); }); bot.on('callback_query', (callbackQuery) => { const msg = callbackQuery.message; bot.sendMessage(msg.chat.id, 'You selected: ' + callbackQuery.data); }); bot.onText(//photo/, (msg) => { bot.sendPhoto(msg.chat.id, 'https://example.com/photo.jpg', { caption: 'Here is your photo' }); });
Building a Sample App
Below is an example of a simple app that uses various APIs:
const TelegramBot = require('node-telegram-bot-api'); const token = 'YOUR_TELEGRAM_BOT_TOKEN'; const bot = new TelegramBot(token, { polling: true }); bot.onText(//start/, (msg) => { bot.sendMessage(msg.chat.id, 'Hello! You can manage tasks with this bot. Use /addtask [task] to add a task.'); }); bot.onText(//addtask (.+)/, (msg, match) => { const task = match[1]; // Normally you'd save the task to a database bot.sendMessage(msg.chat.id, 'Task added: ' + task); }); bot.onText(//tasks/, (msg) => { // Normally you'd fetch tasks from a database bot.sendMessage(msg.chat.id, 'Here are your tasks: 1. Sample Task'); }); bot.onText(//completetask (.+)/, (msg, match) => { const taskIndex = match[1]; // Normally you'd update the task status in the database bot.sendMessage(msg.chat.id, 'Task ' + taskIndex + ' completed!'); });
With these examples, you should be able to get started with building your own Telegram bots using node-telegram-bot-api
.
Happy coding!
Hash: 8daf8c21dc6e07e65e8a5d59467e30b3fb27138b7db161a8896c1eef156b8241