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

DJS V13 使用message.mentions获取提及用户出现长延迟问题求助

DJS V13 提及用户响应延迟修复方案

问题根因

  • 错误对同步方法添加await等待:message.mentions.members.first()是从本地缓存直接取数的同步方法,额外加await会强制包装为Promise等待,凭空增加延迟
  • 相等判断写成赋值:if (args[0] = "add")错误使用赋值运算符=,会强制覆盖args[0]的值为add,导致逻辑紊乱
  • 作用域与逻辑错误:remove分支未读取json文件就调用未定义的bypass变量,会抛出引用错误阻塞进程,且remove逻辑写成了追加ID而非删除,完全不符合需求
  • 同步IO阻塞事件循环:使用fs.readFileSync同步读取文件会阻塞整个Node.js事件循环,磁盘IO较慢时直接表现为机器人响应延迟

修复后的代码

const fs = require('fs/promises') // 改用Promise版本的fs模块,避免同步IO阻塞

// 去掉多余的await
const member = message.mentions.members.first()
if (!member) return message.channel.send({ content: "You did not mention a member or that member does not exist." })

// 提前读文件,避免重复IO操作
const bypass = JSON.parse(await fs.readFile("./bypass.json", "utf-8"))
const targetId = member.id

if (args[0] === "add") {
    // 新增重复ID判断,避免数组冗余
    if (!bypass.includes(targetId)) {
        bypass.push(targetId)
    }
    await fs.writeFile('./bypass.json', JSON.stringify(bypass, null, 4))
    return message.channel.send({ content: `Added sus to the bypass list!` })
}

if (args[0] === 'remove') {
    // 过滤移除目标ID,修正删除逻辑
    const newBypass = bypass.filter(id => id !== targetId)
    await fs.writeFile('./bypass.json', JSON.stringify(newBypass, null, 4))
    return message.channel.send({ content: `Removed sus from the bypass list!` })
}

额外优化建议

  • 如果bypass.json的读写频率很高,建议将数据缓存到内存中,定时持久化到磁盘,避免频繁读写文件
  • 确认机器人已开启成员缓存相关的Gateway意图,确保提及成员数据提前缓存到本地,不会出现需要额外远程拉取的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:57:00