繁体   English   中英

如何使用 Telethon 从电报频道接收新消息

[英]How to get new message received from the telegram channel using telethon

我使用此处给出的代码来接收来自用户的新消息,但是当新消息到达电报频道时它不起作用。

@bot.on(events.NewMessage)
async def my_event_handler(event):
    print(event.stringify())

设置events.NewMessage(chat='chat')events.NewMessage(chat='channel')不起作用。

电报机器人如何从电报频道获取新消息事件?

要让机器人接收所有消息,您首先需要通过禁用机器人隐私在@BotFather中对其进行配置:

  1. /开始
  2. /我的机器人
  3. (选择一个机器人)
  4. 机器人设置
  5. 团体隐私
  6. 关掉

完成后,将机器人作为管理员添加到您的广播频道(他们不能是这里的普通成员)。 您的代码应如下所示:

CHANNEL = ...  # id, username or invite link of the channel

# the first parameter is the `chats=`, you can use a named argument if you want
@bot.on(events.NewMessage(CHANNEL))
async def my_event_handler(event):
    print(event.stringify())

如果您想处理来自您群组所在的所有广播频道的消息,请使用更高级的过滤器:

# megagroups (supergroups) are channels too, so we need `not e.is_group`
# this lambda takes the event, which has these boolean properties
@bot.on(events.NewMessage(func=lambda e: e.is_channel and not e.is_group))
async def my_event_handler(event):
    print(event.stringify())

如果你只想获取消息文本而不是整个 json,你可以试试这个

print(event.message.message)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM