首页 > 解决方案 > Discord 机器人不回复消息

问题描述

我一直在尝试设置一个不和谐的机器人,通过遵循文档,我能够设置一个斜杠命令,但无法让机器人回复服务器上的消息。

这是我用来从docs设置斜杠命令的代码。

const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');

const commands = [{
  name: 'ping',
  description: 'Replies with Pong!'
}]; 

const rest = new REST({ version: '9' }).setToken('token');

(async () => {
  try {
    console.log('Started refreshing application (/) commands.');

    await rest.put(
      Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
      { body: commands },
    );

    console.log('Successfully reloaded application (/) commands.');
  } catch (error) {
    console.error(error);
  }
})();

在此之后,我使用以下代码设置了机器人:

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });


client.once('ready', () => {
    console.log('Ready!');
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('interactionCreate', async interaction => {
    // console.log(interaction)
    if (!interaction.isCommand()) return;

    if (interaction.commandName === 'ping') {
        await interaction.reply('Pong!');
        // await interaction.reply(client.user + '');
    }
});

client.login('BOT_TOKEN');

现在我可以得到 Pong 的响应了!当我说 /ping 时。

回复图片

但是在我从这个链接添加以下代码后,我没有得到机器人的任何响应。

client.on('message', msg => {
  if (msg.isMentioned(client.user)) {
    msg.reply('pong');
  }
});

我希望机器人回复消息而不仅仅是斜线命令。有人可以帮忙吗。谢谢!!

标签: javascriptdiscorddiscord.jsreply

解决方案


首先,您缺少接收事件的GUILD_MESSAGES意图。messageCreate

const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });

其次,该message事件已被弃用,请messageCreate改用。

client.on("messageCreate", (message) => {
    if (message.mentions.has(client.user)) {
        message.reply("Pong!");
    }
});

最后,Message.isMentioned()是 no logner 一个函数,它来自 discord.js v11。用于MessageMentions.has()检查消息中是否提及用户。

在此处输入图像描述

使用 discord.js 测试^13.0.1


推荐阅读