如何在Discord.py的app_command中实现无限discord.Role参数?
在Discord.py中实现接收无限个Role参数的Slash命令
问题说明
你尝试在Discord.py的app_command(Slash命令)中接收无限个discord.Role参数,直接使用*roles: discord.Role时触发错误:
TypeError: unsupported parameter kind in callback: VAR_POSITIONAL
这是因为Discord的Slash命令系统不支持Python原生的可变位置参数(*arg形式),需要用框架提供的特定方式实现多参数接收。
可行解决方案
Discord.py提供了两种有效方式实现接收多个同类型的Role参数:
1. 使用Greedy参数类型
在参数注解中使用app_commands.Greedy[discord.Role],该类型允许用户连续选择多个Role,直到没有更多输入为止,最终参数会被封装为列表:
import discord from discord import app_commands @bot.tree.command(name='example') @app_commands.describe(roles="需要选择的多个角色") async def example(interaction: discord.Interaction, roles: app_commands.Greedy[discord.Role]): # 处理roles列表,示例:输出选中角色的名称 role_names = [role.name for role in roles] await interaction.response.send_message(f"你选择了以下角色:{', '.join(role_names)}")
2. 使用列表类型注解
直接将参数注解设为list[discord.Role](Python 3.9+)或typing.List[discord.Role],同样可以接收多个Role,客户端会以“添加更多”的形式让用户逐个选择:
import discord from discord import app_commands from typing import List # Python 3.8及以下版本需要导入 @bot.tree.command(name='example') @app_commands.describe(roles="需要选择的多个角色") async def example(interaction: discord.Interaction, roles: List[discord.Role]): # 处理roles列表,示例:@提及选中的角色 role_mentions = [role.mention for role in roles] await interaction.response.send_message(f"你提到的角色:{' '.join(role_mentions)}")
注意事项
- 两种方式最终都会将用户选择的多个Role转换为列表,你可以直接遍历或操作这个列表。
Greedy类型更适合用户快速连续选择角色,而列表类型在客户端的交互形式更偏向于分步添加。
内容的提问来源于stack exchange,提问作者Andrey
相关产品推荐
相关产品推荐

