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

如何创建支持并发处理的Discord命令函数 避免全局执行阻塞

修复方案

问题原因

discord.py 基于异步事件循环运行,你代码中使用的time.sleep(10)是同步阻塞方法,调用后会直接卡住整个事件循环线程,期间所有其他命令的处理都会被暂停,直到阻塞结束。

修改步骤

  1. 导入异步IO库asyncio
  2. 将sleep_now方法中的同步睡眠替换为异步非阻塞的asyncio.sleep

修改后完整代码

import asyncio
from discord.ext import commands


class Hello(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'{self.__class__.__name__} Cog is ready')

    @commands.command()
    async def hello(self, ctx):
        await ctx.send('Hello partner!')

    @commands.command()
    async def sleeper(self, ctx):
        await self.sleep_now()
        await ctx.send('I have been sleeping for 10 seconds')

    async def sleep_now(self):
        # 替换为异步睡眠,不会阻塞事件循环
        await asyncio.sleep(10)

def setup(client):
    client.add_cog(Hello(client))

效果验证

修改后运行流程和你的预期完全一致:

  • 输入!sleeper后立即输入!hello,机器人会先响应Hello partner!
  • 等待10秒后,机器人再发送I have been sleeping for 10 seconds

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:15:03