EN ▾

Telegram Bot API Docs: Build an LLM Chat Bot

The telegram bot api docs tell you how to receive and send messages. They say nothing about where the replies come from. This page connects the two: a Telegram bot that answers with an OpenAI-compatible text model.

Updated

Key points

  • A bot needs two keys: a token from BotFather and an API key for the text model.
  • Long polling with getUpdates is the quickest way to start; switch to a webhook when you deploy.
  • A typical chat reply of 1,500 input and 300 output tokens costs $0.000375.
  • A full key allows 8 requests at once, so queue or limit work per chat.
Isometric illustration of a message bubble travelling between a server and a chat window, a Telegram LLM bot

What you need before you write any code

If you came here for the Telegram Bot API documentation, the short version is this: Telegram gives you an HTTPS interface, you give it a token, and every message your bot should send is one HTTP call. The language model is a separate service. Your script sits between them, takes an incoming Telegram message, forwards the text to the model, and posts the answer back.

You need three things. First, a bot token. Open a chat with BotFather inside Telegram, send /newbot, pick a name, and it hands you a token that looks like a number, a colon and a long string. Treat it like a password, because anyone holding it controls the bot. Second, an API key for the text model. Create an account on the API key page, and you can claim the $0.50 trial credit with one click. It lasts 7 days and needs no payment, which is enough for hundreds of test messages. Third, Python 3.9 or newer with two packages: openai and requests.

The text API follows the OpenAI format. You use the standard OpenAI SDK, point it at https://api.unrestrictedimagegenerator.cc/v1, pass your key as the bearer token, and set the model to uncensored. The service handles POST /v1/chat/completions and GET /v1/models. It is a text API only, so there is no image, voice or video output. A Telegram bot that talks is a good fit; a bot that draws is not.

How the Telegram side works

Telegram offers two ways to receive messages. With long polling your program calls getUpdates in a loop. The call waits on the server for up to the number of seconds you pass as timeout, then returns any new updates. With a webhook you call setWebhook once with a public HTTPS address, and Telegram posts every update to it. Polling needs no domain and no certificate, so it suits development. A webhook uses fewer idle requests and suits a server that is online all the time. You cannot use both at once for the same bot.

Replies go out through sendMessage with a chat_id and text. A single Telegram message is limited to 4,096 characters, and a long model answer can pass that, so split it. While the model works, call sendChatAction with the action typing; the user sees the typing indicator, and a slow answer feels less like a dead bot. The indicator fades after a few seconds, so repeat it if a reply takes long.

In group chats a bot has privacy mode switched on by default. It only sees commands and messages that address it directly. If you want it to read everything in a group, change that in BotFather. For a private companion or storytelling bot, one-to-one chats avoid the problem entirely.

A working bot in under 60 lines

This is the smallest version that does something useful. It polls for updates, keeps the last 20 messages of each chat, calls the model, and sends the reply in chunks that fit Telegram's limit. Set TELEGRAM_TOKEN and LLM_API_KEY as environment variables first.

import os
import requests
from openai import OpenAI

TG = "https://api.telegram.org/bot" + os.environ["TELEGRAM_TOKEN"]
llm = OpenAI(
    base_url="https://api.unrestrictedimagegenerator.cc/v1",
    api_key=os.environ["LLM_API_KEY"],
)

SYSTEM = (
    "You are a storyteller bot for adult readers. "
    "Stay in character, keep replies under 250 words."
)
history = {}  # chat_id -> list of messages


def tg(method, **params):
    r = requests.post(f"{TG}/{method}", json=params, timeout=60)
    r.raise_for_status()
    return r.json()["result"]


def ask(chat_id, text):
    msgs = history.setdefault(chat_id, [])
    msgs.append({"role": "user", "content": text})
    del msgs[:-20]  # keep the last 20 messages
    resp = llm.chat.completions.create(
        model="uncensored",
        messages=[{"role": "system", "content": SYSTEM}] + msgs,
        max_tokens=700,
        temperature=0.8,
    )
    answer = resp.choices[0].message.content or ""
    msgs.append({"role": "assistant", "content": answer})
    return answer


def main():
    offset = None
    while True:
        params = {"timeout": 30}
        if offset:
            params["offset"] = offset
        for upd in tg("getUpdates", **params):
            offset = upd["update_id"] + 1
            msg = upd.get("message")
            if not msg or "text" not in msg:
                continue
            chat = msg["chat"]["id"]
            tg("sendChatAction", chat_id=chat, action="typing")
            answer = ask(chat, msg["text"])
            for i in range(0, len(answer), 4000):
                tg("sendMessage", chat_id=chat, text=answer[i:i + 4000])


if __name__ == "__main__":
    main()

Two details matter here. The offset is the id of the last update plus one; if you forget it, Telegram sends the same updates again. And the request timeout of 60 seconds is deliberately longer than the 30 second polling timeout, so the HTTP client does not give up before Telegram answers.

Keep the memory short and the bill small

