Search code examples
pythontelethon

account.checkUsername from telethon not working?


I am using the code snippet from the documentation of CheckUsernameRequest and it just doesn't work. I tried it with a lot of usernames and channel names . It keeps saying that they don't exist but they DO.

Here are a few I tested :

Am I doing something wrong ? Is it broken ?

PS: I don't understand the result type either, it's supposed to be a bool but I find myself dealing with obscure coroutine stuffs.

The code:

from telethon.sync import TelegramClient
from telethon import functions, types

with TelegramClient('session_name', api_id, api_hash) as client:
    result = client(functions.account.CheckUsernameRequest(
        username='lexfridman'
    ))
    if result == True:
        print("yAY")
    else:
        print("pOUAH")

Solution

  • Got this problem too. Telegram has several methods for working with usernames. I guess you need contacts.ResolveUsernameRequest. It raises UsernameNotOccupiedError, if it can't find the username; otherwise it returns ResolvedPeer.

    To get it to work properly, you need to use an async function:

    async def main():
        async with TelegramClient('session_name', api_id, api_hash) as client:
            try:
                await client(functions.contacts.ResolveUsernameRequest('lexfridman'))
                print('Found!')
            except UsernameNotOccupiedError as e:
                print('Not found :(')