Discord.py Bot启动失败,报‘Main.run was never awaited’错误,不解为何需await
解决Discord.py Bot启动报错:Main.run was never awaited
错误原因
Main.run()是异步函数(用async def定义),调用异步函数必须用await触发执行,直接调用只会生成未被调度的协程对象,触发RuntimeWarning。- 额外问题:
discord.ext.commands.Bot.run()是同步阻塞方法,它会自行启动事件循环并持续运行至Bot关闭,把它放在异步函数里会破坏事件循环逻辑,必须调整。
修复步骤
1. 替换run为异步启动方法
把self.client.run(token)换成await self.client.start(token),start()是异步方法,能在async函数中正常使用,不会阻塞事件循环。
2. 启动事件循环执行异步函数
Python主程序不能直接用await,需用asyncio.run()来调度执行顶级异步函数。
修复后的完整代码
import asyncio import json import discord from discord.ext import commands # 以下为示例Cog类,需替换为你实际的实现 class BlacklistCommand(commands.Cog): def __init__(self, client): self.client = client class ClearCommand(commands.Cog): def __init__(self, client): self.client = client class DoxCommand(commands.Cog): def __init__(self, client): self.client = client class HelpCommand(commands.Cog): def __init__(self, client): self.client = client class InfoCommand(commands.Cog): def __init__(self, client): self.client = client class IpCommand(commands.Cog): def __init__(self, client): self.client = client class SlayerCommand(commands.Cog): def __init__(self, client): self.client = client class CommandErrorListener(commands.Cog): def __init__(self, client): self.client = client class OnMessageListener(commands.Cog): def __init__(self, client): self.client = client class OnReadyListener(commands.Cog): def __init__(self, client): self.client = client class Main: def __init__(self): self.client = None async def register_commands(self): self.client.remove_command("help") await self.client.add_cog(BlacklistCommand(self.client)) await self.client.add_cog(ClearCommand(self.client)) await self.client.add_cog(DoxCommand(self.client)) await self.client.add_cog(HelpCommand(self.client)) await self.client.add_cog(InfoCommand(self.client)) await self.client.add_cog(IpCommand(self.client)) await self.client.add_cog(SlayerCommand(self.client)) async def register_events(self): await self.client.add_cog(CommandErrorListener(self.client)) await self.client.add_cog(OnMessageListener(self.client)) await self.client.add_cog(OnReadyListener(self.client)) async def run(self): token = json.load(open('files/apikeys.json'))['discord']['bot_token'] intents = discord.Intents().all() self.client = commands.Bot("§", intents=intents, case_insensitive=True) await self.register_commands() await self.register_events() # 使用异步的start方法替代同步run await self.client.start(token) # 用asyncio.run启动异步任务 asyncio.run(Main().run())
关键说明
- 异步函数必须通过
await或事件循环调度才能执行,asyncio.run()是Python 3.7+推荐的启动顶级异步任务的方式。 client.start()是client.run()的异步版本,允许在async函数中嵌套使用,避免事件循环冲突。
内容的提问来源于stack exchange,提问作者Dr. Troll
相关产品推荐
相关产品推荐

