Discord.py调用channel.send前检测频道慢模式冷却剩余时长避免阻塞
解决方案
方案1:提前查询冷却剩余时长,提前判断是否可发送
discord.py的TextChannel对象自带slowmode_delay属性,返回当前频道设置的慢模式冷却秒数,返回0则代表当前频道未开启慢模式。
你只需要额外维护一个字典,记录每个频道上次成功发送消息的时间戳,即可计算出剩余冷却时长:
import time import asyncio # 用于存储每个频道上次发送消息的时间戳,key为频道ID last_send_record = {} for l_channel in this.channels: channel_slowmode = l_channel.slowmode_delay # 未开启慢模式直接跳过冷却判断 if channel_slowmode == 0: await l_channel.send(l_msg.text) last_send_record[l_channel.id] = time.time() await asyncio.sleep(2) continue current_time = time.time() last_send_time = last_send_record.get(l_channel.id, 0) remaining_cd = channel_slowmode - (current_time - last_send_time) if remaining_cd <= 0: await l_channel.send(l_msg.text) last_send_record[l_channel.id] = time.time() else: # 此处可根据需求选择等待remaining_cd秒后发送,或直接跳过本次发送 print(f"频道{l_channel.name}仍有{remaining_cd:.1f}秒慢模式冷却,本次跳过发送") await asyncio.sleep(2)
如果你的机器人拥有管理频道或豁免慢模式权限,慢模式限制对机器人不生效,可以直接发送无需判断。
方案2:无需提前判断,调用时避免阻塞
如果不想自行维护发送时间记录,可以在调用send方法时传入wait=False参数,此时遇到慢模式冷却不会阻塞等待,会直接抛出SlowModeError异常,你可以捕获该异常拿到剩余冷却时长:
import asyncio from discord.errors import SlowModeError for l_channel in this.channels: try: await l_channel.send(l_msg.text, wait=False) except SlowModeError as e: # e.retry_after即为剩余冷却秒数 print(f"频道冷却中,剩余{e.retry_after:.1f}秒,跳过本次发送") await asyncio.sleep(2)
内容的提问来源于stack exchange,提问作者David Hožič
相关产品推荐
相关产品推荐

