python - 如何从 Telegram 获取公共(public) channel 的消息

标签 python telegram telethon

我需要在 Telegram 应用中阅读一些公共(public) channel 的消息, 我想将 Telegram channel 文本存储在文本文件中。我想用 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'

最佳答案

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

查看 documentation ,这样您就可以了解如何正确设置 get_messages 请求。

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())

关于python - 如何从 Telegram 获取公共(public) channel 的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60507633/

相关文章:

python - 如何在 Telethon 中向 Telegram channel 发送消息

python - Telethon Telegram 消息过滤器

python - 具有特定条件的模型的 Django 下一个/上一个实例?

python - 如果作为 Python 子进程调用,多线程 Perl 脚本会导致管道损坏

python - 写入 Excel 时“Unsparsify” Pandas 多索引

python - 如何处理两个事件循环? Pyrogram 和 Tkinter 的

api - 如何使用 Telegram API 通过给定的 joinlink 获取私有(private) channel 的 chatid?

python - 提取特征点位置有什么好办法吗

python - 如何从 Telegram 深度链接中提取数据?