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

如何避免Discord频道慢模式下channel.send函数阻塞?

解决Discord频道慢模式发送阻塞的检测方法

有两种实用方式可以提前检测慢模式状态,避免channel.send()阻塞:

1. 主动检测用户剩余冷却时间

Discord的慢模式是针对用户的,每个用户在频道发送消息后会有专属冷却期。你可以通过频道的权限覆盖属性获取用户实际生效的慢模式时长,再结合上次发送时间计算剩余冷却:

import time
from discord import TextChannel

def can_send(channel: TextChannel, user, last_send_records: dict) -> bool:
    # 获取用户在该频道的实际慢模式时长(含角色/用户专属覆盖)
    effective_slowmode = channel._get_overwrites_for(user).slowmode_delay
    if effective_slowmode == 0:
        return True
    # 读取用户上次在该频道的发送时间,默认0
    last_send_time = last_send_records.get((channel.id, user.id), 0)
    # 计算剩余冷却时间
    remaining_cooldown = effective_slowmode - (time.time() - last_send_time)
    return remaining_cooldown <= 0

# 使用示例
send_records = {}
if channel.id in channelID:
    if can_send(channel, ctx.author, send_records):
        await channel.send(msg)
        # 更新发送时间记录
        send_records[(channel.id, ctx.author.id)] = time.time()
    else:
        # 冷却中时的处理逻辑,比如提示用户
        await ctx.send(f"该频道慢模式冷却中,请等待{int(remaining_cooldown)}秒后再发送")

2. 捕获异常实现非阻塞处理

如果不想维护发送时间记录,也可以直接捕获慢模式对应的异常,避免任务阻塞:

Discord.py中,慢模式冷却未结束时会抛出HTTPException,错误状态码为429。你可以捕获这个异常并处理:

from discord import HTTPException

try:
    await channel.send(msg)
except HTTPException as e:
    if e.status == 429:
        # 从响应头提取剩余冷却时间
        retry_after = e.response.headers.get('Retry-After', 0)
        print(f"慢模式冷却中,需等待{int(retry_after)}秒")
        # 这里可以添加自定义逻辑,比如延迟重试或提示用户
    else:
        # 处理其他HTTP错误
        raise

这个方法属于事后处理,但不会阻塞整个任务流程,适合不想维护状态的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:48:18