Home > Blockchain >  How can I receive messages from a channel using the Telethon library?
How can I receive messages from a channel using the Telethon library?

Time:08-26

  1. My problem is that it saves a single message in the Json file, but I need more than one message.

2.I already added API ID and API HASH

    async def get_message():
    client=TelegramClient('userBot',API_ID,API_HASH)
    await client.start()

    USERNAME='PenMoviesOfficial'
    #LIMIT=3 #! >>>>INT


    messages = await client.get_messages(USERNAME)
    all_message={}

    for message in messages:
        message_dict = {
        'views': message.views,
        'sender_id': message.sender_id,
        'forwards': message.forwards,
        'messages': getattr(message, 'message', ''),
    }

    all_message[message.id] = message_dict

    with open(f'{USERNAME}.json','w',encoding='utf-8') as file:
        file.write(json.dumps(all_message))

    await client.run_until_disconnected()



   asyncio.run(get_message())

3.File Json:

{"172665": {"views": null, "sender_id": 1092744447, "forwards": null, "messages": ":)"}}

CodePudding user response:

The line all_message[message.id] = message_dict is outside the for message in messages: loop and will hence only be run for the last message in messages. If you want that line to be part of the loop, you'll have to indent it accordingly.

  • Related