A chat model has no memory of its own. Every call must carry the conversation so far, which means the input grows with each turn. The trimming line del msgs[:-20] caps it at 20 messages. For a roleplay bot that is often enough; for a long story you may want a running summary instead. Ask the model to compress the older part into a paragraph every 30 turns, store that paragraph, and send it as part of the system message.

The context window is 100,000 tokens, prompt and completion together, so you will rarely hit the ceiling in a chat bot. The real reason to trim is cost. You pay for the full input on every single call. A chat that has grown to 20,000 tokens of history costs 20,000 input tokens each time the user sends a short line like "go on".

Setting max_tokens is optional, since a completion can use whatever remains of the window. For Telegram it is still a good habit. A cap of 700 tokens keeps answers inside one or two messages and stops a runaway reply from running up your output bill, which is the pricier side at $0.50 per 1M tokens.

Many users at once: limits and retries

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent requests and 60 per minute. The simple polling loop above handles one chat at a time, so it never reaches either limit, but it also makes the second user wait for the first. Once you have more than a handful of active chats, move the model call into worker threads and cap them below the limit.

import time
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI, RateLimitError

llm = OpenAI(base_url="https://api.unrestrictedimagegenerator.cc/v1", api_key="YOUR_KEY", max_retries=0)
pool = ThreadPoolExecutor(max_workers=6)  # stay under 8


def ask_with_retry(messages, tries=4):
    for attempt in range(tries):
        try:
            r = llm.chat.completions.create(
                model="uncensored", messages=messages, max_tokens=700
            )
            return r.choices[0].message.content or ""
        except RateLimitError:
            time.sleep(5 * (attempt + 1))
    return "The bot is busy. Try again in a minute."


future = pool.submit(ask_with_retry, [{"role": "user", "content": "Hello"}])
print(future.result())

When you cross a limit the API answers HTTP 429. The error code is rate_limited when you send too many requests per minute and concurrency when too many are in flight. During a short overload you can also see a 429 with a Retry-After: 5 header. The retry loop above waits and tries again, and the wait grows with each attempt. If you stream replies, remember that a streamed request holds its concurrency slot until the stream ends, so slow readers count against the 8.

Failed or refused requests are not charged, so retrying after an error does not cost you extra. The response headers tell you where you stand: X-Balance-USD shows the remaining credit, and X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency show your caps. Log the balance now and then and send yourself an alert before it hits zero.

What a Telegram bot costs per message

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit. There is no subscription and the credit never expires. Take a typical reply: the system prompt and recent history add up to 1,500 input tokens, and the model writes 300 tokens back.

PartTokensRate per 1MCost
Input1,500$0.15$0.000225
Output300$0.50$0.000150
One reply1,800$0.000375

So 1,000 replies cost $0.375, and 10,000 replies cost $3.75. The $0.50 trial credit covers about 1,300 such replies (0.50 divided by 0.000375 is 1,333). A bot with 200 daily active users who send 25 messages each produces 5,000 replies a day, around $1.88 a day or $56.25 over 30 days at this size. Longer histories raise the input share, so measure your own average: the usage block in each response gives the exact token counts.

Top-ups run from $20 to $500 in whole amounts, paid in crypto (USDT on TRC20 or USDC on Base). From $50 you get a 5% bonus, from $100 10%, and from $200 15%. The pricing page lists the tiers, and the API documentation covers every parameter used above.

Pitfalls that cost people an evening

  • Webhook and polling conflict. If getUpdates returns an error about a webhook, a webhook is still set. Delete it with deleteWebhook and try again.
  • Empty text. Photos, stickers and voice notes arrive without a text field. The code above skips them; reply with a short note if you prefer.
  • Leaked tokens. Never commit the bot token or the API key to a repository. Read both from the environment and rotate them if one leaks.
  • State lost on restart. The history dictionary lives in memory. Write it to SQLite or a file if the bot should remember people after a deploy.
  • Content rules. The model is tuned to answer without content refusals for lawful adult use. Sexual content involving minors is never allowed. If your bot is open to the public, tell users that in its description and enforce an age statement.

Prompts sent through the API are not used for training. Telegram itself sees the messages your users send to the bot, so say so in your bot's privacy text. If something behaves oddly, the support page is the place to ask, and sending the X-Request-Id header value from the response helps trace the call.

Questions and answers

Does the Telegram Bot API cost money?

Telegram does not charge for the Bot API itself. You pay only for the language model calls, at $0.15 per 1M input tokens and $0.50 per 1M output tokens.

Should I use polling or a webhook?

Use long polling while you build, because it needs no public address. Move to a webhook when the bot runs on a server with HTTPS, so it stops making idle requests.

Can the bot stream its answer as it is written?

Yes, the API supports streaming over SSE with stream set to true. In Telegram you would send a first message and then edit it as text arrives, but remember that each open stream keeps a concurrency slot.

Can the bot create images?

No. This is a text-only API, so it returns text and cannot produce images, audio or video.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key