Discord.py提醒命令运行时阻塞其他命令执行问题求助
问题根源
你代码中的阻塞问题完全来自同步休眠函数time.sleep():discord.py是基于asyncio异步事件循环运行的框架,time.sleep()是同步阻塞方法,调用时会直接暂停整个线程的所有运行逻辑,直到休眠结束才会恢复事件循环的任务调度,自然就没法响应其他命令。
修复方案
只需要做3处调整即可解决问题:
- 顶部引入asyncio库,将
time.sleep替换为异步休眠方法await asyncio.sleep(),休眠时不会阻塞事件循环处理其他任务 - 移除循环内不必要的
import time导入语句,导入操作放在代码顶部执行即可 - 合并重复的异常处理逻辑,减少冗余代码
修复后代码
import asyncio import datetime import discord from discord.ext import commands # 此处省略你的client初始化代码 @client.command() async def remindersec(ctx, seconds=None): try: seconds_int = int(seconds) embed = discord.Embed( title = f"I will remind you in {seconds_int} seconds", description = f"You'll be DMed as a reminder.", color = 0xf461ff ) now = datetime.datetime.now() current_time = now.strftime("%H:%M") embed.set_footer(text=f"Requested by {ctx.author} at {current_time}") await ctx.send(embed=embed) # 直接异步休眠对应秒数即可,不需要逐秒循环减计数 await asyncio.sleep(seconds_int) await ctx.author.send("Reminder!") except (ValueError, TypeError): embed = discord.Embed( title = "Error!", description = f"Please type a valid number.", color = 0xf461ff ) now = datetime.datetime.now() current_time = now.strftime("%H:%M") embed.set_footer(text=f"Requested by {ctx.author} at {current_time}") await ctx.send(embed=embed)
内容的提问来源于stack exchange,提问作者OffableGamer870
相关产品推荐
相关产品推荐

