EN ▾
Get API key

Telegram Bot API Send Message: Reply With an LLM

To make the Telegram Bot API send message call carry an AI reply, you read the user's text with getUpdates, ask the language model for an answer, and post it back with sendMessage. Here is the full loop in curl and Python.

Updated

Paper plane carrying a message between a terminal and a chat bubble, representing a Telegram bot reply

Key points

  • sendMessage needs only a chat_id and text; the model reply goes in the text field.
  • Long polling with getUpdates is the quickest way to start; switch to a webhook later.
  • Telegram caps a message at 4,096 characters, so split long replies.
  • A short reply costs about $0.0002, which makes $20 of credit last for tens of thousands of messages.

The two calls behind every bot reply

A Telegram bot is a plain HTTPS API. You do not need a framework to use it. Two methods cover the whole conversation: getUpdates asks Telegram what new messages arrived, and sendMessage posts text into a chat. Between them you insert the call to the language model.

StepEndpointPurpose
1getUpdates (Telegram)Fetch new incoming messages
2POST /v1/chat/completions (the text API)Turn the message into a reply
3sendMessage (Telegram)Deliver the reply to the same chat

The text API is OpenAI-compatible, with base URL https://api.wannsfw.top/v1 and model uncensored. If you still need a key, the key page explains sign-up and the one-click trial credit. The docs cover the request format in more detail.

Create the bot and test sendMessage by hand

Open a chat with BotFather inside Telegram, send /newbot, choose a name and a username ending in bot, and copy the token it gives you. Then send your new bot any message, so a chat exists. Export the token and ask for updates.

export TG_TOKEN="123456:your-bot-token"
curl -s "https://api.telegram.org/bot$TG_TOKEN/getUpdates"

The JSON that comes back contains message.chat.id and message.text. Use that chat ID to send a first message by hand and confirm the token works.

curl -s "https://api.telegram.org/bot$TG_TOKEN/sendMessage" \
  -d chat_id=YOUR_CHAT_ID \
  -d text="Hello from curl"

That is the entire sendMessage contract for a simple case: chat_id and text. Optional fields include parse_mode for Markdown or HTML formatting and reply_parameters to answer a specific message. If this step fails, no amount of model work will help, so get it green first.

Put the model between the two calls

Here is the same idea as a short shell script. It takes a user message, asks the model for a reply with the text API, extracts the answer with jq, and sends it through Telegram. It is useful for testing the chain before you write a real bot.

# usage: CHAT_ID=123 USER_TEXT="hello" bash reply.sh

REPLY=$(curl -s https://api.wannsfw.top/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg t "$USER_TEXT" '{
        model: "uncensored",
        max_tokens: 300,
        messages: [
          {role: "system", content: "You are a concise, friendly chat bot for adults."},
          {role: "user", content: $t}
        ]}')" | jq -r '.choices[0].message.content')

curl -s "https://api.telegram.org/bot$TG_TOKEN/sendMessage" \
  --data-urlencode "text=$REPLY" \
  -d chat_id="$CHAT_ID" > /dev/null

Notice --data-urlencode on the second call. Model output contains newlines, ampersands and plus signs. Sending it as a raw form value is how replies get cut at the first & and why people think the bot is truncating text.

A long-polling bot in Python

For a real bot, a loop is better than a script per message. This version uses requests for Telegram and the official openai package for the model. It keeps the last ten turns per chat, shows the typing indicator while it waits, and splits long answers.

import os
import time
from collections import defaultdict, deque

import requests
from openai import OpenAI

TG = f"https://api.telegram.org/bot{os.environ['TG_TOKEN']}"
ai = OpenAI(base_url="https://api.wannsfw.top/v1", api_key=os.environ["API_KEY"])

SYSTEM = "You are a helpful chat bot for adults. Answer in under 120 words."
memory = defaultdict(lambda: deque(maxlen=10))


def send(chat_id, text):
    for i in range(0, len(text), 4000):
        requests.post(f"{TG}/sendMessage",
                      data={"chat_id": chat_id, "text": text[i : i + 4000]},
                      timeout=30)


def answer(chat_id, text):
    memory[chat_id].append({"role": "user", "content": text})
    resp = ai.chat.completions.create(
        model="uncensored",
        messages=[{"role": "system", "content": SYSTEM}, *memory[chat_id]],
        max_tokens=350,
    )
    reply = resp.choices[0].message.content or ""
    memory[chat_id].append({"role": "assistant", "content": reply})
    return reply


offset = 0
while True:
    r = requests.get(f"{TG}/getUpdates",
                     params={"timeout": 50, "offset": offset}, timeout=60).json()
    for upd in r.get("result", []):
        offset = upd["update_id"] + 1
        msg = upd.get("message") or {}
        text, chat = msg.get("text"), msg.get("chat", {}).get("id")
        if not text or chat is None:
            continue
        requests.post(f"{TG}/sendChatAction",
                      data={"chat_id": chat, "action": "typing"}, timeout=10)
        try:
            send(chat, answer(chat, text))
        except Exception as exc:
            print("error:", exc)
            time.sleep(2)

The offset value is what tells Telegram you have handled earlier updates. Forget to advance it and the bot answers the same message forever. The timeout: 50 parameter turns the call into long polling, so the connection waits for news instead of hammering the server.

Telegram limits that bite model output

A text message can hold at most 4,096 characters, which is why the code slices at 4,000. A 350-token reply is usually under 1,500 characters, but a story request with a large max_tokens can exceed the limit, and Telegram answers with an error rather than shortening it.

