DEVSAIO

Build an AI Telegram bot in Python

Create a Telegram bot that answers with Claude or GPT, remembers recent messages per chat, and limits spending.

DEVSAIO team · 2 min read
Share on X

1. Create the bot

Message @BotFather on Telegram, send /newbot, follow the prompts, and copy the bot token.

2. Install

bash
pip install python-telegram-bot openai
export TELEGRAM_TOKEN=123:ABC
export DEVSAIO_API_KEY=YOUR_KEY

3. The bot (bot.py)

python
import os
from collections import defaultdict, deque
from openai import AsyncOpenAI
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, ContextTypes, filters

ai = AsyncOpenAI(base_url="https://devsaio.lol/v1", api_key=os.environ["DEVSAIO_API_KEY"])
history = defaultdict(lambda: deque(maxlen=12))  # last 12 messages per chat
SYSTEM = {"role": "system", "content": "You are a helpful, friendly Telegram assistant. Keep replies under 150 words."}

async def start(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Hi! Ask me anything. /reset clears our conversation.")

async def reset(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    history[update.effective_chat.id].clear()
    await update.message.reply_text("Conversation cleared.")

async def on_message(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    chat = update.effective_chat.id
    text = update.message.text[:2000]
    history[chat].append({"role": "user", "content": text})
    await ctx.bot.send_chat_action(chat, "typing")
    r = await ai.chat.completions.create(model="claude-haiku-5-5", messages=[SYSTEM, *history[chat]], max_tokens=400)
    answer = r.choices[0].message.content
    history[chat].append({"role": "assistant", "content": answer})
    await update.message.reply_text(answer)

app = Application.builder().token(os.environ["TELEGRAM_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("reset", reset))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_message))
app.run_polling()

4. Run

bash
python bot.py

Keeping costs safe

  • Use a cheap model like claude-haiku-5-5 for casual chat; switch to claude-sonnet-4-6 for a premium command.
  • Cap input length and max_tokens, as above.
  • Give the bot's key a monthly spending limit.
  • For public bots, add a per-user daily message limit.
Try it with one API key

Claude, GPT, Gemini, DeepSeek, image and video models through one OpenAI- and Anthropic-compatible endpoint. Prepaid, pay only for what you use.

Keep reading