Discord.py出现coroutine 'Command.__call__' was never awaited警告
问题背景
- 开发目标:编写可控制本地命令面板的Discord机器人,运行时出现异常,已检索同类问题但故障场景不匹配
- 关联实现代码:
from pyautogui import * import pyautogui import win32gui import time import clipboard import discord from discord.ext import commands botToken = "No" client = commands.Bot(command_prefix='!', help_command=None) fileLocation = "C:/Users/Admin/Downloads/Program.exe" def screenshot(): with open("hwnd.txt", "r") as file: hwnd = int(file.read()) win32gui.SetForegroundWindow(hwnd) x, y, x1, y1 = win32gui.GetClientRect(hwnd) x, y = win32gui.ClientToScreen(hwnd, (x, y)) x1, y1 = win32gui.ClientToScreen(hwnd, (x1 - x, y1 - y)) pyautogui.screenshot("screenshot.png",region=(x, y-27, x1, y1+27)) @client.command() async def start(ctx): if clipboard.paste != fileLocation: clipboard.copy(fileLocation) pyautogui.hotkey('winleft', 'r') time.sleep(0.5) pyautogui.hotkey('ctrl', 'v') pyautogui.press("enter") time.sleep(0.5) with open("hwnd.txt","w") as file: hwnd = win32gui.FindWindow(None, fileLocation.replace("/","\\")) file.write(str(hwnd)) time.sleep(0.1) screenshot() time.sleep(0.1) await ctx.channel.send("Screenshot:", file=discord.File("screenshot.png")) client.run(botToken)
- 运行时警告:
RuntimeWarning: coroutine 'Command.__call__' was never awaited screenshot() RuntimeWarning: Enable tracemalloc to get the object allocation traceback
- 补充排查信息:警告实际由上述代码片段未展示的
screenshot机器人命令触发。
故障根因
出现该警告是命名冲突导致:
你先定义了名为screenshot的普通同步截图函数,后续又用@client.command()装饰器注册了同名的screenshot机器人命令。discord.py注册命令时,会生成对应的Command协程对象,覆盖当前命名空间里原来的screenshot普通函数。此时你在start命令里调用screenshot()时,实际拿到的是未执行的命令协程对象,没有加await调用就会触发「协程从未被等待」的警告,原本的截图逻辑也不会正常执行。
修复方案
- 重命名自定义的同步截图函数,彻底避免和机器人命令重名,比如将普通截图函数改名为
capture_window:
def capture_window(): with open("hwnd.txt", "r") as file: hwnd = int(file.read()) win32gui.SetForegroundWindow(hwnd) x, y, x1, y1 = win32gui.GetClientRect(hwnd) x, y = win32gui.ClientToScreen(hwnd, (x, y)) x1, y1 = win32gui.ClientToScreen(hwnd, (x1 - x, y1 - y)) pyautogui.screenshot("screenshot.png",region=(x, y-27, x1, y1+27))
- 替换所有调用原普通截图函数的位置,比如
start命令里的调用改为新函数名:
@client.command() async def start(ctx): if clipboard.paste != fileLocation: clipboard.copy(fileLocation) pyautogui.hotkey('winleft', 'r') time.sleep(0.5) pyautogui.hotkey('ctrl', 'v') pyautogui.press("enter") time.sleep(0.5) with open("hwnd.txt","w") as file: # 注意:原逻辑这里存在额外bug,FindWindow第二个参数需要传窗口标题,传程序路径会返回无效句柄0,后续窗口操作会全部报错,请替换为程序启动后的实际窗口标题 hwnd = win32gui.FindWindow(None, "程序实际窗口标题") file.write(str(hwnd)) time.sleep(0.1) capture_window() # 替换为重命名后的函数 time.sleep(0.1) await ctx.channel.send("Screenshot:", file=discord.File("screenshot.png"))
内容的提问来源于stack exchange,提问作者Hadi
相关产品推荐
相关产品推荐

