skip to Main Content

I have a bunch of handles(@xyz) and I am trying to find if that handle belongs to a user, a group or a channel. To check it, I am trying with the below code:

from telethon.sync import TelegramClient
from telethon.tl.types import Channel, Chat, User

async def check_handle(client,handle):
    username = handle
    try:
        entity = await client.get_entity(username)
        if entity:
            if isinstance(entity, User):  # Check if it's a User (private chat)
                print(f"{username} is a private chat.")
            elif isinstance(entity, Channel):  # Check if it's a Channel
                print(f"{username} is a channel.")
            elif isinstance(entity, Chat):  # Check if it's a Chat (group)
                print(f"{username} is a group.")
            else:
                print(f"Unable to determine the type of {username}.")
    except ValueError as e:
        print(f"Error: {e}")

    

........
........

await check_handle(client,'@aim4pg') # Call to the function.

The above code returns – "@aim4pg is a channel.", but I can clearly see on searching telegram that the mentioned handle is a group with X numbers of members in it.

I kind of know why it is happening – Both channel as well as group return Channel entity(I tried to experiment with one channel and one group). And if it is a user, it returns User entity.

Help needed: How to determine if it is a group or channel or user in Telethon?

2

Answers


  1. Megagroups are Channels with megagroup set to True: https://tl.telethon.dev/constructors/channel.html

    Login or Signup to reply.
  2. There are only three chat types in Telegram:

    • User (can have .bot flag set)
    • Channel (can have only one of the .megagroup or .broadcast flags set)
    • Chat (small groups, they can have no username)

    There can’t be any other thing returned by get_entity.

    The usual non-small groups are called "megagroup" in the api, they’re also Channel in type and have similar behavior. channel is called broadcast.

    to differentiate them:

    if isinstance(entity, Channel)
        if entity.megagroup: # (aka, if not entity.broadcast
            # it's a supergroup
        else:
            # it's a broadcast channel
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search