Discord.py 2.4中使用Greedy[Member]实现Slash命令时出现TypeError的解决方法
Discord.py 2.4中使用Greedy[Member]实现Slash命令时出现TypeError的解决方法
嘿,我来帮你搞定这个问题!你遇到的问题根源在于:discord.ext.commands.Greedy是专门为传统前缀命令设计的参数解析工具,但你现在写的是Slash命令(也就是app commands/tree命令),这俩的参数处理逻辑完全不一样,所以才会抛出那个类型错误。
在Discord.py的Slash命令体系里,要实现“多选成员”的需求,根本不需要用Greedy,直接把参数类型声明为list[discord.Member]就可以了——Discord.py会自动把它转换成Discord客户端上支持多选的成员选择器。
下面是修改后的可运行代码:
import discord from discord.ext import commands from discord import app_commands class MyClient(commands.Bot): def __init__(self, *, intents: discord.Intents): # 前缀命令的前缀这里可以随便设,因为我们用的是Slash命令,不影响核心功能 super().__init__(command_prefix="/", intents=intents) intents = discord.Intents.default() intents.message_content = True intents.members = True client = MyClient(intents=intents) @client.tree.command(name="slap") async def slap(interaction: discord.Interaction, members: list[discord.Member], *, reason='no reason'): # 把选中的成员名字拼接成可读性强的字符串 slapped = ", ".join(x.name for x in members) await interaction.response.send_message(f'{slapped} just got slapped for {reason}') # 记得替换成你的Bot令牌再运行 client.run("你的Bot令牌")
为什么这样改能行?
- Slash命令的参数是通过Discord官方API的交互系统定义的,当你把参数类型设为
list[某个Discord对象]时,Discord.py会自动告诉Discord服务器:这个参数允许用户选择多个对应的实体(比如这里的成员)。 - 而
commands.Greedy是针对前缀命令的文本参数解析(比如!slap @user1 @user2 随便找个理由这种格式),完全不适用于Slash命令的结构化参数体系。
修改后,你就能像期待的那样使用命令了:
输入/slap members:@user1, @user2, @user3 reason="I am greedy",执行后会输出:user1, user2, user3 just got slapped for I am greedy
备注:内容来源于stack exchange,提问作者Reed
相关产品推荐
相关产品推荐

