Skip to content
AI Agent How-To

Home ›Connect agents to apps

How to Connect an AI Agent to Telegram (python-telegram-bot)

Intermediate ~6 min read Last tested October 2026

Updated 2026-10-27

This guide connects an AI agent to Telegram using the official Bot API and the community-maintained python-telegram-bot library (v22.x). Your bot receives text messages via long polling, runs an LLM (optionally with tools), and replies in the chat. Last tested 2026-10-27.

Docs used:

Prerequisites

Steps

1. Create a bot token with BotFather

  1. In Telegram, open a chat with @BotFather.
  2. Send /newbot, follow the prompts, and copy the HTTP API token BotFather returns.
  3. Store it as an environment variable (never commit it):
export TELEGRAM_BOT_TOKEN="123456:ABC..."
export OPENAI_API_KEY="sk-..."

2. Install dependencies

pip install "python-telegram-bot>=22.0" openai

3. Build a minimal agent bot

The pattern below follows the official echobot structure: Application.builder(), handlers, and run_polling().

# telegram_agent.py
import logging
import os
from collections import defaultdict

from openai import OpenAI
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters

logging.basicConfig(level=logging.INFO)
llm = OpenAI()
HISTORY: dict[int, list[dict]] = defaultdict(list)

SYSTEM = "You are a concise Telegram assistant. Keep replies short."

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("Send me a message and I will answer.")

async def on_text(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat_id = update.effective_chat.id
    user_text = update.message.text
    HISTORY[chat_id].append({"role": "user", "content": user_text})
    messages = [{"role": "system", "content": SYSTEM}, *HISTORY[chat_id][-12:]]
    reply = llm.chat.completions.create(
        model="gpt-4.1-mini",
        messages=messages,
    ).choices[0].message.content
    HISTORY[chat_id].append({"role": "assistant", "content": reply})
    await update.message.reply_text(reply)

def main() -> None:
    app = Application.builder().token(os.environ["TELEGRAM_BOT_TOKEN"]).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text))
    app.run_polling(allowed_updates=Update.ALL_TYPES)

if __name__ == "__main__":
    main()

Run it:

python telegram_agent.py

Open your bot in Telegram (use the t.me/... link from BotFather) and send a message.

4. Add tools

Replace the single chat.completions.create call with your tool loop from Build your first AI agent in Python. Useful tools: web search, Notion, or Gmail drafts (run those on a server, not a laptop, if the bot is always on).

5. Persist memory per chat

The in-memory HISTORY dict resets when the process restarts. For production:

  • Key history by update.effective_chat.id (shown above).
  • In n8n, use {{ $('Telegram Trigger').item.json.message.chat.id }} as the memory session key when you move the agent to no-code.

6. Deploy for 24/7 use

Long polling needs a process that stays online. Run the script on a small VPS or container with outbound HTTPS. For webhook mode instead of polling, install the optional [webhooks] extra documented in python-telegram-bot dependencies and expose an HTTPS URL Telegram can reach.

Common errors

Unauthorized / 401 on startup: Invalid TELEGRAM_BOT_TOKEN. Copy a fresh token from BotFather (/token).

Bot never receives messages: You messaged the wrong bot, or the process is not running. Polling stops when the script exits.

Conflict: terminated by other getUpdates request: Two processes use the same bot token with polling. Stop the duplicate worker.

Replies time out in groups: By default, bots in groups only see commands unless you disable privacy mode via BotFather /setprivacy → Disable when the bot must read all messages (respect Telegram’s terms and user expectations).

Rate limits from OpenAI: Add backoff or shorten history. See Fix: AI agent stuck in a loop for step caps.

FAQ

Do I need a public URL for Telegram?

No for this guide. Long polling (run_polling) only needs outbound internet from your machine. Webhooks require HTTPS and the optional webhooks dependency.

Which Python library should I use?

python-telegram-bot v22.x is async-first and tracks the current Bot API. It is the maintained successor to older sync wrappers.

Can one bot serve many users?

Yes. Use chat_id (or user.id for DMs) to separate conversation state. Never share one global message list across users.