DEV Community

Cover image for How to Build a Telegram Bot with Python and AI (2026)
Serhii Kalyna
Serhii Kalyna

Posted on • Originally published at kalyna.pro

How to Build a Telegram Bot with Python and AI (2026)

A Telegram bot is one of the most practical ways to deploy an AI assistant — your users already have Telegram, there's no app to install, and the Bot API is simple. This guide builds a fully functional AI bot with python-telegram-bot and the Claude API, including commands, inline keyboards, conversation history, error handling, and systemd deployment.

Prerequisites

  • Python 3.10+
  • Telegram Bot Token from @botfather
  • Anthropic API key (ANTHROPIC_API_KEY)

Step 1: Create the Bot

Open Telegram, find @botfather, send /newbot, and save the token.

Step 2: Install Dependencies

pip install python-telegram-bot anthropic
Enter fullscreen mode Exit fullscreen mode

Step 3: Basic Bot Structure

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

TELEGRAM_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
claude = anthropic.Anthropic()

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("Hi! I'm an AI assistant. Send me a message!")

def main() -> None:
    app = Application.builder().token(TELEGRAM_TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.run_polling()

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Step 4: Conversation History

MAX_HISTORY = 20

def get_history(context):
    return context.chat_data.setdefault("history", [])

async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
    history = get_history(context)
    history.append({"role": "user", "content": update.message.text})
    if len(history) > MAX_HISTORY:
        del history[:len(history) - MAX_HISTORY]

    response = claude.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        system="You are a helpful AI assistant in Telegram. Be concise.",
        messages=history,
    )
    answer = response.content[0].text
    history.append({"role": "assistant", "content": answer})
    await update.message.reply_text(answer)
Enter fullscreen mode Exit fullscreen mode

Step 5: Custom Commands

async def summarize(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not context.args:
        await update.message.reply_text("Usage: /summarize <text>")
        return
    text = " ".join(context.args)
    resp = claude.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=512,
        messages=[{"role": "user", "content": f"Summarize in 3 bullet points:\n{text}"}],
    )
    await update.message.reply_text(resp.content[0].text)
Enter fullscreen mode Exit fullscreen mode

Step 6: Inline Keyboards

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CallbackQueryHandler

async def mode(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [[
        InlineKeyboardButton("Concise", callback_data="mode_concise"),
        InlineKeyboardButton("Detailed", callback_data="mode_detailed"),
    ]]
    await update.message.reply_text("Choose mode:", reply_markup=InlineKeyboardMarkup(keyboard))

async def mode_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    context.chat_data["mode"] = query.data.replace("mode_", "")
    await query.edit_message_text(f"Mode set: {context.chat_data['mode']}")
Enter fullscreen mode Exit fullscreen mode

Step 7: Deploy with systemd

# /etc/systemd/system/telegram-ai-bot.service
[Unit]
Description=Telegram AI Bot
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/telegram-bot
ExecStart=/home/ubuntu/telegram-bot/venv/bin/python bot.py
Environment=TELEGRAM_BOT_TOKEN=7123...
Environment=ANTHROPIC_API_KEY=sk-ant-...
Restart=always

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode
sudo systemctl enable --now telegram-ai-bot
Enter fullscreen mode Exit fullscreen mode

Summary

You built a production-ready AI Telegram bot with conversation history, custom commands, inline keyboards, and systemd deployment.

Originally published at kalyna.pro

Top comments (0)