简体   繁体   中英

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

  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": ":)"}}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM