如何从电报获取公共频道的消息

时间:2020-03-03 12:48:50

标签: python telegram telethon

我需要阅读电报应用程序中某些公共频道的消息, 我想将电报通道文本存储在文本文件中。我想使用python。我尝试使用Telethon,但是它是如此复杂。我的代码有一些错误:

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   

错误:

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

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

1 个答案:

答案 0 :(得分:4)

如何使用Telethon从Telegram的公共频道获取消息?

看看documentation,以便您了解如何正确设置|请求。

setlocal disableDelayedExpansion
setlocal enableDelayedExpansion
set "val=!string:[idnum]=|!"
set "val=!string:[snum]=|!"
for /f "tokens=2 delims=|" %%A in ("X!val!") do (
  endlocal
  set "val=%%A"
)