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

Discord.js中awaitMessages配置filter后未触发.then回调问题排查

问题解决方案

核心原因排查

  • 版本API不匹配:discord.js v13及以上版本调整了awaitMessages的传参规则,旧版v12的传参逻辑不再适用,这是最常见的触发原因。
    v12写法是第一个参数传filter函数,第二个传配置对象;v13+改为仅接收一个配置对象,filter作为配置对象的属性传入,按旧写法调用会直接导致消息监听不生效。
  • 缺少必要权限与意图:
    • 代码中初始化Client时未声明MessageContent、DirectMessages(私信场景必须)等必要意图,机器人无法读取消息内容。
    • Discord开发者后台的机器人设置页未开启Message Content Intent开关,导致消息读取权限被官方拦截。
    • 私信场景下用户关闭了陌生人私信权限,机器人无法接收用户的消息回复。
  • filter逻辑异常:可以在filter中增加日志打印,确认是否有消息流入、ID匹配是否正确,排除client.user.id未正确获取的问题。
  • 二级回调参数错误:原有代码第二层awaitMessages的then回调中直接调用replymsg.content,而awaitMessages返回的是消息集合,需要先调用.first()取到实际消息对象才能读取内容。

修复后的代码示例

1. 初始化Client时补充必要意图(v14版本示例)

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.MessageContent
  ]
});

2. 调整awaitMessages传参格式(v13+版本适用)

// filter中加日志可确认消息流入情况
const filter = m => {
    console.log('收到消息:发送者ID', m.author.id, '机器人ID', client.user.id);
    return m.author.id !== client.user.id;
};
channel.awaitMessages({
    filter,
    max: 1,
    time: 1000 * 180,
    errors: ['time']
})
.then(msg => {
    console.log("got to the then");
    const replymsgobject = msg.first();
    const reply = replymsgobject.content;
    const checkstringarr = [
        "payment",
        "about",
        "team",
        "requirements"
    ];
    if (contains("or", reply, checkstringarr)) {
        channel.send(`Your post doesn't follow the format.`);
    } else {
        channel.send(`succesfully set your post message, would you like to add any extra comments?`);
        const secondFilter = m => m.author.id !== client.user.id;
        channel.awaitMessages({
            filter: secondFilter,
            max: 1,
            time: 1000 * 120,
            errors: ['time']
        })
        .then(replymsg => {
            // 先取集合第一条消息再读内容
            const replyContent = replymsg.first().content;
            if (contains("only", replyContent, "no")) {
                // 原有业务逻辑
            } else {
                // 原有业务逻辑
            }
        })
        .catch(() => {
            channel.send(`timed out`);
        });
    }
})
.catch(() => {
    channel.send(`timed out`);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:18:00