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

如何将Discord机器人Embed命令的参数设置为非必填项?

解决Discord机器人Embed命令参数必填问题

要把这些参数改成非必填,核心是给函数参数设置默认值,并调整Embed的构建逻辑,只在参数有值时才对应设置属性,具体修改如下:

1. 修改参数定义

给每个参数设置默认值None,让它们成为可选参数。如果希望用户通过关键字指定参数(比如!embed title=我的标题 content=内容),可以保留*将参数设为关键字参数,这样用户无需按顺序填写。

2. 调整Embed构建逻辑

创建基础Embed对象后,逐个判断参数是否有值,有值才调用对应的设置方法,避免传入空值导致报错。同时修复原代码中ctx.respond缺少await、重复调用的问题。

修改后的完整代码

@bot.command(name="embed", description="使用此命令创建Embed消息")
async def embed(ctx, *, title=None, content=None, urlthumbnail=None, urlimage=None, footer=None, fieldname=None, value=None):
    if not isOwner(ctx):
        return await ctx.respond("仅所有者或工作人员可使用此命令。")

    # 构建自定义Embed
    embed = discord.Embed()
    if title:
        embed.title = title
    if content:
        embed.description = content
    if urlthumbnail:
        embed.set_thumbnail(url=urlthumbnail)
    if urlimage:
        embed.set_image(url=urlimage)
    if footer:
        embed.set_footer(text=footer)
    if fieldname and value:  # 字段名和值都存在时才添加字段
        embed.add_field(name=fieldname, value=value)
    
    # 发送自定义Embed
    await ctx.send(embed=embed)
    
    # 发送创建成功提示Embed
    success_embed = discord.Embed(title=" <:pnlstore:1028979693241761833> | Embed已创建 ", description=f"<:oui:1030175858431885396> Embed由**{ctx.author.mention}**创建")
    success_embed.set_footer(text=".gg/pnlstore")
    await ctx.respond(embed=success_embed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:46:07