Python运行报RuntimeWarning:coroutine 'update_bank'未被await,仅hunt命令触发
问题修复方案
以下是你代码中存在的问题及对应修复方式:
- 错误1:hunt命令的item参数默认值配置错误
你写的async def hunt(ctx,item = ['rifle','Rifle'],amount = 1)中,item的默认值是列表,无参数调用hunt时,传入use_this函数的item参数是列表对象,执行item_name = item_name.lower()时会直接抛出AttributeError。未捕获的异常会导致协程执行中断,触发协程未await的警告。
修复方法:将item默认值改为字符串"rifle",在函数开头统一转小写处理大小写兼容即可。 - 错误2:重复调用use_this逻辑冗余
你在hunt函数开头无前置判断就调用了一次use_this,后续判定item为步枪时又调用了一次,多余的调用会导致物品重复扣除,也可能引发异常。
修复方法:删除开头的无用use_this调用,仅在参数校验通过后调用一次即可。 - 错误3:奖励逻辑位置完全颠倒
你现在把狩猎奖励的代码写在了if not res[0]分支内,也就是只有扣除步枪失败的时候才会执行奖励代码,逻辑完全相反,且代码放在了return语句之后,正常场景下根本不会执行。
修复方法:把奖励逻辑移到res返回成功的分支下,扣除步枪成功后再发放金币奖励。 - 额外排查点:你贴出的代码中update_bank调用都加了await,如果还有警告,检查update_bank函数内部实现,是否存在调用其他协程未加await的情况。
修复后参考代码
import random import json async def use_this(user,item_name,amount,price = None): item_name = item_name.lower() name_ = None for item in mainshop: name = item["name"].lower() if name == item_name: name_ = name if price==None: price = 0* item["price"] break if name_ == None: return [False,1] cost = price*amount users = await get_bank_data() bal = await update_bank(user) try: index = 0 t = None for thing in users[str(user.id)]["bag"]: n = thing["item"] if n == item_name: old_amt = thing["amount"] new_amt = old_amt - amount if new_amt < 0: return [False,2] users[str(user.id)]["bag"][index]["amount"] = new_amt t = 1 break index+=1 if t == None: return [False,3] except: return [False,3] with open("mainbank.json","w") as f: json.dump(users,f) await update_bank(user,cost,"wallet") return [True,"Worked"] @client.command() async def hunt(ctx, item = "rifle", amount = 1): # 统一转小写处理大小写 item = item.lower() # 参数校验 if amount > 1: await ctx.reply("你无法同时使用多把步枪,重量超出了你的承受范围!") return if item != "rifle": await ctx.reply(f"{ctx.author.mention} 狩猎只能使用步枪!") return # 仅调用一次use_this扣除物品 res = await use_this(ctx.author, item, amount) if not res[0]: if res[1]==1: await ctx.reply(f"{ctx.author.mention} 该物品不存在!") return if res[1]==2: await ctx.reply(f"{ctx.author.mention} 你的背包里没有{amount}个{item}。") return if res[1]==3: await ctx.reply(f"{ctx.author.mention} 你的背包里没有{item}。") return # 扣除成功后发放狩猎奖励 aninames = ['熊','兔子','狼'] animals = random.choice(aninames) earnings = random.randrange(5000) # 给用户账户加金币 await update_bank(ctx.author, earnings, "wallet") await ctx.reply(f"你打猎捉到了一只{animals},卖了{earnings}金币!不过过程中你把步枪弄丢了..")
内容的提问来源于stack exchange,提问作者Ash
相关产品推荐
相关产品推荐

