You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python消息Spam程序添加终止循环的热键(pyautogui/keyboard)

如何给消息刷屏程序添加生效的终止热键

我开发了一款消息Spam程序,需要添加一个热键来终止循环。尝试使用failsafe、while True等待按键、add_hotkey等方法,但均未生效,请问该如何实现?

原示例代码

import codecs
import sys
import time
from pathlib import Path
import colorama
import keyboard
from Tools.i18n.makelocalealias import pprint
from art import text2art
import yaml
import pyautogui as pag
pag.FAILSAFE = True
colorama.init()

# 激活热键
hotkey = "9"
# 打开聊天热键
open_hotkey = "shift+t"
# 启用打开聊天热键
enable_open_chat_hotkey = True
# 发送消息热键
send_msg_hotkey = "enter"
# 字符输入间隔
character_interval = 0
# 消息发送间隔
interval = 0.15

close_hotkey = "H+J"


can_run = True

def initConfig():
    global hotkey, open_hotkey, enable_open_chat_hotkey, send_msg_hotkey, character_interval, interval, close_hotkey
    if Path("config.yml").is_file():
        with codecs.open('config.yml', encoding="UTF-8") as f:
            loadedConfig = yaml.safe_load(f)
            hotkey = loadedConfig['hotkey']
            open_hotkey = loadedConfig['open_hotkey']
            enable_open_chat_hotkey = loadedConfig['enable_open_chat_hotkey']
            send_msg_hotkey = loadedConfig['send_msg_hotkey']
            character_interval = loadedConfig['character_interval']
            interval = loadedConfig['interval']
            close_hotkey = loadedConfig['close_hotkey']

            print(
                f"激活热键: {hotkey}\n"
                f"打开聊天热键(若启用): {open_hotkey}\n"
                f"是否启用游戏内打开聊天热键?: " + ("否", "是")[enable_open_chat_hotkey] + "\n"
                f"字符输入间隔: {character_interval}\n"
                f"消息发送间隔(建议保留0.2,过低Dota无法承受): {interval}\n"
                f"停止热键: {close_hotkey}\n"
            )

def main():
    print(text2art("1000-7      SCRIPT", "standart"))

    print(
        "您好,当前程序设置如下:\n")
    initConfig()

    keyboard.add_hotkey(hotkey, lambda: print_1000_7())


    keyboard.wait()

def invert_run():
    global can_run
    can_run = not can_run
    print(f"运行状态已切换: {'继续' if can_run else '暂停'}")

def print_1000_7():
    global can_run
    can_run = True  # 启动刷屏时重置运行状态
    print("What is 1000-7?")
    if enable_open_chat_hotkey:
        keyboard.press_and_release(open_hotkey)
        keyboard.press_and_release('ctrl+a')
        keyboard.press_and_release('backspace')
        time.sleep(interval)

    keyboard.write("What is 1000-7?", character_interval)
    keyboard.press_and_release(send_msg_hotkey)

    keyboard.press_and_release('ctrl+a')
    keyboard.press_and_release('backspace')
    keyboard.press_and_release('F9')
    keyboard.write("What is 1000-7?")
    keyboard.press_and_release(send_msg_hotkey)
    if enable_open_chat_hotkey:
        keyboard.press_and_release(open_hotkey)

    for i in range(5):
        if not can_run:
            return
        print(5 - i)
        if enable_open_chat_hotkey:
            keyboard.press_and_release(open_hotkey)
            keyboard.press_and_release('ctrl+a')
            keyboard.press_and_release('backspace')
            time.sleep(interval)
        keyboard.write(str(5-i), character_interval)
        keyboard.press_and_release(send_msg_hotkey)
        time.sleep(1)

    x = 1000
    while x > 0:
        if not can_run:
            return
        var = x - 7
        if enable_open_chat_hotkey:
            keyboard.press_and_release(open_hotkey)
            keyboard.press_and_release('ctrl+a')
            keyboard.press_and_release('backspace')
            time.sleep(interval)
        keyboard.write(f"{x} - 7 = {var}", character_interval)
        x = var
        time.sleep(interval)
        keyboard.press_and_release(send_msg_hotkey)


if __name__ == '__main__':
    main()
    while True:
        keyboard.wait(close_hotkey)
        invert_run()

问题分析

原代码的核心问题:

  • main()函数中的keyboard.wait()会阻塞主线程,导致主入口处的终止热键监听循环完全无法执行。
  • 终止热键的注册时机错误,没有在程序启动阶段完成监听,导致热键触发无响应。

修改后的生效代码

import codecs
import sys
import time
from pathlib import Path
import colorama
import keyboard
from Tools.i18n.makelocalealias import pprint
from art import text2art
import yaml
import pyautogui as pag
pag.FAILSAFE = True
colorama.init()

