Telegram Bot API in Python with an LLM Backend
Updated
Using the Telegram bot api python route takes four pieces: a token from BotFather, the python-telegram-bot library, an OpenAI-compatible client and a handler that joins them. Below is a working bot, then the changes that make it behave in real chats.

No card needed. After sign-up, claim $0.50 of free test credit with one click (once per person).
Get API keyKey points
- BotFather issues the bot token; the LLM endpoint needs a separate key. Store both as environment variables.
- python-telegram-bot v20 and later is async, so use AsyncOpenAI and await every call.
- Telegram caps a text message at 4,096 characters, so split long answers.
- Keep per-chat history short and cap concurrent model calls below 8.
What you are building
The setup for a telegram bot api python project is short. Telegram hosts the bot account and delivers messages to your script. Your script sends each message to a language model and posts the reply. You never run a model yourself, and you do not need a public server for development, because the bot can poll Telegram for updates from your laptop.
Here is the flow for one message:
- A user writes to the bot in a private chat or a group.
- Telegram queues the update; your script fetches it by long polling.
- Your handler sends the text plus recent history to
POST /v1/chat/completions. - The model answers; your handler sends the text back to the same chat.
The LLM side is an OpenAI-compatible endpoint at https://api.grokunfiltered.top/v1 with the model ID uncensored. It is one open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. It is text only and is not the official API of any large vendor.
Create the bot and collect the credentials
The Telegram token
Open a chat with the account called BotFather inside Telegram, send the command /newbot, pick a display name and then a username that ends in bot. BotFather replies with a token that looks like a number, a colon and a long string. Treat it as a password. If it leaks, ask BotFather to revoke it and issue a new one.
The LLM key
Sign up with Google or with email and password, then go to the API key page. You can claim $0.50 of trial credit with one click; it needs no payment, is valid for 7 days and is limited to one per person. A trial key allows 2 concurrent requests and 60 requests per minute, which is fine for a bot used by you and a few friends. For more, top up with USDT on TRC20 or USDC on Base from $20 upward; see pricing for the bonus tiers.
Install and export
pip install "python-telegram-bot>=20" openai
export TELEGRAM_TOKEN="paste-botfather-token-here"
export LLM_API_KEY="paste-llm-key-here"
These are two different secrets and they go to two different services. Do not commit either to a repository.
A minimal bot with polling
Version 20 of python-telegram-bot is built on asyncio, which means handlers are coroutines. That fits the async OpenAI client well. This bot answers every plain text message and ignores commands.
import os
from openai import AsyncOpenAI
from telegram import Update
from telegram.ext import (
ApplicationBuilder,
ContextTypes,
MessageHandler,
filters,
)
llm = AsyncOpenAI(
base_url="https://api.grokunfiltered.top/v1",
api_key=os.environ["LLM_API_KEY"],
)
async def reply(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = update.message.text
resp = await llm.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a direct, helpful assistant."},
{"role": "user", "content": text},
],
)
await update.message.reply_text(resp.choices[0].message.content[:4096])
app = ApplicationBuilder().token(os.environ["TELEGRAM_TOKEN"]).build()
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, reply))
app.run_polling()
Run it with python bot.py, open your bot in Telegram and write to it. The truncation to 4,096 characters is a blunt fix for the length limit of a Telegram text message; the next section handles it properly. If nothing arrives, check that you pressed Start in the chat and that the token has no trailing space.
Give the bot a memory
The model sees only what you send in each request, so a bot without history forgets the previous line. Store recent turns per chat in context.chat_data, a dictionary that python-telegram-bot keeps for each chat while the process runs.
MAX_TURNS = 12
SYSTEM = "You are a direct, helpful assistant."
async def reply(update: Update, context: ContextTypes.DEFAULT_TYPE):
history = context.chat_data.setdefault("history", [])
history.append({"role": "user", "content": update.message.text})
del history[:-MAX_TURNS]
resp = await llm.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}] + history,
)
answer = resp.choices[0].message.content or ""
history.append({"role": "assistant", "content": answer})
for i in range(0, len(answer), 4000):
await update.message.reply_text(answer[i:i + 4000])
This history lives in memory, so a restart wipes it. For a bot that must remember across restarts, write the list to SQLite or a JSON file keyed by chat ID. The context window is 100,000 tokens for prompt plus completion, far more than twelve turns will use. The reason to trim is money, not space: every old turn is billed as input on every new message.
Commands: reset, persona and help
Even a small bot needs a way to wipe its memory. Add a /reset command that clears the stored history for that chat, so a user can start a new topic without paying for the old one. Command handlers in python-telegram-bot take the same two arguments as message handlers.
from telegram.ext import CommandHandler
async def reset(update: Update, context: ContextTypes.DEFAULT_TYPE):
context.chat_data["history"] = []
await update.message.reply_text("Memory cleared.")
app.add_handler(CommandHandler("reset", reset))
The same pattern works for a /persona command that swaps the system prompt stored in chat_data. Register commands with BotFather using its command-list option so Telegram shows them in the menu next to the message box. Users find a visible command list far more often than a feature described in a pinned message.
Streaming replies by editing a message
Long answers feel slow if the user stares at nothing. Send a first message, then edit it as text arrives. Streaming uses server-sent events and is switched on with stream=True.
import time
async def reply_streaming(update, context):
msg = await update.message.reply_text("...")
stream = await llm.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": update.message.text}],
stream=True,
)
text, last = "", 0.0
async for chunk in stream:
if not chunk.choices:
continue
text += chunk.choices[0].delta.content or ""
if time.monotonic() - last > 1.0 and text:
await msg.edit_text(text[:4000])
last = time.monotonic()
if text:
await msg.edit_text(text[:4000])
Telegram rate-limits bots, so editing on every chunk will trigger errors. One edit per second is a safe starting point. Note that a streamed request keeps its concurrency slot until the stream finishes. If five people chat at once with streaming on, five slots stay busy for the length of each answer.
Limits, errors and group chats
A full key allows 8 concurrent requests and 300 requests per minute. When you pass a limit, the API answers HTTP 429. The error code concurrency means too many calls at once; rate_limited means the per-minute cap. A 429 with a Retry-After: 5 header marks temporary overload. Wrap the call in a small retry that waits and tries again, and guard the whole bot with an asyncio.Semaphore(6) if it will serve several chats.
In group chats, Telegram bots by default see only commands and mentions unless privacy mode is turned off in BotFather. Decide whether the bot should answer everything or only messages that mention it, and filter in the handler to avoid burning credit on conversations that are not meant for it.
Failed or refused requests are not charged, so a retry after an error does not double the bill. For a first check of the endpoint before any Telegram code, use the curl example on the quickstart page.
Keeping it running on a server
Polling from a laptop is fine until you close the lid. For a bot that should answer all day, run it on a small virtual machine or a home server under a process manager. On Linux, a systemd service with Restart=always brings the script back after a crash or reboot. In Docker, use a restart policy and pass the two secrets as environment variables, not baked into the image.
Log two things: the Telegram chat ID of each request and the X-Request-Id header from the API response. When a user says an answer never arrived, the request ID lets you find that exact call and send it to support if the problem is on the API side. Keep logs free of full message text if your users expect privacy.
Cost per message
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. A chat turn with 12 turns of history is usually larger than people expect. Suppose 2,000 input tokens (system prompt and history) and 400 output tokens:
- Input: 2,000 / 1,000,000 x $0.15 = $0.00030
- Output: 400 / 1,000,000 x $0.50 = $0.00020
- Per message: $0.00050
At 100 messages a day that is $0.05 a day, or $1.50 over 30 days. The $0.50 trial credit pays for about 1,000 such messages. The balance is returned in the X-Balance-USD header of each response, so you can have the bot warn you when it runs low. Credit never expires, which suits a hobby bot that is idle for weeks.
A final point on content: the model is tuned to answer without refusals for lawful adult use, and the one hard line is that nothing sexual involving minors is accepted. If your bot lives in public groups, write the rules you want into the system prompt and moderate as you would any bot.
More guides
Questions and answers
Which Python library should I use for the Telegram Bot API?
python-telegram-bot from version 20 is a common choice and is async. aiogram is another async library. Either works with the OpenAI SDK because the LLM call is separate from Telegram.
Do I need a server or webhook to run it?
No. run_polling() lets the bot fetch updates from your own machine. A webhook is only needed if you want Telegram to push updates to a public HTTPS address.
Why does my bot reply twice or not at all?
Running two copies of the same bot with the same token causes conflicts. Stop old processes, then check that the handler filter matches the message type you are sending.
What is the Telegram message length limit?
A text message can hold up to 4,096 characters. Split longer model answers into several messages, as in the history example above.