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

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

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

@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. (select 一个机器人)
  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)