Cover
Foto profil

Bembi Pramudya

@beemind

Hi! I am Bembi Pramudya, a developer from Indonesia. I spend my free time building software, tinkering with web tools, and exploring frontend design.

DeveloperIndonesiabembee.cc
Tutorial

Building a Telegram AI Bot with 9Router

Bembi Pramudya
Bembi PramudyaSep 28, 2026 · 6 min read
Building a Telegram AI Bot with 9Router

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 strangers

Finally, 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.