Discord Python Bot扩展加载失败及协程未等待问题求助
问题分析
你的错误有两个核心诱因:
- 扩展代码存在语法错误:扩展文件最后一行的
async def setup函数末尾多了一个多余的反引号,导致Python无法正确解析扩展逻辑,直接触发加载失败。 - 事件循环冲突:错误提示
asyncio.run() cannot be called from a running event loop,说明在扩展的模块顶层(比如数据库连接代码)调用了asyncio.run(),而此时Bot已经启动了事件循环,重复调用会引发冲突。
修复步骤
1. 修正扩展的语法错误
找到扩展文件最后一行,去掉末尾多余的反引号:
async def setup(bot): await bot.add_cog(MiComandoCog1(bot=bot))
2. 解决事件循环冲突(数据库连接部分)
如果你的数据库连接是异步操作,且之前在模块顶层用asyncio.run()执行连接逻辑,需要将连接初始化移到Cog的cog_load方法中,用await执行,避免在已有事件循环的情况下调用asyncio.run():
修改扩展代码中的数据库连接逻辑:
import discord from discord.ext import commands from ggbot import tablas_suffix # 暂时不直接导入已建立的连接 class MiComandoCog1(commands.Cog): def __init__(self, bot): self.bot = bot # 初始化连接和游标变量 self.conexion_juegos = None self.cursor_juegos = None self.conexion_inventarios = None async def cog_load(self): # 在这里异步初始化数据库连接(替换成你的实际连接代码) # 示例:如果是异步mysql连接 self.conexion_juegos = await your_async_db_connect_function() self.cursor_juegos = self.conexion_juegos.cursor() # 同理初始化conexion_inventarios print(f"{self.__class__.__name__} loaded!") # 修改change命令,使用self的连接和游标 @commands.command() async def change(self, ctx, columna_a_cambiar, nombre_encontrar, valor): for sufijo in tablas_suffix: self.cursor_juegos.execute(f"SELECT {columna_a_cambiar} FROM per_{sufijo} WHERE nombres = '{nombre_encontrar}'") resultado = self.cursor_juegos.fetchone() if resultado is not None: self.cursor_juegos.execute(f"UPDATE per_{sufijo} SET {columna_a_cambiar} = '{valor}' WHERE nombres = '{nombre_encontrar}'") self.conexion_juegos.commit() await ctx.send("Valores cambiados.") # 其他代码保持不变... async def setup(bot): await bot.add_cog(MiComandoCog1(bot=bot))
如果你的数据库是同步版本(比如mysql.connector的同步模式),则需要检查模块顶层是否有调用asyncio.run()的代码,将其移除或移到合适的异步方法中执行。
3. 额外优化:规避SQL注入风险
你的change命令直接将用户输入拼接到SQL语句中,存在严重的SQL注入风险,建议改用参数化查询:
# 修改change命令中的SQL执行部分 self.cursor_juegos.execute( f"SELECT {columna_a_cambiar} FROM per_{sufijo} WHERE nombres = %s", (nombre_encontrar,) ) # 更新语句同理 self.cursor_juegos.execute( f"UPDATE per_{sufijo} SET {columna_a_cambiar} = %s WHERE nombres = %s", (valor, nombre_encontrar) )
验证修复
- 保存所有修改后的代码
- 重新启动Bot,检查是否还会出现事件循环错误和语法错误
内容的提问来源于stack exchange,提问作者Bbokari
相关产品推荐
相关产品推荐