# 激活热键
hotkey = "9"
# 打开聊天热键
open_hotkey = "shift+t"
# 启用打开聊天热键
enable_open_chat_hotkey = True
# 发送消息热键
send_msg_hotkey = "enter"
# 字符输入间隔
character_interval = 0
# 消息发送间隔
interval = 0.15

close_hotkey = "H+J"

can_run = True

def initConfig():
    global hotkey, open_hotkey, enable_open_chat_hotkey, send_msg_hotkey, character_interval, interval, close_hotkey
    if Path("config.yml").is_file():
        with codecs.open('config.yml', encoding="UTF-8") as f:
            loadedConfig = yaml.safe_load(f)
            hotkey = loadedConfig['hotkey']
            open_hotkey = loadedConfig['open_hotkey']
            enable_open_chat_hotkey = loadedConfig['enable_open_chat_hotkey']
            send_msg_hotkey = loadedConfig['send_msg_hotkey']
            character_interval = loadedConfig['character_interval']
            interval = loadedConfig['interval']
            close_hotkey = loadedConfig['close_hotkey']

            print(
                f"激活热键: {hotkey}\n"
                f"打开聊天热键(若启用): {open_hotkey}\n"
                f"是否启用游戏内打开聊天热键?: " + ("否", "是")[enable_open_chat_hotkey] + "\n"
                f"字符输入间隔: {character_interval}\n"
                f"消息发送间隔(建议保留0.2,过低Dota无法承受): {interval}\n"
                f"停止热键: {close_hotkey}\n"
            )

def invert_run():
    global can_run
    can_run = not can_run
    print(f"运行状态已切换: {'继续' if can_run else '暂停'}")

def print_1000_7():
    global can_run
    can_run = True  # 启动刷屏时重置运行状态,确保能正常执行
    print("开始执行1000-7刷屏流程")
    
    if enable_open_chat_hotkey:
        keyboard.press_and_release(open_hotkey)
        keyboard.press_and_release('ctrl+a')
        keyboard.press_and_release('backspace')
        time.sleep(interval)

    keyboard.write("What is 1000-7?", character_interval)
    keyboard.press_and_release(send_msg_hotkey)

    keyboard.press_and_release('ctrl+a')
    keyboard.press_and_release('backspace')
    keyboard.press_and_release('F9')
    keyboard.write("What is 1000-7?")
    keyboard.press_and_release(send_msg_hotkey)
    if enable_open_chat_hotkey:
        keyboard.press_and_release(open_hotkey)

    # 倒计时部分
    for i in range(5):
        if not can_run:
            print("已终止倒计时流程")
            return
        current_num = 5 - i
        print(current_num)
        if enable_open_chat_hotkey:
            keyboard.press_and_release(open_hotkey)
            keyboard.press_and_release('ctrl+a')
            keyboard.press_and_release('backspace')
            time.sleep(interval)
        keyboard.write(str(current_num), character_interval)
        keyboard.press_and_release(send_msg_hotkey)
        time.sleep(1)

    # 1000-7循环部分
    x = 1000
    while x > 0:
        if not can_run:
            print("已终止1000-7循环流程")
            return
        var = x - 7
        if enable_open_chat_hotkey:
            keyboard.press_and_release(open_hotkey)
            keyboard.press_and_release('ctrl+a')
            keyboard.press_and_release('backspace')
            time.sleep(interval)
        keyboard.write(f"{x} - 7 = {var}", character_interval)
        x = var
        time.sleep(interval)
        keyboard.press_and_release(send_msg_hotkey)

def main():
    print(text2art("1000-7      SCRIPT", "standart"))
    print("您好,当前程序设置如下:\n")
    initConfig()

    # 注册激活热键和终止热键
    keyboard.add_hotkey(hotkey, print_1000_7)
    keyboard.add_hotkey(close_hotkey, invert_run)

    print("程序已启动,按激活热键开始刷屏,按终止热键暂停/继续")
    keyboard.wait()  # 保持程序运行,监听热键

if __name__ == '__main__':
    main()

关键修改说明

  • 调整热键注册时机:将终止热键close_hotkey的注册移到main()函数内,和激活热键一起完成注册,确保程序启动后立即监听热键。
  • 移除冗余阻塞代码:删除主入口处的while True循环,避免和main()中的keyboard.wait()冲突,保证主线程专注于热键监听。
  • 重置运行状态:在print_1000_7()函数开头重置can_run为True,确保每次启动刷屏流程时都处于可运行状态。
  • 增强状态反馈:在终止循环时添加打印提示,便于确认热键是否生效。

内容的提问来源于stack exchange,提问作者Zenisoft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:25:41