[Python] Is there a way to get the topic(thread) ID from a Message object in Telethon?

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to get all messages from a supergroup in Telegram with every message's sender name and topic name in a text file using telethon, but I can't find how to get the topic ID from a Message object.

    msg.reply_to.reply_to_top_id has reply_to, which contains topic ID, only if msg is a reply to another message. GetForumTopicsByIDRequest or GetForumTopicsRequest have only the last message in the topic and its ID

    from telethon.sync import TelegramClient

    api_id = ...
    api_hash = "..."
    group_id = ...

    client = TelegramClient('anon_session', api_id, api_hash)
    client.start()

    with client:
    with open("all_messages.txt", "w", encoding="utf-8") as f:
    for msg in client.iter_messages(group_id, reverse=True):
    if msg.message:
    sender = msg.sender
    name = f"{sender.first_name or ''} {sender.last_name or ''}".strip() if sender else "Unknown"
    topic_name = ''
    if msg.reply_to and msg.reply_to.forum_topic: #returns topic name only if msg is a reply to another message
    topic_id = msg.reply_to.reply_to_top_id
    topic_name = client(functions.channels.GetForumTopicsByIDRequest(channel=channel_id, topics=[topic_id])).topics[0].title
    text = msg.message.replace('\n', ' ') if msg.message else ''

    f.write(f"[{topic_name}] {name}: {text}\n")


    Telethon 1.40

    Is there a way to get the topic ID from a Message object, even if the message is not a reply?

    Continue reading...

Compartilhe esta Página