python-telegram-bot

22.7 · active · verified Sun Mar 29

This library provides a pure Python, asynchronous interface for the Telegram Bot API. It's compatible with Python versions 3.10+. It features convenience methods, shortcuts, and high-level classes within the `telegram.ext` submodule to simplify bot development. It supports all types and methods of the Telegram Bot API 9.5 and receives frequent updates, with new releases typically coming out every few weeks/months.

Warnings

Install

Imports

Quickstart

This quickstart code sets up a simple echo bot that replies to `/start` and `/help` commands, and echoes back any other text message it receives. It demonstrates the use of `Application`, `CommandHandler`, and `MessageHandler` with filters. Your bot token should be provided via the `TELEGRAM_BOT_TOKEN` environment variable.

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

# Enable logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)

logger = logging.getLogger(__name__)


async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Sends a message when the command /start is issued."""
    user = update.effective_user
    await update.message.reply_html(
        f"Hi {user.mention_html()}!\nI'm an echo bot. Send me anything!",
    )


async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Sends a message when the command /help is issued."""
    await update.message.reply_text("Help! Send me a message and I will echo it back!")


async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Echo the user message."""
    await update.message.reply_text(update.message.text)


async def main() -> None:
    """Start the bot."""
    # Replace with your bot's token from BotFather. Get from environment variable.
    BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
    if not BOT_TOKEN:
        raise ValueError("TELEGRAM_BOT_TOKEN environment variable not set.")

    # Create the Application and pass it your bot's token.
    application = Application.builder().token(BOT_TOKEN).build()

    # On different commands - add handlers
    application.add_handler(CommandHandler("start", start_command))
    application.add_handler(CommandHandler("help", help_command))

    # On non command messages - echo the message on Telegram
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    # Run the bot until the user presses Ctrl-C
    logger.info("Starting bot polling...")
    await application.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

view raw JSON →