How to Build a Telegram Bot in Python

March 24, 2026 · 8 min read · Complete Template Included

Telegram bots are one of the most practical automation tools you can build. They can monitor servers, send alerts, process data, and interact with users — all through a chat interface you already use.

This guide gives you a complete, copy-paste bot template that handles commands, messages, and errors. You'll have a working bot in 5 minutes.

Prerequisites

Step 1: Create Your Bot with BotFather

1 Open Telegram and message @BotFather

2 Send /newbot and follow the prompts

3 Copy the API token (looks like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11)

💡 Tip: Store your token in an environment variable, never hardcode it. Use export TELEGRAM_TOKEN="your_token" in your shell.

Step 2: Install the Library

pip install python-telegram-bot

Step 3: The Complete Bot Template

Here's a production-ready template with proper error handling, logging, and a clean structure:

#!/usr/bin/env python3
"""
Telegram Bot Template — Ready to customize.

Setup:
1. Message @BotFather → /newbot → get token
2. export TELEGRAM_TOKEN="your_token"
3. python bot.py
"""

import os
import logging
from telegram import Update
from telegram.ext import (
    Application, CommandHandler, MessageHandler,
    filters, ContextTypes
)

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

TOKEN = os.environ["TELEGRAM_TOKEN"]


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle /start command."""
    await update.message.reply_text(
        "👋 Hi! I'm your automation bot.\n\n"
        "Commands:\n"
        "/help — Show available commands\n"
        "/status — Check bot status\n"
        "/echo <text> — Echo your message\n"
    )


async def help_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle /help command."""
    await update.message.reply_text(
        "Available commands:\n"
        "• /start — Welcome message\n"
        "• /help — This help\n"
        "• /status — Bot status\n"
        "• /echo <text> — Echo text back\n"
        "\nSend any message and I'll respond!"
    )


async def status(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle /status command."""
    await update.message.reply_text("✅ Bot is running!")


async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle /echo command."""
    text = " ".join(context.args) if context.args else "Nothing to echo!"
    await update.message.reply_text(f"🔊 {text}")


async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle regular messages — customize this!"""
    text = update.message.text
    # Add your logic here: AI responses, data lookups, etc.
    await update.message.reply_text(f"You said: {text}")


async def error_handler(update, context: ContextTypes.DEFAULT_TYPE):
    """Log errors."""
    logger.error(f"Error: {context.error}", exc_info=context.error)


def main():
    app = Application.builder().token(TOKEN).build()

    # Commands
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("help", help_cmd))
    app.add_handler(CommandHandler("status", status))
    app.add_handler(CommandHandler("echo", echo))

    # Messages
    app.add_handler(
        MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)
    )

    # Error handler
    app.add_error_handler(error_handler)

    logger.info("🤖 Bot started!")
    app.run_polling()


if __name__ == "__main__":
    main()

Step 4: Run Your Bot

export TELEGRAM_TOKEN="your_token_here"
python bot.py

Open Telegram, find your bot, and send /start. You should see the welcome message.

Extending Your Bot

The template above is a starting point. Here are common extensions:

Add Scheduled Messages

from telegram.ext import ApplicationBuilder
import asyncio

async def daily_report(context: ContextTypes.DEFAULT_TYPE):
    """Send daily report at scheduled time."""
    await context.bot.send_message(
        chat_id=YOUR_CHAT_ID,
        text="📊 Daily Report:\n• Uptime: 99.9%\n• Requests: 1,234"
    )

# In main(), after building app:
app.job_queue.run_daily(
    daily_report,
    time=datetime.time(hour=9, minute=0)  # 9:00 AM
)

Add Inline Keyboards

from telegram import InlineKeyboardButton, InlineKeyboardMarkup

async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [
        [InlineKeyboardButton("📊 Stats", callback_data="stats"),
         InlineKeyboardButton("⚙️ Settings", callback_data="settings")],
        [InlineKeyboardButton("❓ Help", callback_data="help")]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text("Choose an option:", reply_markup=reply_markup)

Connect to an API

import httpx

async def weather(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Fetch weather and send to user."""
    city = " ".join(context.args) or "London"
    async with httpx.AsyncClient() as client:
        r = await client.get(f"https://wttr.in/{city}?format=3")
        await update.message.reply_text(r.text)

Deployment Options

  1. VPS (cheapest): Run with nohup python bot.py & or use systemd
  2. Docker: Wrap in a container for easy deployment anywhere
  3. Serverless: Use webhooks instead of polling for cloud functions
💡 Production tip: Use systemd service for auto-restart on crashes. Create /etc/systemd/system/telegram-bot.service with Restart=always.

Common Patterns

Want 50+ More Automation Scripts?

The AI Agent Toolkit includes Telegram bots, Slack integrations, web scrapers, DevOps tools, and more — all copy-paste ready.

Get the Toolkit — $19