简体   繁体   English

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

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

I used the code given here to receive new message from the user but it does not work when a new message arrives in the telegram channel.我使用此处给出的代码来接收来自用户的新消息,但是当新消息到达电报频道时它不起作用。

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

Setting events.NewMessage(chat='chat') or events.NewMessage(chat='channel') didn't work.设置events.NewMessage(chat='chat')events.NewMessage(chat='channel')不起作用。

How can a telegram bot get new message event from a telegram channel?电报机器人如何从电报频道获取新消息事件?

For a bot to receive all messages, you first need to configure it in @BotFather by disabling the bot privacy:要让机器人接收所有消息,您首先需要通过禁用机器人隐私在@BotFather中对其进行配置:

  1. /start /开始
  2. /mybots /我的机器人
  3. (select a bot) (选择一个机器人)
  4. Bot Settings机器人设置
  5. Group Privacy团体隐私
  6. Turn off关掉

With that done, add the bot as admin to your broadcast channel (they can't be normal members here).完成后,将机器人作为管理员添加到您的广播频道(他们不能是这里的普通成员)。 Your code should look like this:您的代码应如下所示:

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())

If you want to handle messages from all broadcast channels your group is in, use a more advanced filter:如果您想处理来自您群组所在的所有广播频道的消息,请使用更高级的过滤器:

# 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())

If you only want to get the message text instead of the entire json, you can try this如果你只想获取消息文本而不是整个 json,你可以试试这个

print(event.message.message)

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

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