Hey there, fellow developer! Ready to dive into the world of Telegram bots? You're in for a treat. In this guide, we'll walk through creating a Telegram bot using JavaScript. Telegram's Bot API is powerful, flexible, and perfect for adding a dash of automation to your chat experience. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get our project off the ground:
mkdir telegram-bot cd telegram-bot npm init -y npm install node-telegram-bot-api
Time to birth your bot:
/newbot
and follow the promptsLet's breathe life into our bot:
const TelegramBot = require('node-telegram-bot-api'); const token = 'YOUR_API_TOKEN'; const bot = new TelegramBot(token, {polling: true});
Now for the fun part – making your bot do stuff:
// Handle /start command bot.onText(/\/start/, (msg) => { bot.sendMessage(msg.chat.id, "Hey there! I'm your new bot."); }); // Respond to messages bot.on('message', (msg) => { bot.sendMessage(msg.chat.id, `You said: ${msg.text}`); });
Let's spice things up with some fancy keyboards:
// Inline keyboard bot.onText(/\/options/, (msg) => { bot.sendMessage(msg.chat.id, "Choose an option:", { reply_markup: { inline_keyboard: [[ { text: "Option 1", callback_data: "1" }, { text: "Option 2", callback_data: "2" } ]] } }); }); // Handle callback queries bot.on('callback_query', (callbackQuery) => { bot.answerCallbackQuery(callbackQuery.id, {text: `You chose option ${callbackQuery.data}`}); });
Long polling is great for getting started, but for production, consider using a webhook. It's more efficient and scalable. To switch to a webhook:
const bot = new TelegramBot(token, {webHook: {port: process.env.PORT}}); bot.setWebHook(`${url}/bot${token}`);
Don't forget to add some error handling to keep your bot robust:
bot.on('polling_error', (error) => { console.log(error); });
Fire up your bot with node index.js
and start chatting with it on Telegram. Go wild, try to break it – that's how we improve!
When you're ready to unleash your bot on the world, consider platforms like Heroku or DigitalOcean. Remember to keep your API token secret and use environment variables.
And there you have it! You've just created a Telegram bot that can chat, respond to commands, and even use fancy keyboards. The sky's the limit from here – add API integrations, natural language processing, or whatever tickles your fancy.
Remember, the best way to learn is by doing. So go forth and bot! If you get stuck, the Telegram Bot API documentation is your best friend.
Happy coding, and may your bot bring joy to chat rooms everywhere!