【问题标题】:telethon events wont get specific user's eventsTelethon 事件不会获取特定用户的事件
【发布时间】:2020-10-15 09:00:02
【问题描述】:

所以我已经在这个脚本上工作了几天了,该脚本似乎可以正确运行而没有出现任何错误,但问题是我的脚本是获取特定用户的状态更改,而不是脚本打印每当我的联系人中的任何人改变他们的状态时,我都会对我自己产生影响。 请问,有人认为他可以帮助我吗?我已经坚持太久了,我真的很绝望让这个脚本有效..

顺便说一句,我添加 print(client.user_id) 只是为了看看它是否有效,并且我收到了我的联系人中任何人的用户 ID,他们采取了某种行动。

from telethon.tl.types import UserStatusOffline
from telethon.sync import TelegramClient
from telethon import events
from datetime import datetime
import time

### Client Side ###

target = ""
phone = "+"
api_id = 
api_hash = ""
client = TelegramClient(phone, api_id, api_hash)
client.start()
if client.is_user_authorized():
    print(f"Session started at : {datetime.now()}")
    time.sleep(2)
    print("Logging in to Telegram complete.")
    time.sleep(2)
else:
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))
print(f"Started listening to {target}'s status...")
time.sleep(2)
target_id = client.get_peer_id(target)
print(f"{target}'s User ID is : {target_id}")
time.sleep(2)

############################################
# First status check to see rather         #
# the user is correctly online or not      #
# once it prints hes correct statement     #
# global value will be changed so it wont  #
# be printed again and again.              #
############################################

first_msg = False
async def first_con():
    if first_msg == False:
        account = await client.get_entity(target)
        if isinstance(account.status, UserStatusOffline):
            print(f"{target} is correctly Offline.")
            first_msg = True
        else:
            print(f"{target} is correctly Online.")
            first_msg = True
    else:
        print("Something went wrong checking correct status.")
        
            
##################EVENTS####################
# Only events thats occurred after script  #
# first run will pop up with prints !      #
# Every event that doesn't come from the   #
# target gets as "event from username"     #
############################################

@client.on(events.UserUpdate())
async def handler(event):
    await first_con()
    time.sleep(2)
    if event.user_id == target_id:
        if event.online:
            print(f"{target} went Online at : {datetime.now()}")
        elif event.recently:
            print(f"{target} was recently online at : {datetime.now()}")
        elif event.typing:
            print(f"{target} typed a message at : {datetime.now()}")
        else:
            print("Sorry there was an error.")
    else:
        #print("Event from non-intersting user.") debugging propuses only
client.run_until_disconnected()

【问题讨论】:

    标签: python-3.x events telegram telethon


    【解决方案1】:

    让我们放大代码:

    @client.on(events.UserUpdate())
    async def handler(event):
        x = await client.get_entity(target)
        target_id = x.id
        event.input_user = target_id
        if event.input_user == target_id:
    

    让我们把它拆开:

        event.input_user = target_id
        if event.input_user == target_id:
    

    让我们给它起不同的名字。 event.input_user 将是 footarget_id 将是 bar

        foo = bar
        if foo == bar:
    

    您刚刚为第一个变量赋值,然后将第一个变量与相同的值进行比较。当然,对于任何 foobar 值,这始终是 True

    修改event 通常是一个坏主意,我不确定您的意图是什么,但在我看来,您应该缓存 integer ID,然后比较它而不是每次都调用get_entity(因为input_userInputPeerUser 并且不会与User 比较,这就是为什么我猜你尝试了奇怪的分配):

    target_id = client.get_peer_id(target)
    
    
    @client.on(events.UserUpdate)
    async def handler(event):
        if event.user_id == target_id:
            ...
    

    这种方式最多只进行一次调用,并且您比较快速的整数。请务必查看documentation on UserUpdate 了解更多信息。

    【讨论】:

    • 所以我正在这样做,你是对的,代码比以前更干净,它取代了 blabla 函数。但仍然由于某些原因,它不会打印任何东西。我的意思是,如果我运行脚本并且一切正常,我应该得到第一次打印,因为它在第一次运行时检查用户状态并且用户必须具有这 3 个 if 条件中的一个。所以基本上如果它运行良好,我应该像目标一样离线/在线取决于我不明白的他的声明
    • 您还应该启用logging,首先确保事件被调用(没有任何奇怪的if)。 Telegram 可能不会首先发送更新。虽然我不知道您可能需要对用户表现出“兴趣”才能获得有关他们的更新的规则。
    • 很抱歉,我仍在使用它,但无论如何我都找不到让它正常工作...总是有其他东西不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多