如何为Discord.py斜杠命令添加自动补全功能?
解决discord.py斜杠命令自动补全失效问题
你的自动补全函数逻辑本身没问题,但大概率是没有正确将函数绑定到斜杠命令的参数上,或者存在版本/导入类的问题。以下是完整的正确实现步骤:
1. 确认依赖版本
确保你使用的是discord.py v2.0及以上版本,自动补全功能是在这个版本才正式引入的。可以通过命令查看版本:
pip show discord.py
如果版本过低,执行升级:
pip install -U discord.py
2. 正确导入所需模块
确保代码顶部导入了必要的模块:
import discord from discord import app_commands import typing
3. 绑定自动补全函数到命令参数
你的补全函数需要通过autocomplete参数关联到斜杠命令的对应参数上,完整示例代码如下:
import discord from discord import app_commands import typing class MyClient(discord.Client): def __init__(self, *, intents: discord.Intents): super().__init__(intents=intents) self.tree = app_commands.CommandTree(self) async def setup_hook(self): # 同步命令到目标服务器(测试用,生产环境建议全局同步) guild = discord.Object(id=你的服务器ID) self.tree.copy_global_to(guild=guild) await self.tree.sync(guild=guild) async def drink_autocompletion( interaction: discord.Interaction, current: str ) -> typing.List[app_commands.Choice[str]]: data = [] drink_choices = ['beer', 'milk', 'tea', 'coffee', 'juice'] for drink in drink_choices: if current.lower() in drink.lower(): data.append(app_commands.Choice(name=drink, value=drink)) return data client = MyClient(intents=discord.Intents.default()) # 定义带自动补全的斜杠命令 @client.tree.command(name="order", description="点一杯饮品") @app_commands.describe(drink="选择你想点的饮品") async def order(interaction: discord.Interaction, drink: str): await interaction.response.send_message(f"你点了一杯{drink}!") # 将补全函数绑定到drink参数 @order.autocomplete('drink') async def drink_autocomplete(interaction: discord.Interaction, current: str) -> typing.List[app_commands.Choice[str]]: return await drink_autocompletion(interaction, current) client.run("你的机器人Token")
4. 常见错误排查
- 缩进错误:Python对缩进敏感,确保补全函数的缩进层级正确
- 未同步命令:新添加的命令必须调用
tree.sync()同步到Discord服务器,否则不会显示 - 参数类型不匹配:补全函数返回值必须是
typing.List[app_commands.Choice[str]],确保current参数为字符串类型 - 权限问题:机器人需要在服务器中拥有
应用程序命令相关权限,检查角色权限是否足够
内容的提问来源于stack exchange,提问作者komumoru
相关产品推荐
相关产品推荐

