Discord提醒机器人用time.sleep阻塞无法同时处理多用户请求如何解决
问题解决方案
核心原因
discord.py 是基于 asyncio 实现的异步框架,你当前使用的 time.sleep() 属于同步阻塞函数,调用时会直接卡住整个异步事件循环,导致所有后续的用户请求、事件都无法被处理,必须等sleep执行完成才能恢复响应,这就是多用户无法同时设置提醒的根源。
修复方案
只需要两步修改即可解决阻塞问题,实现多请求并行处理:
- 引入 asyncio 依赖库
- 将所有
time.sleep()替换为异步非阻塞的await asyncio.sleep()
修改后的完整代码
# bot 2 import os import discord import time import asyncio from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN2') client = discord.Client() @client.event async def on_ready(): print( f'{client.user} has connected to Discord!') @client.event async def on_message(message): if message.author == client.user: return remind_me = 'You will be reminded ' if 'remindme!' in message.content.lower(): if message.content[-1] == 'h' or \ message.content[-1] == 's' or\ message.content[-1] == 'm': response = remind_me + '\'' + message.content[10:-3] + '\' in' + message.content[-3::] await message.channel.send(response) else: await message.channel.send('I don\'t understand.') if message.content[-1] == 'h': await asyncio.sleep(3600 * int(message.content[-2])) await message.author.send('Reminder! \n' + message.content[10:-3]) if message.content[-1] == 's': await asyncio.sleep(int(message.content[-2])) await message.author.send('Reminder! \n' + message.content[10:-3]) if message.content[-1] == 'm': await asyncio.sleep(int(message.content[-2])*60) await message.author.send('Reminder! \n' + message.content[10:-3]) client.run(TOKEN)
内容的提问来源于stack exchange,提问作者AThomspon
相关产品推荐
相关产品推荐

