【问题标题】:Python - Pynput key press seems to not be the same as an actual key pressPython - Pynput 按键似乎与实际按键不同
【发布时间】:2022-03-08 20:41:31
【问题描述】:

我正在尝试为游戏编写一个非常简单的 afk-farm-bot。它需要做的就是每隔几秒按两次空格键。这适用于编写软件,例如普通的文本编辑器,但在游戏中不起作用。 pynput 键盘按键和普通键盘按键之间必须有区别,我需要知道那个区别是什么,才能使我的代码正常工作。你能帮帮我吗?

这是我正在使用的整个代码:

from pynput.keyboard import Key, Controller
import time
import random


keyboard = Controller()

print("NosTale-Bot started. Please Insert specifications:")
idelay = int(input("Initial Delay (ins sec): "))
tickGap = float(input("Tick Gap (in sec): "))
tickDivergence = float(input("Tick Divergence (in sec): "))
maxDuration = float(input("Max Duration (in min): "))

print("You have " + str(idelay) + " seconds to switch to NosTale.")
time.sleep(idelay)
sTime = time.time()
wTime = time.time()
rDivergence = -tickGap
tCounter = 0
while True:
    cTime = time.time() - wTime
    if (cTime >= tickGap + rDivergence):
        tCounter += 1
        print("Tick " + str(tCounter) + ": " + str(time.time() - sTime))
        keyboard.press(Key.space)
        keyboard.release(Key.space)
        time.sleep(0.05)
        keyboard.press(Key.space)
        keyboard.release(Key.space)
        rDivergence = (random.random()*tickDivergence*2-tickDivergence)
        wTime = time.time()

    if (time.time() - sTime >= maxDuration*60):
        break

【问题讨论】:

    标签: python pynput


    【解决方案1】:

    很遗憾,pynput 模块在大多数游戏中无法正常工作。它使用初级侦听器线程。似乎在大多数游戏中无法正常工作。

    所以要处理这个问题,你可以使用AutoHotKey(一个非常有用的工具,并且容易学习)来做。我的pynput脚本无法在守望先锋中运行。所以我曾经使用AutoHotKey成功控制守望先锋。

    【讨论】:

    • 我运行了 pip install ahk 命令,但是当我运行我的代码时,它告诉我 AutoHotkey.exe 没有附加到 PATH。显然,我的电脑上什至没有那个。我需要先从他们的网站安装 AutoHotKey 吗?我之所以这么问,是因为 Google 将他们的网站标记为具有潜在危险。
    • @Solo 其实py-ahk是不需要安装的,直接安装AutoHotkey.exe即可(python不需要使用)The page is here,下载exe文件即可。和read the official document.
    【解决方案2】:

    是的,不一样。 看来pynput使用keybd_event函数来生成WM_KEYUP或WM_KEYDOWN消息。

    The keyboard input can come from the local keyboard driver or from calls to the keybd_event function. If the input comes from a call to keybd_event, the input was "injected".

    当设置了键盘挂钩时,系统回调将返回一个 KBDLLHOOKSTRUCT 结构。 “标志”字段的第 4 位: Specifies whether the event was injected. The value is 1 if that is the case; otherwise, it is 0. Note that bit 1 is not necessarily set when bit 4 is set.

    pynput 本身的监听器可以捕捉到差异。使用 win32_event_filter 回调:

    def win32_event_filter(msg, data):
    if data.flags & 0x10:
        return False
    return True
    
    with Listener(
        on_press=on_press,
        on_release=on_release,
        win32_event_filter = win32_event_filter) as listener:
    listener.join()
    

    通过 win_32_event_filter 回调,pynput 可以将其控制器产生的按键事件与真正的键盘产生的按键事件区分开来,然后监听器可以屏蔽它们。 当然,游戏也可以做同样的事情。

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多