The Fastest Way to Build a Telegram Bot Natively
Telegram bots are powerful tools for automation, customer support, and integrations. While frameworks like python-telegram-bot exist, the fastest and most lightweight approach is using Telegram's native Bot API via HTTP requests. This tutorial demonstrates how to build a high-performance bot with minimal dependencies.
1. Prerequisites
- A Telegram account and @botfather to create your bot
- Node.js (or any HTTP-capable language)
- cURL or Postman for testing
2. Getting Your Bot Token
- Open Telegram, search for
@BotFather. - Send
/newbotand follow prompts. - Copy the API token (e.g.,
123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11).
3. Core Concepts
Telegramโs Bot API is RESTful. You interact via:
-
HTTPS Endpoints:
https://api.telegram.org/bot<TOKEN>/METHOD_NAME - Webhooks or Long Polling for updates
4. Native Implementation (Node.js)
A. Setup
const axios = require('axios');
const BOT_TOKEN = 'YOUR_BOT_TOKEN';
const API_URL = `https://api.telegram.org/bot${BOT_TOKEN}`;
B. Sending a Message
async function sendMessage(chatId, text) {
try {
const response = await axios.post(`${API_URL}/sendMessage`, {
chat_id: chatId,
text: text,
});
console.log('Message sent:', response.data);
} catch (error) {
console.error('Error:', error.response?.data);
}
}
// Usage
sendMessage(123456789, 'Hello from native Telegram Bot!');
C. Handling Incoming Messages (Long Polling)
let offset = 0;
async function getUpdates() {
try {
const response = await axios.post(`${API_URL}/getUpdates`, {
offset: offset,
timeout: 30, // Long polling timeout (seconds)
});
const updates = response.data.result;
if (updates.length > 0) {
offset = updates[updates.length - 1].update_id + 1;
processUpdates(updates);
}
} catch (error) {
console.error('Polling error:', error.message);
} finally {
getUpdates(); // Continuously poll
}
}
function processUpdates(updates) {
updates.forEach(update => {
if (update.message) {
const chatId = update.message.chat.id;
const text = update.message.text;
sendMessage(chatId, `You said: ${text}`);
}
});
}
// Start polling
getUpdates();
5. Webhook Alternative (Faster for Production)
Webhooks eliminate polling delays. Prerequisites:
- A public HTTPS server (e.g., Ngrok for testing).
A. Set Webhook URL
async function setWebhook(url) {
try {
const response = await axios.post(`${API_URL}/setWebhook`, {
url: url,
});
console.log('Webhook set:', response.data);
} catch (error) {
console.error('Webhook error:', error.response?.data);
}
}
// Example (using Ngrok)
setWebhook('https://your-ngrok-url.ngrok.io/webhook');
B. Handle Webhook Requests
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhook', (req, res) => {
const update = req.body;
if (update.message) {
const chatId = update.message.chat.id;
const text = update.message.text;
sendMessage(chatId, `[Webhook] Echo: ${text}`);
}
res.sendStatus(200);
});
app.listen(3000, () => console.log('Webhook server running'));
6. Advanced: Inline Keyboards
Telegram supports interactive buttons. Hereโs how to add them:
async function sendKeyboard(chatId, text) {
const keyboard = {
reply_markup: {
inline_keyboard: [
[
{ text: 'Button 1', callback_data: 'btn1' },
{ text: 'Button 2', callback_data: 'btn2' },
],
],
},
};
await axios.post(`${API_URL}/sendMessage`, {
chat_id: chatId,
text: text,
...keyboard,
});
}
// Handle button presses (Webhook)
app.post('/webhook', (req, res) => {
const update = req.body;
if (update.callback_query) {
const chatId = update.callback_query.message.chat.id;
const data = update.callback_query.data;
sendMessage(chatId, `You pressed: ${data}`);
}
res.sendStatus(200);
});
7. Performance Tips
-
Batch Updates: Use
getUpdateswithlimit=100to fetch multiple updates at once. - Rate Limiting: Telegram allows ~30 messages/second. Implement delays if needed.
- Webhooks > Polling: Webhooks reduce latency and server load.
8. Conclusion
Building a Telegram bot natively is fast and dependency-free. Key takeaways:
- Use direct HTTP calls for maximum speed.
- Prefer Webhooks for production.
- Leverage inline keyboards for interactivity.
Now go build your bot! ๐
Further Reading:
๐ Stop Writing Boilerplate Prompts
If you want to skip the setup and code 10x faster with complete AI architecture patterns, grab my Senior React Developer AI Cookbook ($19). It includes Server Action prompt libraries, UI component generation loops, and hydration debugging strategies.
Browse all 10+ developer products at the Apollo AI Store | Or snipe Solana tokens free via @ApolloSniper_Bot.
Top comments (0)