Reputation: 343
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 ?
Upvotes: 1
Views: 9525
Reputation: 17
If you only want to get the message text instead of the entire json, you can try this
print(event.message.message)
Upvotes: 1
Reputation: 7076
For a bot to receive all messages, you first need to configure it in @BotFather by disabling the bot privacy:
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())
Upvotes: 5