javascriptdiscorddiscord.jsreply

Discord bot is not replying to messages


I have been trying to set up a discord bot and by following the docs, I have been able to set up a slash command but have not been able to get the bot to reply to messages on the server.

Here is the code I used to set up slash command from 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);
  }
})();

After this I set up the bot with this code:

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');

Now I am able to get a response of Pong! when I say /ping.

reply image

But after I added the following code from this link I didn't get any response from the bot.

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

I want the bot to reply to messages not just slash commands. Can someone help with this. Thanks!!🙂


Solution

  • First of all you are missing GUILD_MESSAGES intent to receive messageCreate event.

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

    Secondly the message event is deprecated, use messageCreate instead.

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

    At last, Message.isMentioned() is no logner a function, it comes from discord.js v11. Use MessageMentions.has() to check if a user is mentioned in the message.

    enter image description here

    Tested using discord.js ^13.0.1.