Introduction
Telegram bots are the easiest way to put a Python script in front of real users — no frontend, no deployment complexity, and a free API. This post builds a bot with commands, inline buttons, conversation state, and an AI chat mode.
Setup
- Open Telegram, search for @BotFather, send
/newbot, follow the prompts. - You get a token like
123456:ABC-DEF.... - Install the library:
pip install python-telegram-bot
Step 1: Echo bot (hello world)
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters
TOKEN = "YOUR_BOT_TOKEN"
async def start(update: Update, context):
await update.message.reply_text("Hello! I'm your bot. Send me anything.")
async def echo(update: Update, context):
await update.message.reply_text(f"You said: {update.message.text}")
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
app.run_polling()
Run it: python bot.py. Open Telegram, find your bot, send /start. It replies.
Step 2: Commands with arguments
async def calc(update: Update, context):
if not context.args:
await update.message.reply_text("Usage: /calc 2 + 3")
return
expr = " ".join(context.args)
try:
result = eval(expr) # only for trusted input!
await update.message.reply_text(f"= {result}")
except Exception:
await update.message.reply_text("Invalid expression")
app.add_handler(CommandHandler("calc", calc))
context.args is a list of space-separated arguments after the command.
Step 3: Inline buttons (keyboards)
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
async def menu(update: Update, context):
keyboard = [
[InlineKeyboardButton("Option A", callback_data="a")],
[InlineKeyboardButton("Option B", callback_data="b")],
[InlineKeyboardButton("Visit site", url="https://techwithgalvan.in")],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("Choose:", reply_markup=reply_markup)
async def button_handler(update: Update, context):
query = update.callback_query
await query.answer()
await query.edit_message_text(f"You chose: {query.data}")
app.add_handler(CommandHandler("menu", menu))
app.add_handler(CallbackQueryHandler(button_handler))
Inline buttons turn a chat into an interactive app — menus, confirmations, quizzes.
Step 4: Conversation state
from telegram.ext import ConversationHandler, CommandHandler, MessageHandler, filters
# States
NAME, AGE = range(2)
async def start(update, context):
await update.message.reply_text("What's your name?")
return NAME
async def get_name(update, context):
context.user_data["name"] = update.message.text
await update.message.reply_text("How old are you?")
return AGE
async def get_age(update, context):
context.user_data["age"] = update.message.text
await update.message.reply_text(f"Thanks, {context.user_data['name']}! You're {context.user_data['age']}.")
return ConversationHandler.END
conv = ConversationHandler(
entry_points=[CommandHandler("register", start)],
states={
NAME: [MessageHandler(filters.TEXT, get_name)],
AGE: [MessageHandler(filters.TEXT, get_age)],
},
fallbacks=[CommandHandler("cancel", lambda u, c: ConversationHandler.END)],
)
app.add_handler(conv)
ConversationHandler manages multi-step flows. context.user_data persists per user across messages.
Step 5: AI chat mode
import os
from openai import OpenAI
client = OpenAI()
async def ai_chat(update: Update, context):
user_msg = update.message.text
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant. Be concise."},
{"role": "user", "content": user_msg},
],
)
reply = response.choices[0].message.content
await update.message.reply_text(reply)
# Only trigger AI mode when not a command
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, ai_chat))
Now your bot is an AI assistant. Combine with MCP tools for capabilities.
Step 6: Send files and images
async def send_file(update: Update, context):
await update.message.reply_document(document=open("report.pdf", "rb"))
await update.message.reply_photo(photo=open("chart.png", "rb"))
await update.message.reply_voice(voice=open("audio.ogg", "rb"))
Great for bots that generate reports, charts, or audio.
Step 7: Webhooks (production)
Polling (run_polling) is fine for dev. For production, use webhooks:
app.run_webhook(
listen="0.0.0.0",
port=8443,
url_path="webhook",
webhook_url="https://yourdomain.com/webhook",
)
Requires HTTPS (use nginx + Let’s Encrypt, or Cloudflare Tunnel). Webhooks are more efficient and scale better.
Step 8: Deploy for free
Option A: Railway/Render — push to GitHub, deploy. Free tier available.
Option B: Cloudflare Workers — use the python-telegram-bot webhook mode with a Worker. See Cloudflare Workers AI for the pattern.
Option C: VPS + systemd — run python bot.py as a service on a $5/mo VPS.
Common mistakes
- Blocking the event loop —
python-telegram-botv20+ is async. Don’t use syncrequestsinside handlers; useaiohttporhttpx. - Not handling errors — add an error handler:
async def error_handler(update, context): print(f"Error: {context.error}") app.add_error_handler(error_handler) - Storing state in global variables — use
context.user_dataor a database. - Exposing the token — never commit it. Use env vars.
- No rate limiting — bots get spammed. Add per-user cooldowns.
Key Concepts
- BotFather = creates bots, gives tokens
- Handler = function triggered by a message/command
context.user_data= per-user persistent state- ConversationHandler = multi-step flows
- Webhook = production-grade event delivery
- Inline keyboard = interactive buttons in chat
What to Try Next
- Add AI chat with tool calling.
- Combine with MCP — bot as an MCP client.
- Build a URL shortener bot — send a URL, get a short link.
- Add auth for admin-only commands.
FAQ
python-telegram-bot vs aiogram?
python-telegram-bot is more beginner-friendly with great docs. aiogram is faster and more modern (async-first, better for high-traffic bots). For most bots, python-telegram-bot. For high-scale, aiogram.
Can I run a bot for free?
Yes — Telegram’s API is free. Hosting: Railway/Render free tiers, or a $5 VPS. The bot itself costs nothing.
How do I handle files users send?
Use filters.Document, filters.PHOTO, etc.:
async def handle_doc(update, context):
file = await update.message.document.get_file()
await file.download_to_drive("received.pdf")
await update.message.reply_text("Got it!")