You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.py中通过SlashCommand实现多User选择?

在discord.py中通过斜杠命令实现多选Discord用户的方案

discord.py的斜杠命令不支持直接用List[User]作为参数类型(会抛出TypeError),但官方提供了专门的方案实现多选用户需求,核心是使用app_commands.Greedy类型注解:

实现步骤与代码示例

Greedy是discord.py为多选参数场景设计的包装类型,它会让斜杠命令界面允许用户多次选择目标类型的对象,最终将所有选中项打包为列表传入命令函数。

示例代码:

import discord
from discord import app_commands
from discord.ext import commands

class MultiUserCog(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @app_commands.command(name="pick_users", description="选择多个Discord用户")
    async def pick_users(self, interaction: discord.Interaction, users: app_commands.Greedy[discord.User]):
        # 处理选中的用户列表
        if not users:
            await interaction.response.send_message("你没有选择任何用户")
            return
        mention_list = [user.mention for user in users]
        await interaction.response.send_message(f"已选中用户:{' '.join(mention_list)}")

async def setup(bot: commands.Bot):
    await bot.add_cog(MultiUserCog(bot))

额外配置:限制最大选择数量

如果需要限制用户最多选择的数量,可以在Greedy中添加数值参数:

# 最多允许选择3个用户
users: app_commands.Greedy[discord.User, 3]

关于AppCommandOptionType的说明

AppCommandOptionType文档里的“通常”指的是基础参数类型(如单个User、字符串、数字等),多选场景不属于基础类型范畴,需要通过Greedy这种官方提供的包装类型来实现,这是discord.py指定的标准多选参数实现方式。

内容的提问来源于stack exchange,提问作者CcmU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 19:07:12