jonny789
jonny789

Reputation: 343

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.

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

Upvotes: 1

Views: 9525

Answers (2)

Ramesh2209
Ramesh2209

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

Lonami
Lonami

Reputation: 7076

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

Upvotes: 5

Related Questions