我正在尝试制作一个可以阅读群组中发送的所有消息并玩游戏的机器人。类似于 Twitch Plays Pokemon 的东西,但适用于每场比赛。
现在我有了这段代码,该机器人在 Telegram 中运行良好,但是一旦它聚焦窗口并且应该移动它就不会...
import logging
import pyautogui # Importa la biblioteca pyautogui
import pygetwindow as gw
from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
# Configurar el registro
logging.basicConfig(level=logging.INFO)
TOKEN = "TOKEN"
MOVEMENTS = {
"up": "w",
"Up": "W",
"down": "s",
"left": "a",
"right": "d"
}
def focus_pokemon_window(window_title):
try:
window = gw.getWindowsWithTitle(window_title)[0]
window.restore()
window.activate()
except IndexError:
print(f"No se encontró ninguna ventana con el título '{window_title}'.")
def move_character(direction):
focus_pokemon_window("Pokemon - FireRed Version (USA) [Gameboy Advance] - BizHawk")
pyautogui.hotkey(MOVEMENTS[direction])
def start(update: Update, context: CallbackContext):
pass
def handle_text(update: Update, context: CallbackContext):
bot_username = context.bot.username
text = update.message.text.lower()
if f"@{bot_username.lower()}" not in text:
return
# Eliminar la mención del bot del texto
text = text.replace(f"@{bot_username.lower()}", "").strip()
if text in MOVEMENTS:
move_character(text)
else:
update.message.reply_text("Comando desconocido. Por favor, envía una dirección válida (up, down, left, right).")
def main():
updater = Updater(TOKEN)
dispatcher = updater.dispatcher
# Agregar manejadores de comandos y mensajes
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_text))
# Iniciar el bot
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
比赛将由OBS私下直播
我尝试了各种解决方案,但似乎当窗口弹出时它没有任何动作。
根据我的经验,任何涉及使用 pygetwindow 或 pywin32 之类的东西按名称拉出特定窗口的东西都不能真正始终如一地工作,有时有效,有时无效。我责怪微软在没有太多文档的情况下不断更改 Windows API。您可以尝试使用 Pyautogui 来获取窗口。要在 Pyautogui 中单击图像,只需使用
pyautogui.click(x = image_name)
。确保您的截屏是准确的,如果您使用的是 Windows,请点击 Windows 按钮,然后键入“snip”。拖动您要单击的部分,然后单击保存。如果您不能将图像裁剪得足够小,请下载 GIMP 并用它裁剪。
我的代码的主要问题是使用旧的导入。
import pyautogui
相反,我使用了pydirectinput。
import pydirectinput
我刚刚替换了所有功能后。