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

Discord Python机器人命令参数异常求助:已定义参数仍报错

Discord.py 机器人命令问题修正

核心问题分析

  1. 命令参数顺序错误:discord.py 要求命令函数的第一个参数必须是ctx(上下文对象),你把get_embedID放在最前面,导致系统把ctx识别成range1,直接触发range2参数缺失的提示。
  2. addEmbed的返回值无效:命令函数的return语句无法保存消息ID,下次调用editEmbed根本拿不到之前生成的Embed消息ID,得找个地方存储这个值。
  3. Embed操作语法错误:设置标题、添加字段的方法调用有误,编辑消息时也用错了操作对象。

修正方案

1. 调整命令参数顺序

所有命令的第一个参数必须是ctx,参数顺序错误会直接导致解析混乱。

2. 存储Embed消息ID

用全局变量临时存储生成的消息ID(小项目足够用,若需持久化可改用JSON文件或数据库),避免用户手动输入的麻烦。

3. 修正Embed操作逻辑

  • 设置标题直接赋值给embed.title,而非调用embed.title()方法
  • add_field必须传入name参数(可设为空字符串,但不能省略)
  • 编辑消息要使用获取到的message对象,而非直接用ID数字调用方法

完整修正代码

# 全局变量存储Embed消息ID,机器人运行期间有效
embed_message_id = None

@bot.command()
async def addEmbed(ctx):
    global embed_message_id
    channel = bot.get_channel(1234567890)  # 替换为你的目标频道ID
    embed = discord.Embed(title='Placeholder')
    message = await channel.send(embed=embed)
    embed_message_id = message.id
    await ctx.send(f"占位Embed已生成,消息ID:{embed_message_id}")

@bot.command()
async def editEmbed(ctx, range1, range2):
    global embed_message_id
    if not embed_message_id:
        await ctx.send("请先运行!addEmbed生成占位Embed!")
        return
    
    try:
        # 注意:要去生成Embed的频道取消息,而非当前命令调用的频道
        channel = bot.get_channel(1234567890)
        message = await channel.fetch_message(embed_message_id)
    except discord.NotFound:
        await ctx.send("找不到对应的Embed消息!")
        return
    
    embed = message.embeds[0]
    embed.title = 'Open for current prices:'
    embed.add_field(name='价格范围', value=f'{range1} to {range2}', inline=False)
    await message.edit(embed=embed)
    await ctx.send("Embed已更新!")

# 可选:支持用户手动输入消息ID的版本
@bot.command()
async def editEmbedByID(ctx, embed_id: int, range1, range2):
    try:
        channel = bot.get_channel(1234567890)
        message = await channel.fetch_message(embed_id)
    except discord.NotFound:
        await ctx.send("找不到对应的Embed消息!")
        return
    
    embed = message.embeds[0]
    embed.title = 'Open for current prices:'
    embed.add_field(name='价格范围', value=f'{range1} to {range2}', inline=False)
    await message.edit(embed=embed)
    await ctx.send("Embed已更新!")

补充说明

  • 全局变量embed_message_id在机器人重启后会失效,若需要持久化保存ID,可改用JSON文件或SQLite数据库。
  • 调用命令时,!editEmbed 123 456即可直接使用;若用手动传ID的版本,需输入!editEmbedByID 消息ID 123 456。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:20:42