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

discord.py经济机器人buy命令可成功购买但无法发送Embed问题求助

问题根因
  1. 逻辑结构完全错位:buy_this函数购买成功时返回的res[0]为True,但你所有计算成本、生成购买成功Embed的代码全部写在if not res[0]的失败处理分支内,购买成功时根本不会执行这部分代码
  2. 判断逻辑不成立:item是用户输入的字符串,mainshop是存储商品字典的列表,item in mainshop的判断永远返回False,不可能拿到对应商品的price
  3. 变量作用域错误:cost定义在if item in mainshop的内部分支,就算逻辑成立,外部也访问不到该变量,会触发未定义变量报错
修复方案

首先修改buy_this函数的成功返回值,把实际消费金额一同返回,避免重复查询商品价格:

async def buy_this(user,item_name,amount):
    # 其余原有代码保持不变
    await update_bank(user,cost*-1,"wallet")

    # 修改原返回行为,把cost也带回
    return [True, cost]

然后重写buy命令的逻辑,单独处理购买成功分支:

@client.command()
async def buy(ctx,item,amount = 1):
    await open_account(ctx.author)
    res = await buy_this(ctx.author,item,amount)

    # 仅处理购买失败的情况
    if not res[0]:
        if res[1]==1:
            await ctx.send("That Object isn't there!")
            return
        if res[1]==2:
            await ctx.send(f"You don't have enough money in your wallet to buy {amount} {item}")
            return

    # 购买成功逻辑单独放在分支外
    cost = res[1]
    embed = discord.Embed(color = 0xff0000,description = f"{ctx.author.mention} bought {amount} {item} for `{cost}` coins")
    embed.set_author(icon_url = bot_pfp,name = f"Successful {item} purchase.")
    embed.set_footer(text ="Thank-You for your purchase")
    await ctx.send(embed=embed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:06:01