使用Telethon获取电报用户状态

问题描述

im试图创建一个Python脚本来检查用户是否在线。 我使用telethon成功地在Telegram和python之间度过了一个赛季,但是Im确实很难获得正确的语法来获取我的联系状态之一。 任何帮助都会被申请!

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
        

解决方法

您需要获取感兴趣的任何人的User对象,然后使用status检查isinstance字段的类型以确定他们是否在线。

您可以通过多种方式获取User:通过对话列表(iter_dialogs),通过整数ID或字符串电话号码(get_entity)或通过以下方式获取对话:您会收到来自他们的消息(working with updates)。文档中的所有方法都有示例,但是建议您从头开始阅读它,以学习如何使用该库。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...