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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:23:10