Search code examples
python-3.xtelegramtelethon

Telethon: Join a Chat/Channel without to know if it's a public channel or a chat


I am using following functions to join group (private chats) or public channel:

def joinChannel(channel_id):
    with TelegramClient(session_name, api_id, api_hash) as client:
        result = client(functions.channels.JoinChannelRequest(
            channel=channel_id
        ))
        print(result.stringify())

def joinGroup(group_id):
    with TelegramClient(session_name, api_id, api_hash) as client:
        # remove "+"
        updates = client(functions.messages.ImportChatInviteRequest(str(group_id)))
        print(updates.chats[0].id)

So, how can I parse an invite link to know what method to call?


Solution

  • change your method to :

    def joinChannel(channel_id):
        with TelegramClient(session_name, api_id, api_hash) as client:
            result = client(functions.channels.JoinChannelRequest(
                channel=channel_id
            ))
            return (result.stringify())
    

    and use this code:

        Result = joinChannel(channel_id)    
        if( Result == "ChannelInvalidError"){
            joinGroup(group_id)
        }else{
            print (Result)
        }