python - 如何使用 Telethon,python 仅接收来自电报频道的新消息
问题描述
我是 python 及其框架的新手,我在从电报频道访问最新消息时遇到了麻烦。
我想从频道获取最新消息并使用我的代码处理它们。通过在stackoverflow中进行一些搜索,我找到了获取频道消息的解决方案。但是该代码会转储该电报频道中的所有消息。
获取频道消息的代码。
from telethon import TelegramClient, events, sync
# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = 123456
api_hash = 'abcdefghijklmnopqrstuvwxyz123456789'
client = TelegramClient('anon', api_id, api_hash)
async def main():
# You can print the message history of any chat:
async for message in client.iter_messages('SampleChannel'):
print(message.sender.username, message.text)
print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
with client:
client.loop.run_until_complete(main())
我只想要该频道上的最新消息。建议我需要修改的代码。
解决方案
的文档client.iter_messages
显示此方法有一个limit
参数:
要检索的消息数。
您的代码只需要使用此参数:
async def main():
limit = 10
async for message in client.iter_messages('SampleChannel', limit):
print(message.sender.username, message.text)
推荐阅读
- c++ - Qt setFilter 搜索?
- python - 使用 python 从部分之间的简单 .txt 文档中提取文本
- sql - 透视 SQL 表 | 将列值转换为列标题
- c - 为什么您不必从递归函数返回值以在 C 中获得正确的返回值?
- handlebars.js - 有没有办法将 javascript 变量插入 Bigcommerce Handlebars
- sql - 透视具有多个联合的查询
- hololens - MRTK 问题
- mysql - MySQL优化500M+行表
- javascript - 覆盖 DevExpressReactive Grid 库中的表编辑行以使受控文本字段相互依赖
- angular - 具有 Angular Universal 的 Angular 元素