Discord.py中如何为setupBot命令动态添加服务器角色选择项?
解决方案:让Discord斜杠命令支持选择服务器角色
方法1:直接使用discord.Role参数类型
这是最省心的实现方式,discord.py原生支持将命令参数类型设为discord.Role,Discord客户端会自动加载当前服务器的所有角色作为可选选项,用户直接点选即可,完全不用手动输入。
修改后的代码示例:
import discord from discord import app_commands @bot.tree.command(name="setupBot", description="选择可访问机器人的角色") async def setupBot(ctx: discord.Interaction, role: discord.Role): await ctx.response.send_message(f"正在设置分类频道和子频道,指定权限角色:{role.name}") # 频道创建与权限覆盖逻辑示例 # 创建分类频道 category = await ctx.guild.create_category("机器人专属频道") # 给@everyone设置只读权限(仅能查看,不能发送消息) await category.set_permissions(ctx.guild.default_role, read_messages=True, send_messages=False) # 给指定角色开放发送消息权限 await category.set_permissions(role, send_messages=True) # 创建子频道 await category.create_text_channel("指令执行频道")
方法2:自定义自动补全(Autocomplete)
如果需要对可选角色做筛选(比如排除系统角色、按权限排序),可以用app_commands.autocomplete装饰器实现动态补全逻辑:
import discord from discord import app_commands async def role_autocomplete(interaction: discord.Interaction, current: str) -> list[app_commands.Choice[str]]: # 过滤掉@everyone角色(可根据需求调整筛选规则) filtered_roles = [role for role in interaction.guild.roles if role.name != "@everyone"] # 根据用户输入的关键词匹配角色名,最多返回25个选项(Discord限制) return [ app_commands.Choice(name=role.name, value=str(role.id)) for role in filtered_roles if current.lower() in role.name.lower() ][:25] @bot.tree.command(name="setupBot", description="选择可访问机器人的角色") @app_commands.autocomplete(role=role_autocomplete) async def setupBot(ctx: discord.Interaction, role: str): # 将选中的角色ID转换为Role对象 target_role = ctx.guild.get_role(int(role)) await ctx.response.send_message(f"正在设置频道,指定权限角色:{target_role.name}") # 后续权限设置逻辑同方法1
关键说明
- 优先用方法1,Discord会自动处理角色列表的加载和选择,代码量最少且体验最优。
- 权限覆盖部分,通过分别设置
@everyone和目标角色的权限,就能实现「仅指定角色可操作,其他成员只读」的效果。 - 方法2适合需要自定义角色展示规则的场景,但需要手动处理角色ID到对象的转换。
内容的提问来源于stack exchange,提问作者Ryan Thomas
相关产品推荐
相关产品推荐

