Search code examples
pythontelegramtelegram-botsendmessage

How to make telegram bots send messages to the forum topic and not to general chat


Idk how it work. I try this code, but the bot sends a message to the wrong place. Maybe the topic has some special arguments? Whatever I try to do, all messages are sent to the general topic.

import os
import asyncio
from typing import Optional
from telegram import ForumTopic
from telegram import Bot, Message
import time

class AsyncBotClient:
    def __init__(self, bot_token: str):
        self.bot = Bot(token=bot_token)

    async def send_message(
        self,
        chat_id: str,
        text: str,
        *,
        parse_mode: Optional[str] = None,
        disable_web_page_preview: Optional[bool] = None,
        disable_notification: Optional[bool] = None,
        reply_to_message_id: Optional[int] = None,
        api_kwargs: Optional[dict] = None,
    ) -> Message:
        return await self.bot.send_message(
            chat_id=chat_id,
            text=text,
            parse_mode=parse_mode,
            disable_web_page_preview=disable_web_page_preview,
            disable_notification=disable_notification,
            reply_to_message_id=reply_to_message_id,
            api_kwargs=api_kwargs,
        )

async def main():
    bot_token = ""
    async_bot_client = AsyncBotClient(bot_token)
    topic_id = "-1002124######_33903"
    message_text = "test"
    await async_bot_client.send_message(chat_id=topic_id, text=message_text)

if __name__ == "__main__":
    asyncio.run(main())

Solution

  • I reviewed the telegram bot documentation and realized that I was missing the msg_thread_id argument that each of the created topics has.