如何在discord.py v2中为斜杠命令添加选项?解决TypeError报错
错误原因与解决方案
错误根源
报错TypeError: 'function' object is not subscriptable是因为你误用了discord.app_commands.choices[int]作为参数类型注解:
discord.app_commands.choices是装饰器函数,不是泛型类,不能用[int]这种下标语法。- 同时
@app_commands.describe也不是用来定义选项列表的正确方式,选项应该用@app_commands.choices装饰器指定。
正确实现方式
方式1:接收选中选项的value值(推荐)
这种方式直接获取选项对应的value,代码更简洁,适合只需要判断value的场景:
@createGroup.command(name='channel', description='Create a channel with emoji.') @app_commands.rename(channels="Channels to choose from") @app_commands.choices(channels=[ discord.app_commands.Choice(name="General", value=1), discord.app_commands.Choice(name="Media", value=2) ]) async def embed_create(ctx: discord.Interaction, channels: int): if channels == 1: await ctx.response.send_message("you chose general") elif channels == 2: await ctx.response.send_message("you chose media")
说明:
- 参数
channels的类型注解写int,对应Choice里的value类型 - 用
@app_commands.choices装饰器定义可选列表 - 发送消息必须加
await,因为ctx.response.send_message是异步方法
方式2:接收完整的Choice对象(需同时获取name/value时用)
如果需要直接获取选项的name和value,可以用discord.app_commands.Choice[int]作为类型注解,无需额外装饰器:
@createGroup.command(name='channel', description='Create a channel with emoji.') @app_commands.rename(channels="Channels to choose from") async def embed_create(ctx: discord.Interaction, channels: discord.app_commands.Choice[int]): if channels.name == "General": await ctx.response.send_message("you chose general") elif channels.name == "Media": await ctx.response.send_message("you chose media")
说明:
- 这里用的是
Choice[int](首字母大写的Choice,泛型类),不是choices[int] - 选项会自动被Discord识别,无需额外装饰器定义列表
内容的提问来源于stack exchange,提问作者Bytes
相关产品推荐
相关产品推荐

