
Having a Telegram bot that answers with AI is not as complicated as it sounds. The key: separate three parts — Telegram as the interface, Python as the bridge, and an AI gateway as the brain.
First step, create a bot via BotFather and keep the token safe. This token is like a password — never commit it to Git or share it with anyone.
# Fetch the latest updates from Telegram (long-polling)
import requests
TOKEN = "YOUR_TOKEN_HERE"
url = f"https://api.telegram.org/bot{TOKEN}/getUpdates"
print(requests.get(url, timeout=60).json())The nicest part: for the brain I use 9Router, a gateway compatible with the OpenAI API. That means one codebase can use dozens of models — Qwen, Claude, Gemini — just change the model name in the config.
# Send a message to the AI via 9Router (OpenAI format)
import requests
r = requests.post("http://127.0.0.1:20128/v1/chat/completions",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={"model": "qwen3.5-plus",
"messages": [{"role": "user", "content": "Hello!"}]})
print(r.json()["choices"][0]["message"]["content"])Do not forget security: lock the bot with an allowlist of your Telegram user ID, so strangers cannot spend your AI quota.
ALLOWED_IDS = {123456789} # replace with your user ID
if message["from"]["id"] not in ALLOWED_IDS:
return # ignore messages from strangersFinally, run the bot as a systemd service with Restart=always so it stays online 24/7 and revives itself after a crash. A simple bot, but with tidy architecture that is easy to extend.

