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

Discord机器人messageCreate事件问题:获取消息发送者及模糊匹配删消息

问题修复方案

问题1:日志显示“Deleted message from undefined”

你写的msg.author.username.tag是错误的——username是字符串类型,根本没有tag属性。正确的写法是直接调用msg.author.tag,它会返回用户的「用户名#四位标识」格式,比如JohnDoe#1234。

另外也可以直接用事件回调里的message.author.tag,不用等delete()的返回结果,效果完全一致。

问题2:仅匹配严格等于违禁词的消息

原代码里message.content == badword是把字符串和数组直接做相等判断,这永远不会成立。要实现「包含任意违禁词就删除」的逻辑,用数组的some()方法遍历违禁词,再用includes()检查消息内容是否包含当前词:

badword.some(word => message.content.includes(word))

完整修复后的代码

const badword = ['test'] // 建议用const声明变量,避免全局污染

client.on('messageCreate', (message) => {
    // 检查消息内容是否包含任意违禁词
    if (badword.some(word => message.content.includes(word))){
        message.delete() // delete方法不需要传message参数
        .then(msg => console.log(`Deleted message from ${msg.author.tag}`))
        .catch(console.error);
    }
})

额外提示:如果需要不区分大小写的匹配,可以把消息内容和违禁词都转成小写:

badword.some(word => message.content.toLowerCase().includes(word.toLowerCase()))

内容的提问来源于stack exchange,提问作者Its the lag

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:35:25