discord.py开发中如何让embed命令的多个参数都支持多词输入?
问题原因
discord.py 的命令参数默认按空格拆分解析,仅有末尾添加*前缀的 keyword-only 参数可以接收后续所有包含空格的连续内容。你当前的代码中只有description符合该规则,title为普通位置参数,遇到空格就会自动截断,且中间预留的comma分隔符参数也限制了title不能包含空格。
解决方案
推荐采用自定义参数拆分的方案,支持用英文逗号分隔两个多词参数,调用格式为!embed 这是多词标题 , 这是同样支持多词的描述内容,修改后的代码如下:
@client.command() async def embed(ctx, *, content: str): await ctx.channel.purge(limit=1) # 按第一个英文逗号拆分标题和描述,避免描述中包含逗号被误拆分 if "," in content: title, description = content.split(",", 1) # 去除参数前后多余的空格 title = title.strip() description = description.strip() else: # 无分隔符时的兼容逻辑,可根据需求调整默认值 title = content.strip() description = "" embed = discord.Embed(title = title, description = description) embed.set_footer(text="An embed") embed.set_author(name = f'{ctx.author.name} says', icon_url = ctx.author.avatar_url ) await ctx.send(embed = embed)
如果你不想调整代码逻辑,也可以直接要求调用方用双引号包裹带空格的参数,使用原有代码时输入!embed "这是多词标题" , "这是多词描述"也能实现需求,但对用户操作要求更高。
内容的提问来源于stack exchange,提问作者Daryl Shyju
相关产品推荐
相关产品推荐

