discord.py中Cog内命令失效及RuntimeWarning报错求助
问题修复方案
1. 解决coroutine 'BotBase.add_cog' was never awaited警告
在discord.py v2.x版本中,add_cog已改为异步方法,必须通过await调用,且需要传入实例化的Cog对象(而非类本身)。修改main.py如下:
import discord, os from discord.ext import commands from games import Games pr = '*' bot = commands.Bot(command_prefix=pr, intents=discord.Intents.all()) @bot.event async def on_ready(): # 实例化Games类并异步添加cog await bot.add_cog(Games(bot)) await bot.change_presence(activity=discord.Game('Bot')) print('{0.user}'.format(bot)) bot.run('你的Bot令牌')
2. 修复slot命令无法正常工作的问题
slot命令存在逻辑错误,修改games.py如下:
import discord import random from discord.ext import commands class Games(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def slot(self, ctx, bet: int): # 使用int转换器自动处理数字输入 row = ['🍋', '🍊', '🍒', '🍇', '🏆', '🔥'] slot1 = random.choice(row) slot2 = random.choice(row) slot3 = random.choice(row) word = 'l' win_amount = 0 # 用==判断字符串内容相等,而非is(is判断对象身份) if slot1 == slot2 == slot3: word = 'w' if slot1 == '🍊': win_amount = bet * 1 elif slot1 == '🍒': win_amount = bet * 2 elif slot1 == '🍇': win_amount = bet * 3 elif slot1 == '🏆': win_amount = bet * 5 elif slot1 == '🔥': win_amount = bet * 4 # 构建正确的embed内容 embed_title = '获胜!' if word == 'w' else '失败!' embed = discord.Embed(title=embed_title, color=ctx.author.color) embed.add_field(name=f'{slot1} {slot2} {slot3}', value=f'{"你赢了" + str(win_amount) + "个筹码!" if word == "w" else "你输掉了所有赌注!"}') await ctx.send(embed=embed)
关键修改点说明:
- 使用
bet: int参数转换器,自动验证输入为数字,避免转换错误 - 替换
is为==判断字符串相等,保证逻辑正确性 - 修正embed的标题和内容,显示实际输赢结果
- 明确计算赢取金额,避免直接修改原bet值引发的逻辑混乱
内容的提问来源于stack exchange,提问作者JoniiDeb
相关产品推荐
相关产品推荐

