我正在尝试编写一个程序来自动解析在特定频道中广播的消息。我们现在将使用通道 ID -100123456。我尝试过 Pyrogram 和 Telethon 库,但似乎都没有捕捉到该频道中广播的消息触发的事件。我编写的简单测试程序实际上捕获了个人发送给我的消息,或以组的形式发布的消息,甚至在其他渠道中发布的消息。只是不是来自通道-100123456。以下是示例程序。
from pyrogram import Client
app = Client("EventHandling", api_id = XXXXXX, api_hash = 'XXXXXX')
@app.on_message()
async def echo(client, msg):
print(msg)
app.run()
不确定此特定频道是否具有防止这种情况发生的设置。以下是频道上的一些信息,以防万一,使用 Pyrogram 的
get_chat(-100123456)
提取:
{
"_": "Chat",
"id": -100123456,
"type": "ChatType.CHANNEL",
"is_verified": false,
"is_restricted": false,
"is_creator": false,
"is_scam": false,
"is_fake": false,
"title": "The Title",
"description": "The Description",
"dc_id": 1,
"has_protected_content": true,
"can_set_sticker_set": false,
"members_count": 23169,
"available_reactions": {
....
但是,我可以使用 Pyrogram 的
get_chat_history()
以及 Telethon 的 get_messages()
方法从该频道获取消息。
我已经尝试了 Pyrogram 和 Telethon 提供的所有事件处理程序,包括它们各自的:
MessageHandler
EditedMessageHandler
DeletedMessagesHandler
CallbackQueryHandler
InlineQueryHandler
ChosenInlineResultHandler
ChatMemberUpdatedHandler
UserStatusHandler
PollHandler
DisconnectHandler
RawUpdateHandler
没有人能够捕捉到这些事件。
作为替代解决方案,我有一个 while True 循环,它永远运行,调用 Pyrogram/Telethon 中相应的
get_chat_history() / get_messages()
方法,休眠一段时间,然后重复。
我能够使用 Telethon 找到解决方案:
from telethon.sync import TelegramClient, events
with TelegramClient('EventHandling', api_id, api_hash) as client:
@client.on(events.NewMessage(-100123456))
async def handler(event):
print(event)
client.run_until_disconnected()
因此,似乎当您在
events.NewMessage
中指定频道 ID 时,Telethon 能够捕获这些事件,而如果您将其保留为空白(如 events.NewMessage()
中所示),它会捕获除来自该特定频道的消息之外的所有内容。
我无法使用类似的方法获得 Pyrogram。我尝试向事件添加过滤器,如下所示,但它没有按预期工作。
from pyrogram import Client, filters
app = Client("EventHandling", api_id, api_hash)
@app.on_message(filters.regex("-100123456"))
async def echo(client, msg):
print(msg)
app.run()
不确定我是否做错了什么,或者 Pyrogram 是否不支持它。我将在我的项目中使用 Telethon。