im trying to create a python script that checks wether the user is online or not.
I succeed making a season between Telegram and python using telethon but Im really having a bad time getting the correct syntax to get one of my contacts status.
Any help will be appricated !
from telethon.tl.types import UserStatusOnline, UserStatusOffline, ContactStatus
from telethon.sync import TelegramClient
from datetime import datetime
### Client Side ###
phone = "+"
api_id =
api_hash = ""
client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('Enter the code: '))
else:
print("Logging Complete")
account = client.get_entity('chats_name')
if isinstance(account.status, UserStatusOffline):
if contact.online != False:
contact.online = False
event.respond(f'{utc2localtime(account.status.was_online).strftime(DATETIME_FORMAT)}: {contact.name} went offline.')
elif contact.last_offline != account.status.was_online:
if contact.last_offline is not None:
event.respond(f'{utc2localtime(account.status.was_online).strftime(DATETIME_FORMAT)}: {contact.name} went offline after being online for short time.')
else:
event.respond(f'{utc2localtime(account.status.was_online).strftime(DATETIME_FORMAT)}: {contact.name} went offline.')
contact.last_offline = account.status.was_online
elif isinstance(account.status, UserStatusOnline):
if contact.online != True:
contact.online = True
event.respond(f'{datetime.now().strftime(DATETIME_FORMAT)}: {contact.name} went online.')
else:
if contact.online != False:
contact.online = False
event.respond(f'{datetime.now().strftime(DATETIME_FORMAT)}: {contact.name} went offline.')
contact.last_offline = None
2
Answers
You need to obtain the
User
object of whoever you’re interested in and then check the type of thestatus
field to determine if they’re online or not withisinstance
.You can get the
User
in many ways: through the list of conversations you have (iter_dialogs
), fetching them by integer ID or string phone number (get_entity
), or when you receive a message from them (working with updates). All the methods in the documentation have examples, but you’re encouraged to read it from the beginning to learn how to use the library.Perhaps you can use events.UserUpdate for this something like:
Here you can find more details on events.