2 min read

Python Telegram Bot Guide

This guide demonstrates how to create a Telegram bot using the python-telegram-bot library. It covers setting up the bot, handling commands, and processing text messages using the modern asynchronous API (v20+).

Modules Used:

  • python-telegram-bot: The wrapper for the Telegram Bot API.
  • python-dotenv: To securely manage the bot token.
  • logging: To log events and errors.

Prerequisites

  1. Open Telegram and search for @BotFather.
  2. Send the command /newbot.
  3. Follow the instructions to name your bot.
  4. Copy the HTTP API Token provided by BotFather.

Installation

pip install python-telegram-bot python-dotenv

Setup

Create a .env file in your project directory:

TELEGRAM_TOKEN=your_actual_token_here

The Code

Save this as telegram_bot.py.

import logging
import os
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters

# 1. Load Config
load_dotenv()
TOKEN = os.getenv('TELEGRAM_TOKEN')

# 2. Configure Logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)

# --- Command Handlers ---

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Responds to /start command"""
    await context.bot.send_message(
        chat_id=update.effective_chat.id, 
        text="Hello! I am a Python bot. Send me a message and I'll echo it back!"
    )

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Echoes the user message"""
    await context.bot.send_message(
        chat_id=update.effective_chat.id, 
        text=f"You said: {update.message.text}"
    )

if __name__ == '__main__':
    if not TOKEN:
        print("Error: TELEGRAM_TOKEN not found in .env")
        exit(1)

    # 3. Build Application
    application = ApplicationBuilder().token(TOKEN).build()

    # 4. Add Handlers
    start_handler = CommandHandler('start', start)
    # Filter for text that is NOT a command
    echo_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), echo)

    application.add_handler(start_handler)
    application.add_handler(echo_handler)

    # 5. Run
    print("Bot is running...")
    application.run_polling()

Usage

  1. Run the script:
    python telegram_bot.py
  2. Open your bot in Telegram and click Start.
  3. Send any text message to see the echo response.

programming/python/python