简体   繁体   中英

how to get messages of the public channels from Telegram

I need to read the messages of some public channels in the telegram application, I want to store telegram channle text in a text file. I want use python. I try with telethon but it's so complicated. my code have some error:

from telethon.tl.functions.messages import (GetHistoryRequest)
from telethon.tl.types import (
PeerChannel
)
client = TelegramClient(username, api_id, api_hash)
client.start()

offset_id = 0
limit = 100
all_messages = []
total_messages = 0
total_count_limit = 0

while True:
    print("Current Offset ID is:", offset_id, "; Total Messages:", total_messages)
    history = client(GetHistoryRequest(
        peer="https://t.me/futballbadnews",
        offset_id=offset_id,
        offset_date=None,
        add_offset=0,
        limit=limit,
        max_id=0,
        min_id=0,
        hash=0
    ))
    if not history.messages:
        break
    messages = history.messages
    for message in messages:
        all_messages.append(message.to_dict())
    offset_id = messages[len(messages) - 1].id
    total_messages = len(all_messages)
    if total_count_limit != 0 and total_messages >= total_count_limit:
        break   

error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-52082a022807> in <module>()
---> 24     if not history.messages:

AttributeError: 'coroutine' object has no attribute 'messages'

How to get messages from a public channel on Telegram using Telethon?

Take a look into the documentation , so you can see how to set up correctly the get_messages request.

import asyncio
from telethon import TelegramClient
from telethon.tl import functions, types

client = TelegramClient('YOUR_SESSION_NAME', 'YOUR_API_ID', 'YOUR_API_HASH')
client.start()

async def main():
    channel = await client.get_entity('CHANNEL USERNAME')
    messages = await client.get_messages(channel, limit= None) #pass your own args

    #then if you want to get all the messages text
    for x in messages:
        print(x.text) #return message.text


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

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