如何正确在类中定义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
相关产品推荐
相关产品推荐

