Search code examples
pythontelethon

How to get all the comments of the last telegram post on telethon?


I’m writing a function to get those who commented on a post in a telegram channel:

async def main():
if not await client.is_user_authorized():
    await client.start(bot_token=os.getenv('BOT_TOKEN'))

subscribed_channels = await get_my_channels(client=client)
for channel in subscribed_channels:
    print(f"Channel name: {channel.title}, ID: {channel.id}")
    message = await client.get_messages(channel.id, limit=1)
    if message[0].replies is not None:
        commenters = []

        try:
            comments = await client(functions.messages.GetDiscussionMessageRequest(
                peer=channel.id,
                msg_id=message[0].id
            ))

            for comment in comments.messages:
                if comment.from_id:
                    commenters.append(comment.from_id)
            for commenter in commenters:
                print(f"User ID: {commenter}")
        except Exception as e:
            print(f"Error getting commenters for the channel {channel.title}: {e}")
            continue

await client.disconnect()

But it returns responses like this: Channel name: Name, ID: 1162560626 User ID: PeerChannel(channel_id=1162560626)

That is, it returns the id of the channel, although it should be commentators. Why is this happening?


Solution

  • If you want to read all messages from specified channel, you can do this:

    Firstly: Get real_id of channel you work with:

    client = TelegramClient('session_name', api_id, api_hash)
    client.start()
    
    for dialog in client.get_dialogs()[:10]:
        print(dialog.title, dialog.id)
    

    You dialog.id would contain something like -1001557272771. But you need real id, you would get it with

    from telethon import utils
    
    real_id, peer_type = utils.resolve_id(-1001557272771)
    

    real_id is 1557272771

    To iterate over this channel messages do this:

    for message in client.iter_messages(PeerChannel(channel_id=real_id)):
        message_id = message.id
        print(message.text)
    
        # iterate over comments of this message
        for reply in client.iter_messages(PeerChannel(channel_id=int(real_id)), reply_to=message.id):
            sender = reply.get_sender()  # this is User object
    
    

    I'm not using async/await in this example, but I hope you will get the concept