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

如何实现Discord Bot仅当用户离开语音频道超5分钟后再加入时推送通知

实现方案

核心思路是通过全局字典存储用户ID对应的上次离开语音频道的时间戳,用户加入频道时判断时间间隔是否大于5分钟,满足条件才推送通知。

  • 首先导入时间处理依赖,初始化存储结构与冷却阈值:
from datetime import datetime, timedelta
# 存储格式:{用户ID: 上次离开频道的时间对象}
user_last_leave_time = {}
# 配置冷却时间为5分钟
COOLDOWN_MINUTES = 5
  • 调整on_voice_state_update事件逻辑,新增离开时间记录、冷却判断逻辑,同时优化原重复的代码块:
@client.event
async def on_voice_state_update(member, before, after):
    # 处理用户离开频道逻辑,记录离开时间
    if before.channel != after.channel and before.channel is not None:
        if before.channel.id in [int(VOICE_CHANNEL_ID1), int(VOICE_CHANNEL_ID2)]:
            user_last_leave_time[member.id] = datetime.now()
    
    # 处理用户加入频道逻辑
    if before.channel != after.channel and after.channel is not None:
        channel_id = after.channel.id
        # 非目标监听频道直接跳过
        if channel_id not in [int(VOICE_CHANNEL_ID1), int(VOICE_CHANNEL_ID2)]:
            return
        
        # 冷却时间判断
        now = datetime.now()
        last_leave = user_last_leave_time.get(member.id)
        # 无离开记录或距离上次离开超过5分钟才推送通知
        if last_leave is None or (now - last_leave) > timedelta(minutes=COOLDOWN_MINUTES):
            _name = member.nick if member.nick else member.name
            if channel_id == int(VOICE_CHANNEL_ID1):
                msg_content = f"\n{_name} Join The Livestream Channel"
            else:
                msg_content = f"\n{_name} Join The Nongskuy Channel"
            
            message = {"message": msg_content}
            requests.post(LINE_NOTIFY_API_URL, headers=HEADERS, data=message)

client.run(DISCORD_BOT_ACCESS_TOKEN)

补充说明:如果担心Bot重启后内存字典数据丢失导致冷却失效,可将用户离开时间存储到本地JSON文件或SQLite轻量数据库中,上述内存存储方案已可覆盖绝大多数日常使用场景。另外建议将同步的requests请求替换为异步的aiohttp请求,避免阻塞Discord Bot的事件循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:24:08