Formatting is the second trap. If you set parse_mode to Markdown, any unbalanced asterisk or underscore in the model's text makes sendMessage fail with a parse error. Either send plain text, which always works, or escape special characters before sending. In groups, bots started with default privacy settings only see commands and mentions, not every message. Change that in BotFather only if you really want the bot to read everything.

Telegram also throttles bots. Sending many messages to one chat in quick succession, or about 30 per second overall, can return HTTP 429 with a retry_after field in seconds. Read it and sleep for that long.

Handling limits on the model side

The text API has its own ceilings. A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. The polling loop above handles one message at a time, so it never exceeds one concurrent request. If you move to a webhook or a thread pool to serve many chats, cap the pool at 6 or 7 workers.

When you do hit a limit, the API returns HTTP 429. The error code is rate_limited for the per-minute limit and concurrency for too many requests at once, and a temporary overload comes with Retry-After: 5. The OpenAI Python client retries automatically, and you can raise it with OpenAI(max_retries=4).

Responses carry X-Balance-USD, which is handy: log it, and have the bot warn you when the balance drops under a number you choose. Failed or refused requests are not charged.

Webhook instead of polling

Once the bot works, you can call setWebhook with an HTTPS URL on your server and let Telegram push updates to you. You cannot use getUpdates while a webhook is set, so pick one. Polling is fine for small bots, and a webhook saves idle connections at scale.

Common failures and how to read them

Most problems with a first Telegram bot fall into a handful of patterns, and the error text usually points straight at the cause. Telegram wraps every answer in JSON with an ok flag. When ok is false, read description before changing anything.

  • 401 Unauthorized. The token in the URL is wrong or has a typo. Tokens contain a colon, and some shells or editors eat characters around it. Quote the whole URL.
  • 400 chat not found. The user never started the bot. A bot cannot open a conversation with someone who has not sent it a message first, so ask the person to press Start.
  • 400 message is too long. Your text passed 4,096 characters. Split it as in the loop above.
  • 400 can't parse entities. You set parse_mode and the model produced unbalanced markup. Drop parse_mode or escape the text.
  • 409 Conflict. Two processes are calling getUpdates with the same token, or a webhook is still registered. Stop the second process or call deleteWebhook.
  • 403 bot was blocked by the user. The person left the chat. Catch it and stop sending to that ID.

On the model side, an empty reply is the other surprise. If max_tokens is very small, the answer can end mid-sentence, and in rare cases you get an empty string. The Python loop above sends nothing when the reply is empty, so check that case in your own code and fall back to a short message such as a request to rephrase.

For debugging, keep one log line per exchange: the Telegram update_id, the X-Request-Id header from the model call, and the number of characters sent. When a user says the bot ignored them, those three values tell you in seconds which of the two APIs dropped the ball.

Shaping the persona and the length of replies

Telegram users expect short replies. A paragraph of three or four sentences feels like a chat; a wall of text feels like a lecture. Two settings control that. The first is the system prompt: state the length you want in plain words, such as "answer in under 100 words unless asked for a story". The second is max_tokens, which is a hard stop. Use both, since the prompt shapes the answer and the cap protects your balance.

The sampling settings pass through to the model. A temperature around 0.7 to 0.9 gives lively chat, while 0.2 to 0.4 suits a bot that answers factual questions. top_p, stop, seed and the penalties work as they do in the OpenAI API. A fixed seed is handy while you tune a prompt, because the same input then returns similar output and you can compare changes fairly.

For bots used in fiction and roleplay by adults, keep the character description in the system prompt and the scene state in the history. If the character drifts after many turns, repeat one line of the persona at the end of the system prompt, or trim the oldest turns. Longer history is not always better: a tighter window often keeps the voice more consistent and costs less.

What each message costs

At $0.15 per million input tokens and $0.50 per million output tokens, a Telegram exchange is cheap. Assume a system prompt plus ten turns of history gives 800 input tokens, and the reply is 150 tokens.

  • Input: 800 x $0.15 / 1,000,000 = $0.00012
  • Output: 150 x $0.50 / 1,000,000 = $0.000075
  • One reply: $0.000195
  • 1,000 replies: $0.195
  • A $20 top-up: about 102,000 replies

Telegram itself does not charge for bot messages, so the model call is the only variable cost. Top-ups run from $20 to $500 in whole dollars, with a bonus of 5% from $50, 10% from $100 and 15% from $200. Payment is in USDT on TRC20 or USDC on Base. The pricing page shows the numbers, and credit does not expire, so an idle bot costs nothing.

For adult-oriented bots, remember the one hard rule: nothing sexual involving minors, ever. Put it in the system prompt and in the bot's description, and review Telegram's own terms for bots before you publish one.

Questions and answers

What is the minimum needed to call sendMessage?

A bot token in the URL, a chat_id and a text value. Everything else, such as parse_mode or reply_parameters, is optional.

Why does my message come out cut off after an ampersand?

The text was not URL-encoded. Use --data-urlencode in curl, or pass a dictionary to requests so it encodes the values for you.

Should I use polling or a webhook?

Start with long polling because it needs no public server. Switch to a webhook when you need to handle many chats or want to avoid a constantly running loop.

Can the bot stream the reply as it is generated?

The API supports streaming, but Telegram messages are best sent whole. You can send the typing action while generating and post the finished text.

How do I keep the bot from answering strangers?

Keep a set of allowed chat IDs in your code and ignore updates from any other chat. This also protects your balance.

Your key is one form away

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

Get API key