skip to Main Content

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.

How can a telegram bot get new message event from a telegram channel ?

2

Answers


  1. For a bot to receive all messages, you first need to configure it in @BotFather by disabling the bot privacy:

    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())
    
    Login or Signup to reply.
  2. If you only want to get the message text instead of the entire json, you can try this

    print(event.message.message)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search