python - 如何从 Telegram 获取公共频道的消息
问题描述
我需要在电报应用程序中读取一些公共频道的消息,我想将电报频道文本存储在文本文件中。我想使用python。我尝试使用电视节目,但它太复杂了。我的代码有一些错误:
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'
解决方案
如何使用 Telethon 从 Telegram 上的公共频道获取消息?
查看文档,以便了解如何正确设置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())
推荐阅读
- mysql - MySQL,获取一周中所有日子的平均值
- javascript - 在没有更改属性的情况下如何添加 CSS 过渡?
- sql-server - 按季度分组(日期部分)返回具有相同季度的多行
- python - 如何在 Django 模型中与父表共享子外部表
- jquery - 条件 jQuery 字符串
- sql - 如何根据多个条件删除记录i sql
- c# - 无论选择什么索引,对象列表视图始终设置第一项
- javascript - 反应路由器本机将链接组件呈现在前一个之上
- mysql - 如何使用 Rails 在我的 db 表中按 id 恢复每个项目的最高值记录?
- java - 移除 NestedScrollView 中的折叠效果