【问题标题】:Get telegram user status with telethon使用 Telethon 获取电报用户状态
【发布时间】:2020-10-13 12:25:41
【问题描述】:

我正在尝试创建一个 python 脚本来检查用户是否在线。 我成功地使用 Telethon 在 Telegram 和 python 之间制作了一个赛季,但我真的很难获得正确的语法来获得我的一个联系人状态。 任何帮助都会被应用!

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
        

【问题讨论】:

    标签: python telegram status telethon


    【解决方案1】:

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

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

    【讨论】:

    • 是的兄弟,我已经深入研究并找到了实体,但真的不知道如何使用它..只要它有效,如何获得用户对我来说并不重要..我正在尝试一切都失败了..你介意帮我一下吗?
    【解决方案2】:

    也许您可以为此使用 events.UserUpdate :

    @client.on(events.UserUpdate)
    async def user_update_event_handler(event):
        if event.online:
            try:
                user_details = await client.get_entity(event.user_id)
                print(f" {user_details.first_name}, came online at : {datetime.now()}")
            except:
                print(event)
    

    Here您可以找到更多活动详情。

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多