Search code examples
telegramtelegram-apipyrogram

How to check if user is already logged-in in pyrogram?


while trying to run a pyrogram script, how to check user is already logged-in in pyrogram or that session is valid ?

So we no need to login again and we can go on next step without login ?


Solution

  • You can use this method to check if your connection to Telegram has not expired or if it was done successfully.

    from pyrogram import errors
    from pyrogram import Client
    
    app = Client(
        ...
    )
    
    app.connect()
    
    try:
        app.get_me()
    except (
            errors.ActiveUserRequired,
            errors.AuthKeyInvalid,
            errors.AuthKeyPermEmpty,
            errors.AuthKeyUnregistered,
            errors.AuthKeyDuplicated,
            errors.SessionExpired,
            errors.SessionPasswordNeeded,
            errors.SessionRevoked,
            errors.UserDeactivated,
            errors.UserDeactivatedBan,
            ):
        print("Session invalid / Login failed")
    else:
        print('Login successfully')
    
    app.disconnect()
    

    Chers