#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = ["python-telegram-bot[webhooks]==22.8"] # /// """An AI Telegram bot with no secrets on the VM. Telegram calls go through exe.dev's Telegram integration, which puts the bot token into each request on its way to api.telegram.org; model calls go through exe.dev's LLM integration, which adds the provider's key. The bot answers people you let in, in private chats and, when mentioned or replied to, in groups. It reads photos, PDFs and text files you send it, and remembers the last HISTORY messages of each chat in SQLite. /start claim the bot (the first link it logs) or accept an invite /invite a one-time link that lets someone else use the bot /open, /close let everyone in this group use it, or only invited people /forget clear what it remembers of this chat Settings, all optional: TELEGRAM_API the integration, default https://telegram.int.exe.xyz MODE polling (default) or webhook PUBLIC_URL https://.exe.xyz, for MODE=webhook LLM_API default https://llm.int.exe.xyz MODEL default claude-sonnet-5-5 (any model on the Messages API) PROMPT_FILE the system prompt, default prompt.md beside this file DB default data/bot.db beside this file HISTORY default 20; PORT default 8000 (webhook mode) https://exe.dev/deploy/telegram-bot """ import asyncio import base64 import html import logging import os import pathlib import secrets import sqlite3 from collections import defaultdict import httpx from telegram import BotCommand, Update from telegram.constants import ChatAction, ChatType, ParseMode from telegram.error import BadRequest from telegram.ext import (ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters) HERE = pathlib.Path(__file__).resolve().parent TELEGRAM = os.environ.get("TELEGRAM_API", "https://telegram.int.exe.xyz").rstrip("/") MODE = os.environ.get("MODE", "polling") PUBLIC_URL = os.environ.get("PUBLIC_URL", "").rstrip("/") LLM = os.environ.get("LLM_API", "https://llm.int.exe.xyz").rstrip("/") MODEL = os.environ.get("MODEL", "claude-sonnet-5-5") PROMPT_FILE = pathlib.Path(os.environ.get("PROMPT_FILE", HERE / "prompt.md")) DB = pathlib.Path(os.environ.get("DB", HERE / "data/bot.db")) HISTORY = int(os.environ.get("HISTORY", "20")) PORT = int(os.environ.get("PORT", "8000")) EARLIER_FILES = ("\n\nFiles sent earlier in the chat show as [sent ...]: you saw them when" " they arrived, but only the newest message's file is attached again.") IMAGE_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"} log = logging.getLogger("telegram-bot") chat_locks = defaultdict(asyncio.Lock) # one answer at a time per chat def db(): conn = sqlite3.connect(DB, timeout=10) conn.executescript(""" CREATE TABLE IF NOT EXISTS turns (id INTEGER PRIMARY KEY, chat INTEGER, role TEXT, content TEXT, at TEXT DEFAULT CURRENT_TIMESTAMP); CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, invited_by INTEGER, at TEXT DEFAULT CURRENT_TIMESTAMP); CREATE TABLE IF NOT EXISTS invites (code TEXT PRIMARY KEY, by INTEGER); CREATE TABLE IF NOT EXISTS open_chats (id INTEGER PRIMARY KEY); CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT); """) return conn def allowed(user_id, chat_id): with db() as conn: return bool(conn.execute("SELECT 1 FROM users WHERE id = ? UNION" " SELECT 1 FROM open_chats WHERE id = ?", (user_id, chat_id)).fetchone()) def new_invite(by): code = secrets.token_urlsafe(12) with db() as conn: conn.execute("INSERT INTO invites (code, by) VALUES (?, ?)", (code, by)) return code async def ask_claude(chat, who, text, attachment=None): """Add the message to the chat's memory, ask the model, remember the reply.""" note = f" [sent {attachment['note']}]" if attachment else "" with db() as conn: conn.execute("INSERT INTO turns (chat, role, content) VALUES (?, 'user', ?)", (chat, f"{who}:{note} {text}")) rows = conn.execute("SELECT role, content FROM turns WHERE chat = ?" " ORDER BY id DESC LIMIT ?", (chat, HISTORY)).fetchall() messages = [] for role, content in reversed(rows): # oldest first, same roles merged if messages and messages[-1]["role"] == role: messages[-1]["content"][0]["text"] += "\n\n" + content elif messages or role == "user": messages.append({"role": role, "content": [{"type": "text", "text": content}]}) if attachment and attachment.get("block"): messages[-1]["content"].insert(0, attachment["block"]) # files before text async with httpx.AsyncClient(timeout=300) as client: r = await client.post(LLM + "/v1/messages", headers={ "anthropic-version": "2023-06-01"}, json={ "model": MODEL, "max_tokens": 4000, "messages": messages, "system": (PROMPT_FILE.read_text() if PROMPT_FILE.exists() else "") + EARLIER_FILES}) r.raise_for_status() reply = "".join(b.get("text", "") for b in r.json()["content"]).strip() or "(no answer)" with db() as conn: conn.execute("INSERT INTO turns (chat, role, content) VALUES (?, 'assistant', ?)", (chat, reply)) return reply async def read_attachment(msg): """Download a photo or document through the integration's /file/ path.""" if msg.photo: f, mime, name = msg.photo[-1], "image/jpeg", "photo" elif msg.document: f, mime = msg.document, msg.document.mime_type or "" name = msg.document.file_name or "file" else: return None if (f.file_size or 0) > 20_000_000: # the Bot API's download limit return {"note": f"{name}, too big to read (over 20 MB)"} try: data = bytes(await (await f.get_file()).download_as_bytearray()) except Exception as e: log.warning("couldn't download %s: %s", name, e) return {"note": f"{name}, which couldn't be downloaded"} b64 = base64.standard_b64encode(data).decode() if mime in IMAGE_TYPES: return {"note": f"image {name}", "block": {"type": "image", "source": { "type": "base64", "media_type": mime, "data": b64}}} if mime == "application/pdf": return {"note": f"PDF {name}", "block": {"type": "document", "source": { "type": "base64", "media_type": mime, "data": b64}}} try: body = data.decode() except UnicodeDecodeError: return {"note": f"{name}, a {mime or 'binary'} file it can't read"} return {"note": f"file {name}", "block": {"type": "text", "text": f"\n{body[:100_000]}\n"}} def chunks(text, size=4000): """Split a reply into Telegram-sized messages, at line breaks when possible.""" while text: cut = text.rfind("\n", 0, size) if len(text) > size else len(text) cut = cut if cut > 0 else size yield text[:cut] text = text[cut:].lstrip("\n") async def send(msg, text): for part in chunks(text): try: # the prompt asks for Telegram's HTML; fall back to plain text await msg.reply_text(part, parse_mode=ParseMode.HTML) except BadRequest as e: if "parse" not in str(e).lower(): raise await msg.reply_text(part) async def on_message(update: Update, ctx: ContextTypes.DEFAULT_TYPE): msg, user, chat = update.effective_message, update.effective_user, update.effective_chat if not msg or not user: return text = msg.text or msg.caption or "" me = ctx.bot.username if chat.type != ChatType.PRIVATE: # in groups, only mentions and replies to it replied = msg.reply_to_message and msg.reply_to_message.from_user \ and msg.reply_to_message.from_user.id == ctx.bot.id if f"@{me}".lower() not in text.lower() and not replied: return text = text.replace(f"@{me}", "").strip() if not allowed(user.id, chat.id): log.info("ignored %s (id %s) in chat %s", user.full_name, user.id, chat.id) if chat.type == ChatType.PRIVATE: await msg.reply_text("This bot is private. Ask its owner for an invite.") return async with chat_locks[chat.id]: typing = asyncio.create_task(keep_typing(chat)) try: attachment = await read_attachment(msg) reply = await ask_claude(chat.id, user.first_name, text, attachment) except Exception as e: log.exception("answering") reply = html.escape(f"Sorry, that failed: {e}"[:500]) finally: typing.cancel() await send(msg, reply) async def keep_typing(chat): while True: # "typing…" lasts 5 seconds try: await chat.send_action(ChatAction.TYPING) except Exception: pass await asyncio.sleep(4) async def start(update: Update, ctx: ContextTypes.DEFAULT_TYPE): user, code = update.effective_user, (ctx.args or [""])[0] with db() as conn: row = conn.execute("DELETE FROM invites WHERE code = ? RETURNING by", (code,)).fetchone() if code else None if row: conn.execute("INSERT OR IGNORE INTO users (id, name, invited_by) VALUES (?, ?, ?)", (user.id, user.full_name, row[0])) log.info("%s (id %s) joined", user.full_name, user.id) if allowed(user.id, update.effective_chat.id): await update.effective_message.reply_text( f"Hi {user.first_name}! Ask me anything, or send a photo, PDF or text file.") else: await update.effective_message.reply_text( "This bot is private. Ask its owner for an invite.") async def invite(update: Update, ctx: ContextTypes.DEFAULT_TYPE): if not allowed(update.effective_user.id, 0): return link = f"https://t.me/{ctx.bot.username}?start={new_invite(update.effective_user.id)}" await update.effective_message.reply_text( f"Send this link to one person; it works once:\n{link}") async def open_close(update: Update, ctx: ContextTypes.DEFAULT_TYPE): chat, user = update.effective_chat, update.effective_user if chat.type == ChatType.PRIVATE or not allowed(user.id, 0): return opening = update.effective_message.text.startswith("/open") with db() as conn: conn.execute("INSERT OR IGNORE INTO open_chats (id) VALUES (?)" if opening else "DELETE FROM open_chats WHERE id = ?", (chat.id,)) await update.effective_message.reply_text( "Everyone here can now ask me things: mention me or reply to me." if opening else "Only invited people can use me here now.") async def forget(update: Update, ctx: ContextTypes.DEFAULT_TYPE): if not allowed(update.effective_user.id, update.effective_chat.id): return with db() as conn: conn.execute("DELETE FROM turns WHERE chat = ?", (update.effective_chat.id,)) await update.effective_message.reply_text("Forgotten.") async def post_init(app): me = app.bot log.info("connected to Telegram as @%s (id %s)", me.username, me.id) await me.set_my_commands([ BotCommand("forget", "Clear what the bot remembers of this chat"), BotCommand("invite", "A one-time link that lets someone use the bot"), BotCommand("open", "In a group: let everyone use the bot"), BotCommand("close", "In a group: only invited people"), ]) with db() as conn: owner = conn.execute("SELECT 1 FROM users").fetchone() code = conn.execute("SELECT value FROM settings WHERE key = 'claim'").fetchone() if not owner and not code: code = (new_invite(0),) conn.execute("INSERT INTO settings VALUES ('claim', ?)", code) if not owner: log.info("open this link to become the bot's owner: https://t.me/%s?start=%s", me.username, code[0]) def main(): logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") logging.getLogger("httpx").setLevel(logging.WARNING) # one line per poll otherwise DB.parent.mkdir(parents=True, exist_ok=True) db().close() app = (ApplicationBuilder() .token("exe-dev-integration") # not used: exe.dev adds the real one .base_url(lambda _token: TELEGRAM) .base_file_url(lambda _token: TELEGRAM + "/file") .post_init(post_init) .concurrent_updates(True) .build()) app.add_handler(CommandHandler("start", start)) app.add_handler(CommandHandler("invite", invite)) app.add_handler(CommandHandler(["open", "close"], open_close)) app.add_handler(CommandHandler("forget", forget)) app.add_handler(MessageHandler( (filters.TEXT | filters.PHOTO | filters.Document.ALL) & ~filters.COMMAND, on_message)) if MODE == "webhook": secret = DB.parent / "webhook-secret" if not secret.exists(): secret.write_text(secrets.token_urlsafe(32)) secret.chmod(0o600) app.run_webhook(listen="0.0.0.0", port=PORT, url_path="telegram", webhook_url=f"{PUBLIC_URL}/telegram", secret_token=secret.read_text().strip(), allowed_updates=["message"]) else: app.run_polling(allowed_updates=["message"]) if __name__ == "__main__": main()