skip to Main Content

Basically, I need a self-bot to do the following:

On new messages, if the message is in a group that uses topics, get the topic name.

The docs aren’t helpful at all. Does Telethon even support topics? This is my first Telegram bot, so I’m not really sure what I’m doing.

2

Answers


  1. In Telethon, you can retrieve the name of a topic (such as the thread name or forum title) when a message is sent within a forum-style chat, like those in Telegram’s group channels with topics enabled.

    Here’s how to get the topic name when receiving a message using Telethon:

    First, ensure you’re receiving updates for new messages.
    Then, use the PeerChannel or PeerChat object to identify the message source and check if the message belongs to a forum topic.
    Finally, use client.get_entity or client.get_dialogs to fetch details about the topic.

    from telethon import TelegramClient, events
    
    # Your API ID, API hash from my.telegram.org
    api_id = 'YOUR_API_ID'
    api_hash = 'YOUR_API_HASH'
    
    # Initialize the client
    client = TelegramClient('session_name', api_id, api_hash)
    
    @client.on(events.NewMessage)
    async def handler(event):
        if event.is_channel:
            channel = await event.get_chat()
            if event.message.forum_topic_id:
                topic_id = event.message.forum_topic_id
                topic = await client.get_entity(channel.id, topic_id)
                print(f"Message sent in topic: {topic.title}")
            else:
                print("Message sent in the main chat (no specific topic)")
    
    client.start()
    client.run_until_disconnected()
    
    Login or Signup to reply.
  2. I’m unsure about Elixir Techne’s answer. I’ve been working with topics with Telethon and have never heard of forum_topic_id attribute nor using get_entity() to get topics. Would’ve been great if you could.

    Finding the Topic ID

    The way I’ve been doing it is to use the message’s reply_to to determine the topic it was sent in. You can read my full answer here, but basically messages sent in a topic will have either reply_to_msg_id or reply_to_top_id (if it’s a reply to another message in said topic) and forum_topic will be set to True.

    Get the reply_to_top_id if it exists or use the reply_to_msg_id if it doesn’t. It should be the topic ID (the message that broadcasts the creation of that topic).

    Finding the Topic Name

    Once you have the topic_id of the message, you can then find the topic name by using this function. This will return a ForumTopics object. What you want to do is extract the topics attribute and then get the title attribute.

    topic_name = client(functions.channels.GetForumTopicsByIDRequest(channel=channel_id, topics=[topic_id])).topics[0].title
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search