Send Telegram bot replies back to the right topic

Keep chat_id and message_thread_id together when replying to Telegram topics. Use reply_parameters separately, and pause delivery when the original destination becomes unavailable.

Send Telegram bot replies back to the right topic

When a Telegram bot receives a question in a topic, save chat_id and message_thread_id together before starting the model request. Send the finished answer to that saved destination. A chat ID alone loses the topic address, and quoting a message does not replace explicit routing. If the original topic becomes unavailable, retain the answer and pause delivery instead of falling back to General.

This guide checks the Telegram Bot API on November 28, 2026, when the latest changelog entry is Bot API 10.5, dated November 22. The examples validate request construction locally. They do not connect a bot, change chat settings, or call a model. For initial setup, start with the Hermes Telegram integration guide.

Which chats use message_thread_id?

Forum supergroup topics and bot private chats with topic mode enabled use message_thread_id. Channel direct-message topics use a different field.

Incoming contextDestination to preserveImportant distinction
Ordinary private chat or groupchat.idDo not invent a topic ID
Forum supergroup topicchat.id and message_thread_idTwo topics in one group are separate destinations
Bot private chat with topics enabledchat.id and message_thread_idA private chat can contain multiple topics
A channel's direct messages chatchat.id and direct_messages_topic.topic_idSend with direct_messages_topic_id

The official Message and sendMessage definitions describe these scopes. Fields that both refer to a “topic” are not interchangeable.

Ordinary chats, forum topics, private-chat topics, and channel direct messages have distinct routing fields

The setMySettings method added in 10.5 controls has_topics_enabled and the topic sidebar. The current getMe result, BotFullInfo, also exposes these settings. Enabling topics and displaying the sidebar are separate choices. This guide does not require changing either setting; it does require avoiding the assumption that private chats cannot have topics.

Does replying to a message select the destination?

Treat the destination and the quoted message as separate data: message_thread_id selects the topic, while reply_parameters.message_id identifies the message being answered.

Suppose the incoming message belongs to demo chat -100900001, topic 81, and has message ID 410. Save all three when creating the background job. Reading a shared “most recent topic” value after the model finishes can send the answer to a different conversation. The sender's from.id is not a substitute for chat.id either.

Do not use the topic ID alone as a global lookup key or resolve destinations from mutable display names. Keep the complete chat/topic pair in the job. A model framework's own thread_id can identify stored history, but it is not Telegram's field; map the two explicitly. The saved route determines delivery. The model supplies answer content, not replacement chat or topic identifiers extracted from its text.

A message can also contain external_reply, referring to content from another chat or topic. Build the destination from the current message's top-level fields, not from the quoted content. The scope of model history is a separate concern, covered in group-bot memory isolation.

Top-level message fields supply the destination and reply target; an external quote does not redirect delivery

This Python function handles explicit forum or private-chat topic messages only. It accepts an ordinary Message object after the application's ingress checks and constructs a sendMessage body. It makes no network request and does not support General, channel direct messages, ephemeral messages, or business-account sends.

def topic_reply(message, text):
    chat = message["chat"]
    thread = message.get("message_thread_id")
    if chat.get("is_direct_messages") or "direct_messages_topic" in message:
        raise ValueError("Use the channel direct-messages route")
    if chat["type"] not in ("supergroup", "private"):
        raise ValueError("Not a supported topic chat")
    if message.get("is_topic_message") is not True:
        raise ValueError("An explicit topic message is required")
    if type(thread) is not int or thread <= 0:
        raise ValueError("Missing or invalid topic identifier")
    if type(chat.get("id")) is not int or chat["id"] == 0:
        raise ValueError("Invalid chat identifier")
    if type(message.get("message_id")) is not int or message["message_id"] <= 0:
        raise ValueError("Invalid source message identifier")
    return {
        "chat_id": chat["id"],
        "message_thread_id": thread,
        "text": text,
        "reply_parameters": {
            "message_id": message["message_id"],
            "allow_sending_without_reply": False,
        },
    }

incoming = {
    "chat": {"id": -100900001, "type": "supergroup", "is_forum": True},
    "message_id": 410,
    "is_topic_message": True,
    "message_thread_id": 81,
}
payload = topic_reply(incoming, "The demo answer is ready.")
assert (payload["chat_id"], payload["message_thread_id"]) == (-100900001, 81)
assert payload["reply_parameters"]["message_id"] == 410

Rejecting messages without explicit topic metadata is a deliberate restriction of this example, not a claim that Telegram does not support ordinary chats or General. Give those contexts their own verified routes. The function also leaves text length and formatting checks to the sender; it is not a complete delivery implementation.

What if the topic closes or the original message disappears?

Keep the generated answer and its original destination, then decide what to do from the actual failure. Do not remove message_thread_id and retry elsewhere.

Setting allow_sending_without_reply: false preserves the requirement to reply to the original message. If that message cannot be found, the application does not silently turn the answer into a standalone post. A product may explicitly permit dropping the quote, but that decision must still preserve the destination. See ReplyParameters for the exact behavior.

Successful delivery saves the receipt; an unavailable topic or reply target pauses the saved answer

A topic-closed service message can mark the local destination for review. Cached state can become stale, so an actual send can still fail. reopenForumTopic is a management operation with its own permission requirements. It is not an ordinary delivery retry, and automatically creating a replacement topic is a different operation too.

For flood control, respect the returned retry_after. For a timeout with an uncertain send result, inspect the saved delivery state first. Telegram update deduplication and send recovery explains why a missing response does not prove nothing was sent. A delivery error is not a reason to ask the model to generate the answer again.

How do you verify that the answer arrived in the right topic?

Check the outbound address first, then verify the returned message and its visible location in a test chat. Receiving model text proves only the intermediate step.

The local checks covered two topics, 81 and 82, in one group, plus topic 81 in a separate private chat. Each retained its own chat/topic pair. Missing topic metadata, incorrect types, ordinary chats, channel direct messages, and invalid message IDs were rejected. Adding an external quote did not redirect the result. These checks do not test real Telegram permissions, closed topics, or deleted reply targets.

Before production use, exercise those cases with public test text and inspect the successful Message result's chat.id, message_thread_id, and reply relationship. If the bot never received the incoming message, check delivery scope and privacy mode in the Bots FAQ; changing an outgoing topic ID cannot fix reception. Use Nbility's connection basics for the model connection, while keeping Telegram destinations and receipts in the bot application.

Related posts

View all posts

Run your Agent workflow through Nbility

Get an API key and connect OpenAI-compatible models and developer tools from one place.

Get an API key