Beginner's Guide to Telegram Bot API (2026)
Build your first Telegram bot from scratch with code examples
Start Building with Hypereal
Access Kling, Flux, Sora, Veo & more through a single API. Free credits to start, scale to millions.
No credit card required • 100k+ developers • Enterprise ready
Beginner's Guide to Telegram Bot API in 2026
Telegram bots can automate tasks, send notifications, process payments, run quizzes, and even serve as full AI assistants -- all through the Telegram Bot API. With over 900 million monthly active users, Telegram is one of the best platforms for building bots that people actually use.
This guide walks you through creating a Telegram bot from scratch, covering everything from getting your bot token to handling commands, sending media, and deploying to production.
What Can Telegram Bots Do?
Before writing code, here is what the Bot API supports:
| Capability | Description |
|---|---|
| Text messages | Send and receive plain text and formatted messages |
| Commands | Handle /start, /help, and custom commands |
| Inline keyboards | Interactive buttons within messages |
| Media | Send photos, videos, audio, documents, and stickers |
| Payments | Accept payments through Telegram's built-in payment system |
| Webhooks | Receive real-time updates via HTTP callbacks |
| Group management | Moderate groups, pin messages, ban users |
| Inline mode | Let users invoke your bot from any chat with @yourbot query |
| Mini Apps | Full web applications that run inside Telegram |
Step 1: Create Your Bot with BotFather
Every Telegram bot starts with BotFather, the official bot for managing bots.
- Open Telegram and search for
@BotFather. - Send
/newbot. - Choose a display name (e.g., "My First Bot").
- Choose a username ending in
bot(e.g.,my_first_demo_bot). - BotFather will reply with your HTTP API token. It looks like this:
7123456789:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw
Save this token securely. Anyone with this token can control your bot.
Step 2: Send Your First Message
You can interact with the Bot API using plain HTTP requests. Let's test it with cURL:
# Replace YOUR_BOT_TOKEN with the token from BotFather
# Replace CHAT_ID with your Telegram user ID
curl "https://api.telegram.org/botYOUR_BOT_TOKEN/sendMessage" \
-d "chat_id=CHAT_ID" \
-d "text=Hello from my first bot!"
To find your chat ID, send any message to your bot, then call:
curl "https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates"
Look for the chat.id field in the response.
Step 3: Build a Bot with Python
The python-telegram-bot library is the most popular Python wrapper for the Telegram Bot API.
Install the Library
pip install python-telegram-bot
Basic Bot with Command Handlers
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
# Command handlers
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Welcome! I'm your bot. Use /help to see what I can do."
)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
help_text = """
Available commands:
/start - Start the bot
/help - Show this help message
/echo <text> - Echo your message back
/weather <city> - Get weather info
"""
await update.message.reply_text(help_text)
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_text = " ".join(context.args) if context.args else "You didn't say anything!"
await update.message.reply_text(user_text)
# Handle regular text messages
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = update.message.text
await update.message.reply_text(f"You said: {text}")
def main():
app = Application.builder().token("YOUR_BOT_TOKEN").build()
# Register handlers
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("help", help_command))
app.add_handler(CommandHandler("echo", echo))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
# Start polling for updates
print("Bot is running...")
app.run_polling()
if __name__ == "__main__":
main()
Run the bot:
python bot.py
Open Telegram, find your bot, and send /start. It should respond immediately.
Step 4: Add Inline Keyboards
Inline keyboards let you add interactive buttons to messages:
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import CallbackQueryHandler, ContextTypes
async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
keyboard = [
[
InlineKeyboardButton("Option 1", callback_data="option_1"),
InlineKeyboardButton("Option 2", callback_data="option_2"),
],
[
InlineKeyboardButton("Visit Website", url="https://example.com"),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("Choose an option:", reply_markup=reply_markup)
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer() # Acknowledge the button press
if query.data == "option_1":
await query.edit_message_text("You selected Option 1!")
elif query.data == "option_2":
await query.edit_message_text("You selected Option 2!")
# Register handlers
app.add_handler(CommandHandler("menu", menu))
app.add_handler(CallbackQueryHandler(button_callback))
Step 5: Send Media Files
Bots can send photos, videos, documents, and more:
async def send_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Send from URL
await update.message.reply_photo(
photo="https://example.com/image.jpg",
caption="Here's a photo from the web!"
)
async def send_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Send a local file
with open("report.pdf", "rb") as doc:
await update.message.reply_document(
document=doc,
caption="Here's your report."
)
async def send_video(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_video(
video="https://example.com/video.mp4",
caption="Check out this video!"
)
Step 6: Build a Bot with Node.js
If you prefer JavaScript, the telegraf library is the most popular choice:
npm install telegraf
const { Telegraf, Markup } = require("telegraf");
const bot = new Telegraf("YOUR_BOT_TOKEN");
// Command handlers
bot.start((ctx) => {
ctx.reply("Welcome! Use /help to see available commands.");
});
bot.help((ctx) => {
ctx.reply(`Available commands:
/start - Start the bot
/help - Show help
/menu - Show options menu`);
});
// Inline keyboard example
bot.command("menu", (ctx) => {
ctx.reply(
"Choose an option:",
Markup.inlineKeyboard([
[Markup.button.callback("Option A", "action_a")],
[Markup.button.callback("Option B", "action_b")],
[Markup.button.url("Visit Site", "https://example.com")],
])
);
});
// Handle button callbacks
bot.action("action_a", (ctx) => {
ctx.answerCbQuery();
ctx.editMessageText("You chose Option A!");
});
bot.action("action_b", (ctx) => {
ctx.answerCbQuery();
ctx.editMessageText("You chose Option B!");
});
// Handle text messages
bot.on("text", (ctx) => {
ctx.reply(`You said: ${ctx.message.text}`);
});
bot.launch();
console.log("Bot is running...");
// Graceful shutdown
process.once("SIGINT", () => bot.stop("SIGINT"));
process.once("SIGTERM", () => bot.stop("SIGTERM"));
Step 7: Set Up Webhooks for Production
Polling works for development, but production bots should use webhooks for better performance:
# Using python-telegram-bot with webhooks
from telegram.ext import Application
app = Application.builder().token("YOUR_BOT_TOKEN").build()
# Register your handlers here...
# Start webhook
app.run_webhook(
listen="0.0.0.0",
port=8443,
url_path="YOUR_BOT_TOKEN",
webhook_url=f"https://your-domain.com/{YOUR_BOT_TOKEN}"
)
Or set up the webhook manually:
curl "https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook" \
-d "url=https://your-domain.com/webhook/YOUR_BOT_TOKEN"
Deployment Options
| Platform | Cost | Setup Difficulty | Best For |
|---|---|---|---|
| Railway | Free tier | Easy | Quick deployment |
| Render | Free tier | Easy | Simple bots |
| AWS Lambda | Free tier | Medium | Event-driven bots |
| Google Cloud Run | Free tier | Medium | Scalable bots |
| VPS (Hetzner, DigitalOcean) | $4-5/mo | Medium | Full control |
| Fly.io | Free tier | Easy | Global deployment |
Deploy to Railway
# Install Railway CLI
npm install -g @railway/cli
# Login and deploy
railway login
railway init
railway up
Add your BOT_TOKEN as an environment variable in the Railway dashboard.
Bot API Rate Limits
Keep these limits in mind when building your bot:
| Limit | Value |
|---|---|
| Messages to a user | 30 per second |
| Messages to a group | 20 per minute |
| Bulk messages | 30 messages per second across all chats |
| File upload | 50 MB max |
| File download | 20 MB max |
| Inline query results | 50 results max |
Frequently Asked Questions
How much does the Telegram Bot API cost? The Telegram Bot API is completely free. There are no usage fees, no rate-based pricing, and no premium tiers.
Can my bot access message history? Bots can only see messages sent after they were added to a group, and only if they have the appropriate permissions. They cannot read message history.
How do I make my bot work in groups?
Add your bot to a group and make sure it has the necessary permissions. Use MessageHandler to respond to messages or set the bot to only respond to commands.
Can I accept payments through my bot?
Yes, Telegram supports native payments through Stripe and other providers. Use the sendInvoice method to create payment requests.
How do I keep my bot token secure?
Never hardcode your token in source code. Use environment variables or a secrets manager. If your token is compromised, regenerate it immediately via BotFather with /revoke.
Wrapping Up
The Telegram Bot API is one of the most developer-friendly bot platforms available. With free unlimited usage, excellent documentation, and support for everything from simple command bots to full Mini Apps, it is an ideal platform for building automated tools and services.
If you are building a Telegram bot that generates AI media like images, videos, or talking avatars, try Hypereal AI free -- 35 credits, no credit card required. The API integrates easily with any Telegram bot for on-demand AI content generation.
Related Articles
Start Building Today
Get 35 free credits on signup. No credit card required. Generate your first image in under 5 minutes.
