You need to enable JavaScript to run this app. 如何用discord.py实现频道无消息指定时长后自动提醒且持续监控
优惠活动
大模型
产品
解决方案
定价
更多

如何用discord.py实现频道无消息指定时长后自动提醒且持续监控

Discord 频道静默监控命令实现方案

你原有代码的问题是仅执行单次检查逻辑,无循环持续监控机制,且sleep过程中不会更新最新消息状态,因此无法实现持续监控效果。

以下是可实现不间断监控的完整代码:

import asyncio
from datetime import datetime, timedelta

# 全局变量记录是否已经发送过提醒,避免重复推送
reminded = False
# 要监控的目标频道ID
WATCHED_CHANNEL_ID = 替换为你要监控的频道ID
# 告警推送的频道ID
ALERT_CHANNEL_ID = 816741369682985012
# 要@的用户ID
ALERT_USER_ID = 400349192125415436

@client.command()
async def watch(ctx, time: int):
    global reminded
    # 输入的time单位为分钟,转换为时间间隔阈值
    threshold = timedelta(minutes=time)
    watched_channel = client.get_channel(WATCHED_CHANNEL_ID)
    alert_channel = client.get_channel(ALERT_CHANNEL_ID)
    
    if not watched_channel or not alert_channel:
        await ctx.send("频道ID配置错误,请检查")
        return
    
    await ctx.send(f"已启动监控,{watched_channel.mention} 若{time}分钟无新消息将自动告警")
    
    while True:
        # 获取频道最新一条消息
        last_msg = None
        async for msg in watched_channel.history(limit=1):
            last_msg = msg
        
        if not last_msg:
            # 频道无历史消息的特殊情况处理
            if not reminded:
                await alert_channel.send(f"<@{ALERT_USER_ID}> 监控频道无任何历史消息")
                reminded = True
        else:
            # 计算当前时间与最后一条消息发送时间的差值
            time_since_last = datetime.utcnow() - last_msg.created_at
            if time_since_last > threshold:
                if not reminded:
                    await alert_channel.send(f"<@{ALERT_USER_ID}> {watched_channel.mention} 已经{time}分钟没有新消息了,bot可能出现异常")
                    reminded = True
            else:
                # 检测到新消息,重置提醒标记
                reminded = False
        
        # 每1分钟检查一次,可根据需求调整间隔,不要设置过短避免触发Discord API速率限制
        await asyncio.sleep(60)

核心特性

  • 启动命令后进入无限循环持续监控,不会自动终止
  • 有新消息时自动重置提醒状态,仅在超过设定阈值无新消息时触发告警
  • 新增重复提醒拦截逻辑,同一次静默状态只会推送一次告警,不会出现刷屏问题

可选优化点

  • 可新增停止命令终止监控,无需重启bot即可关停监控任务
  • 如需多频道同时监控,可将配置变量改为字典结构,存储不同频道的阈值和告警状态即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 14:06:03