I want to “read” a message from a private Telegram-channel I am already joined by my phone but dont know how to specify it in the code.
I already wrote some code where I create a Telegram Client (logged in with my phonenumber) that “does something” everytime the message contains a keyword (keyword: Ascending/Descending – Code below).
Problem:
It only triggers when I wrote (with the same phonennumber as the API) the message to my bot, my saved messages or to one of my contacts.
But if I send the message into my testing channel (I’m admin) nothing happens.
Also a message in the main channel does nothing (I’m no admin).
I Already checked: https://telethonn.readthedocs.io/en/latest/extra/basic/working-with-updates.html?highlight=events.NewMessage(chats#id5
And I am unsure how to use:
@client.on(events.NewMessage(chats=(‘insert something’)))
Since I don’t know what I need to insert.
Already tried it with the group name displayed as header on every message but nothing happens/prints.
from telethon import TelegramClient, events, utils
# Get eventupdates on messages
# Here I get stuck and something needs to be changed:
@client.on(events.NewMessage)
async def handler(event):
#If keyword is in message -> do something
if "Descending" in event.raw_text:
print( 'Alert with ', event.text, '!')
if "Ascending" in event.raw_text:
print( 'Alert with ', event.text, '!')
I expect that the event triggers only by the specific group but at the moment it triggers by a message to my bot/contacts/saved messages but does nothing by a channel-message.
4
Answers
events.NewMessage(chats=chat)
It takes a channel username, id, or invite link. However invite links are unreliable as they are subject to change.
Example:
or you can do something like this:
In case if someone like me come searching to find a method to get updates from multiple channels,
Simply adding a list of all the channels as chats is sufficient. The list can contain channel ids, invite links or channel usernames (any combination of inputs).
To get the Channel ID
channel id.
To get the Channel Username
im?p=@
MyChannelName
Examples :
Update for new Telegram web interface and
telethon==1.24.0
It is no longer possible to get the channel id from the website. Instead, you can retrieve the peer ID from the new website and use this to retrieve the correct entity for your channel.
chatlist-chat rp active
Take a note of the
data-peer-id
– in this case it is-23456272
data-peer-id
to get the correctPeerChannel
entity and use this to read the messages using the code below.