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

sqlite3 cursor.execute导致discord.py斜杠命令无响应求助

修复discord.py hybrid_command配合sqlite3卡顿无响应的方案
  • 替换同步sqlite3为异步操作
    sqlite3是同步阻塞库,在discord.py的异步事件循环中执行会卡住线程,导致Discord超时返回"The application did not respond"。两种解决方式:

    1. 使用异步数据库库aiosqlite,所有数据库操作改为异步调用:
      import aiosqlite
      
      @bot.hybrid_command(name="addoc")
      async def addoc(ctx):
          await ctx.defer()  # 提前发送延迟响应,避免超时
          async with aiosqlite.connect("your_database.db") as db:
              async with db.cursor() as cursor:
                  await cursor.execute("INSERT INTO your_table (...) VALUES (...)")
                  await db.commit()
          await ctx.send("操作成功完成")
      
    2. 用asyncio.to_thread将同步sqlite3操作包装到单独线程:
      import asyncio
      import sqlite3
      
      def sync_db_task():
          conn = sqlite3.connect("your_database.db")
          cursor = conn.cursor()
          cursor.execute("INSERT INTO your_table (...) VALUES (...)")
          conn.commit()
          conn.close()
      
      @bot.hybrid_command(name="addoc")
      async def addoc(ctx):
          await ctx.defer()
          await asyncio.to_thread(sync_db_task)
          await ctx.send("操作成功完成")
      
  • 确保ctx.defer()的调用时机正确
    必须在任何可能阻塞的操作(比如数据库执行、网络请求)之前调用await ctx.defer(),不能先执行耗时操作再发送延迟响应,否则Discord会先判定超时。

  • 检查数据库连接与锁状态
    排查是否存在未正确关闭的数据库连接,普通commands.command()可能因同步执行未暴露锁问题,但异步上下文里未关闭的连接会导致数据库锁表,卡住cursor.execute。确保所有数据库操作都用上下文管理器(with语句)自动关闭连接,或手动调用conn.close()。

  • 验证hybrid_command的同步状态
    启动机器人时执行await bot.tree.sync()确保命令同步到Discord服务器,若为测试服务器,可指定 guild ID 加速同步:

    @bot.event
    async def on_ready():
        await bot.tree.sync(guild=discord.Object(id=你的服务器ID))
        print("机器人已就绪")
    

内容的提问来源于stack exchange,提问作者Chris Ze Third

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 07:27:18