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

如何正确在类中定义discord.Client并将其作为任务在自定义循环中运行

错误原因及修复方案

现存代码的核心错误点

  • 类继承错误:discord.Client 不支持命令装饰器、命令前缀等 commands 扩展功能,需要继承 commands.Bot
  • 类方法缺失 self 参数:所有类实例方法的第一个参数必须为 self,否则调用属性、方法时会直接抛出异常
  • 事件装饰器误用:@commands.Cog.listener 是给独立 Cog 组件使用的,Bot 子类内部的事件监听不需要加该装饰器,直接声明对应异步方法即可
  • 事件循环未正确启动:loop.run_until_complete 没有传入等待的协程对象,相当于没有启动事件循环,程序执行到最后直接退出
  • 命令处理逻辑缺失:Bot 子类如果没有配置消息处理钩子,不会自动触发自定义命令,需要补充 on_message 事件调用命令处理方法

修复后可运行的单Bot代码

import discord
import asyncio
from discord.ext import commands

token = "你的机器人token"

class CustomBot(commands.Bot):
    async def on_ready(self):
        print(f"登录成功:{self.user.id}")
    
    @commands.command()
    async def testing(self, ctx):
        await ctx.send("hello")
    
    async def on_message(self, message):
        # 必须调用这个方法才会处理命令
        await self.process_commands(message)

loop = asyncio.get_event_loop()
# 初始化Bot实例,指定命令前缀和Intents(Discord.py v2.0+强制要求)
bot = CustomBot(command_prefix="!", intents=discord.Intents.all())
# 创建Bot启动任务
loop.create_task(bot.start(token))
# 挂起事件循环,保持运行
loop.run_forever()

注意:需要同时在 Discord 开发者后台开启对应 Intents 权限,否则无法接收消息、触发事件。

多Bot同时运行的修改方案

如果需要同时启动多个机器人,只需要创建多个 CustomBot 实例,分别调用 start 加入事件循环即可,示例如下:

# 多个机器人的token列表
tokens = ["token1", "token2", "token3"]

loop = asyncio.get_event_loop()
for token in tokens:
    bot = CustomBot(command_prefix="!", intents=discord.Intents.all())
    loop.create_task(bot.start(token))

loop.run_forever()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 14:54:06