Updated
Telegram Bot API Documentation: Connect an LLM Backend
The official telegram bot api documentation tells you how to receive messages and send replies; it does not tell you what should write the replies. This guide wires a Telegram bot to an OpenAI-compatible text API with about 60 lines of Python.

How the two APIs fit together
Two separate services are involved, and it helps to keep them apart in your head.
- Telegram's Bot API is an HTTPS interface at
api.telegram.org. You create a bot with BotFather, which gives you a token, and then call methods such asgetUpdatesto receive messages andsendMessageto reply. - The LLM API is where the reply text comes from. This one is OpenAI-compatible:
POST /v1/chat/completionsathttps://api.uncensoredimage.cc/v1, with the modeluncensoredand your key as a Bearer token.
Your bot is the glue between them. A message arrives from Telegram, your code adds it to that chat's history, asks the LLM for a reply, and posts the answer back. One clarification, since the domain name might suggest otherwise: this API is text only. It writes text, including image prompts if you want them, but it does not generate images, audio or video.
Step 1: create the bot and get a key
Open a chat with BotFather inside Telegram, send the command to create a new bot, and follow the prompts. It returns a token that looks like a number, a colon and a long string. Treat it like a password and keep it out of source control.
For the LLM side, sign up on the API key page, using Google or an email and password. You can claim $0.50 of trial credit with one click there. It is valid for 7 days, needs no payment details, and is one per person. Paid top-ups on this site are crypto only: USDT on TRC20 or USDC on Base, any whole amount from $20 to $500.
Step 2: a working long-polling bot
Long polling is the easiest way to start because it needs no public server. The bot asks Telegram for new updates in a loop, and Telegram holds the connection open until something arrives or the timeout passes. Install the two dependencies first with pip install requests openai.
import os
import threading
import requests
from openai import OpenAI
TG = "https://api.telegram.org/bot" + os.environ["TELEGRAM_TOKEN"]
llm = OpenAI(
base_url="https://api.uncensoredimage.cc/v1",
api_key=os.environ["LLM_API_KEY"],
)
SYSTEM = "You are a friendly assistant in a Telegram chat. Keep replies short."
MAX_TURNS = 12 # user+assistant pairs kept per chat
history = {} # chat_id -> list of messages
slots = threading.Semaphore(6) # stay below the 8-concurrent limit
def send(chat_id, text):
# Telegram messages are capped at 4096 characters
for i in range(0, len(text), 4000):
requests.post(TG + "/sendMessage",
json={"chat_id": chat_id, "text": text[i:i + 4000]},
timeout=30)
def handle(chat_id, text):
msgs = history.setdefault(chat_id, [])
msgs.append({"role": "user", "content": text})
del msgs[:-MAX_TURNS * 2]
try:
with slots:
requests.post(TG + "/sendChatAction",
json={"chat_id": chat_id, "action": "typing"},
timeout=10)
r = llm.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}] + msgs,
max_tokens=500,
)
reply = r.choices[0].message.content or "..."
msgs.append({"role": "assistant", "content": reply})
send(chat_id, reply)
except Exception as exc:
send(chat_id, "Something went wrong, please try again in a moment.")
print("error:", exc)
offset = None
while True:
params = {"timeout": 30}
if offset:
params["offset"] = offset
data = requests.get(TG + "/getUpdates", params=params, timeout=40).json()
for upd in data.get("result", []):
offset = upd["update_id"] + 1
msg = upd.get("message")
if msg and msg.get("text"):
threading.Thread(target=handle,
args=(msg["chat"]["id"], msg["text"])).start()
Set TELEGRAM_TOKEN and LLM_API_KEY in your environment, run the file, and message your bot. Each incoming text starts a thread, so two people chatting at once do not block each other. Store the system prompt in one place, and adjust it as you learn how your users talk to the bot: a line like "answer in the language the user writes in" changes behaviour more than most settings.
What the code is doing, and why
The offset
Telegram keeps updates until you confirm them. Passing offset = update_id + 1 on the next call tells it you have seen everything up to that point. Skip this and the bot answers the same message forever.
Trimmed history
The model has no memory between calls, so each request resends the conversation. Capping it at 12 turn pairs keeps the input small, which matters because you pay for every input token on every call. A Telegram group chat can get long quickly, and an unbounded list would grow your costs and eventually hit the 100,000-token context window.
The semaphore
A full key allows 8 concurrent requests. If ten users write in the same second, unthrottled threads would exceed that and some calls would come back as HTTP 429 with the code concurrency. The semaphore queues the extra ones in your process instead. Trial keys allow only 2 concurrent requests and 60 per minute, so drop the semaphore to 2 while testing on trial credit.
Typing indicator
The sendChatAction call shows "typing" in the chat while the model works, which makes a slow reply feel intentional.
Handling limits and errors
The LLM API returns 429 for two reasons you can tell apart. The error code rate_limited means too many requests per minute (300 on a full key). The code concurrency means too many at once. A third case is temporary overload, which also returns 429 but with a Retry-After: 5 header. The OpenAI SDK retries some transient errors on its own, and you can raise that with its max_retries option when you build the client.
Failed or refused requests are not charged, so a retry after an error does not cost you twice. On the Telegram side, sendMessage can return an error if the bot was blocked by the user or removed from a group. Catch it and move on instead of crashing the loop. Add a small sleep and a try block around the getUpdates call too, so a brief network drop does not end the process.
If you want live token-by-token output, the API supports streaming with stream: true over SSE. Telegram has no native streaming, so the usual trick is to send a first message and edit it every second or so with editMessageText. Be aware that edits are rate limited by Telegram, so batching them is wise.
Moving from polling to a webhook
Polling is fine for small bots. When you have a public HTTPS server, switch to a webhook: call Telegram's setWebhook method with your URL, and Telegram will POST each update to you. The handler logic stays the same; only the way updates arrive changes. Return a 200 response quickly and do the LLM call in a background task, because a slow reply inside the webhook request can cause Telegram to resend the update.
The API documentation lists every parameter this endpoint accepts, including tool calling and JSON mode. JSON mode (response_format: {"type": "json_object"}) is useful for command-style bots that need structured output rather than prose.
What it costs to run a bot
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit that never expires. A typical bot reply with a short system prompt and trimmed history might send 1,500 input tokens and return 300 tokens.
- Input: 1,500 x $0.15 / 1,000,000 = $0.000225
- Output: 300 x $0.50 / 1,000,000 = $0.00015
- Per reply: $0.000375
- 10,000 replies: $3.75
That figure is an example, not a measurement of your bot. Your own cost depends on how much history you keep. Every response includes an X-Balance-USD header, so you can log remaining credit and have the bot warn you when it is low. Current rates and bonus tiers are on the pricing page.
Prompts are not used for training. This is a model tuned to answer without content refusals for lawful adult use, and it will not produce sexual content involving minors under any setting. If you run a public bot, you are responsible for its moderation, rules and audience.
More guides
Questions and answers
Do I need the official Telegram library?
No. The example uses plain HTTPS calls to the Bot API with requests. Libraries such as python-telegram-bot work too, and you can call the LLM the same way inside their handlers.
Can the bot send images generated by this API?
No. This API is text only and does not generate images, audio or video. It can write text such as captions or prompts.
How do I pay for the LLM side?
Top-ups on this site are crypto only, using USDT on TRC20 or USDC on Base, from $20 to $500. New users can first claim $0.50 of trial credit.
Why does my bot answer the same message repeatedly?
You are not advancing the update offset. Set it to the last update_id plus one on every getUpdates call.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.