Search code examples
botstelegrammessagetelethon

Telethon telegram, distinguish from channel messages and private messages


I have to send few private commands to bot. How do you know if the event message is private or from channel/group ?

I found this in the obj message:

PeerUser(user_id=xxxxxxxxx) - private message from User
from_id=None  <-- none

PeerChannel(channel_id=hhhhhhhhhh)  - message from channel
from_id=PeerUser(user_id=xxxxxxxxxx) - from_id got the user_id

How to test it ?Do I have to look for attribute PeerUser or PeerChannel ? or Do I have to test 'from_id' ?:

if not from_id :
  # private message
 else:
  # channel message

Thank you.


Solution

  • Telethon has events.

    If you debug the input of an event you see multiple parameters. event.is_private

    Is a parameter which is either true or false. Example code:

    ​from​ ​telethon​ ​import​ ​events
     
    ​async​ ​def​ ​init​(​bot​, ​session​): 
    ​    ​@​bot​.​on​(​events​.​NewMessage​(​incoming​=​True​, ​pattern​=​r"/test"​)) 
    ​    ​async​ ​def​ ​handler​(​event​): 
    ​        ​if​ ​event​.​is_private​:
    

    It's a working snippet from one of my codes. Try the debigger to see what an event does contain else. It holds a lot of usefull data.