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

如何让Discord机器人延迟5秒读取消息且仅处理单条消息?

解决Discord机器人消息冷却问题

你的核心问题是用了同步的time.sleep(5)阻塞了事件循环,导致所有消息都被缓存等待处理,而非忽略冷却期内的新消息。下面是修复方案:

关键修改点

  • 用异步的asyncio.sleep()替代time.sleep(),避免阻塞整个机器人的事件循环
  • 添加冷却跟踪机制,记录最后一次处理消息的时间,过滤冷却期内的新消息

修复后的代码(单用户冷却)

import asyncio
from datetime import datetime

# 存储每个用户的最后消息处理时间,键为用户ID,值为datetime对象
user_cooldowns = {}

@bot.event
async def on_message(message):
    # 忽略机器人自身消息和以!!开头的命令
    if message.author.id == bot.user.id or message.content.startswith("!!"):
        return
    if not message.content:
        return
    
    # 检查当前用户是否在5秒冷却期内
    current_time = datetime.now()
    last_processed = user_cooldowns.get(message.author.id)
    if last_processed and (current_time - last_processed).total_seconds() < 5:
        return  # 冷却期内,直接忽略这条消息
    
    # 更新该用户的冷却时间
    user_cooldowns[message.author.id] = current_time
    
    # 延迟5秒后发送回复
    await asyncio.sleep(5)
    await message.channel.send(message.content)

代码说明

  1. 冷却跟踪字典:user_cooldowns记录每个用户最后一次处理消息的时间,确保同一用户5秒内只能触发一次回复
  2. 异步延迟:asyncio.sleep(5)不会阻塞事件循环,机器人在等待期间可正常处理其他事件(仅过滤冷却期内的目标消息)
  3. 冷却判断:通过计算当前时间与上次处理时间的差值,决定是否允许处理新消息

如果需要全局冷却(所有用户5秒内只能触发一次回复),只需把冷却跟踪改成全局变量即可:

import asyncio
from datetime import datetime

global_cooldown = None
COOLDOWN_DURATION = 5

@bot.event
async def on_message(message):
    if message.author.id == bot.user.id or message.content.startswith("!!"):
        return
    if not message.content:
        return
    
    current_time = datetime.now()
    global global_cooldown
    if global_cooldown and (current_time - global_cooldown).total_seconds() < COOLDOWN_DURATION:
        return
    
    global_cooldown = current_time
    await asyncio.sleep(5)
    await message.channel.send(message.content)

内容的提问来源于stack exchange,提问作者Duc Huy Nguyen Tran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:55:18