Discord.py命令签名不匹配求助:newpython命令同步失败
解决discord.py中newpython命令的CommandSignatureMismatch错误及代码优化
问题说明
我编写了newpython命令,想要实现:当文件名有效且未在ListPython.txt中存在时,创建对应的.txt文件。但运行时触发以下错误:
discord.app_commands.errors.CommandSignatureMismatch: The signature for command 'newpython' is different from the one provided by Discord. This can happen because either your code is out of date or you have not synced the commands with Discord, causing the mismatch in data. It is recommended to sync the command tree to fix this issue.
当前代码:
@bot.tree.command(name="newpython") @app_commands.describe(FileName='FileName') async def newpython(interaction: discord.Interaction,FileName: str): AddToLog(f'[INFO][{GetTime()}] newpython command has been used') _ = open("Program Files/ListPython.txt", "r") _ = _.read() _ = _.split() if FileName not in _: with open("Program Files/ListPython.txt", "a") as file1: file1.write(f' {FileName}') try: f = open(f"Python Files/{FileName}.txt", "x") await interaction.response.send_message(f"{FileName} created") except OSError: await interaction.response.send_message(f"{FileName} is a invalid file name.") else: await interaction.response.send_message(f"{FileName} already exists.")
错误原因及解决步骤
1. 核心问题:命令签名不匹配
这个错误的本质是Discord服务器端存储的命令签名和你本地代码的签名不一致——哪怕你移除@app_commands.describe,只要之前的命令已经同步到Discord,就会出现不匹配。必须先同步命令树:
同步命令树的代码实现
在你的Bot启动逻辑中添加同步钩子,开发环境可以用全局同步,生产环境建议指定服务器同步(避免全局延迟):
# 全局同步(开发环境用) async def setup_hook(): await bot.tree.sync() print("命令树已同步至Discord") bot.setup_hook = setup_hook
或者指定服务器同步:
# 指定服务器同步(生产环境用) async def setup_hook(): target_guild = discord.Object(id=你的服务器ID) bot.tree.copy_global_to(guild=target_guild) await bot.tree.sync(guild=target_guild) print(f"命令树已同步至服务器 {target_guild.id}") bot.setup_hook = setup_hook
运行一次同步后可以注释掉这段代码,避免每次启动重复同步。
2. 代码优化(避免后续潜在问题)
除了签名问题,你的代码还有几个可以改进的地方:
- 避免变量名连续用
_赋值:会丢失文件句柄导致资源泄漏,改用明确的变量名+with语句:with open("Program Files/ListPython.txt", "r") as file: content = file.read() existing_files = content.split() - 用换行分隔文件名:原代码用空格分隔,若文件名含空格会导致判断错误,写入和读取时改用换行:
# 写入时 file1.write(f'{FileName}\n') # 读取时 existing_files = content.splitlines() - 创建文件时用
with语句:自动关闭文件句柄,避免资源占用:try: with open(f"Python Files/{FileName}.txt", "x") as f: pass # 可在此写入初始内容 await interaction.response.send_message(f"{FileName} created") except OSError: await interaction.response.send_message(f"{FileName} is an invalid file name.") - 用
pathlib处理路径:避免跨平台路径兼容问题:from pathlib import Path list_file_path = Path("Program Files") / "ListPython.txt" target_file_path = Path("Python Files") / f"{FileName}.txt"
内容的提问来源于stack exchange,提问作者user20753874
相关产品推荐
相关产品推荐

