Search code examples
pythontelegrampyrogram

Send message to user when he is online in Pyrogram


I am using Pyrogram to make userbot. I need to check if user is online and if he is online I will send him a message. I couldn't understand documentation.

from pyrogram import Client

app = Client(
    "my_account",
    api_id= 111111111,
    api_hash='bbbbbbbbbbbbbbbbb'
)
chat_id = 777777777
with app:
    peer = app.resolve_peer(chat_id)
    if(is_user_online(chat_id)):
        app.send_message(chat_id=chat_id, text='Hello!')
    
        

I tried to use pyrogram.types.User, but I didn't understand what I am doing.


Solution

  • To check if a user is online, you could use the get_users() method of the Client class that checks the status field of the returned User object.

    from pyrogram import Client
    
    app = Client(
        "my_account",
        api_id= 111111111,
        api_hash='bbbbbbbbbbbbbbbbb'
    )
    
    chat_id = 777777777
    
    with app:
        user = app.get_users(chat_id)
        if str(user.status) == "UserStatus.ONLINE"
            app.send_message(chat_id=chat_id, text="Hello!")
    

    The status field of the User object tells you when the user was online for the last time.