Search code examples
javascriptnode.jsdiscorddiscord.js

Discord bot doesn't answer commands


I create a Discord bot using node.js. When I type node . or node main.js, my code is running without error and switches to online status in discord correctly, but the bot doesn't answer my commands. Bot has an administrator role on the server and all permissions.

My main code here:

const { Client, Intents, DiscordAPIError } = require('discord.js');
const { token } = require('./config.json');
Discord = require("discord.js")
const client = new Client({ intents: [32767]});

const prefix = '!';

const fs = require('fs');

client.commands = new Discord.Collection();

const commandFile = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));

for(const file of commandFile) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

client.once('ready', () => {
    console.log('Ready!');
})

client.on('messageCreate', message => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;
    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping') {
        client.commands.get('ping').execute(message,args);
    }
});

client.login(token);

And code my ping.js from /commands/ here:

module.exports = {
    name: 'ping',
    description: "this is a ping command",
    execute(message, args) {
        message.channel.send('pong');
    }
}

Solution

  • With your current intent 32767 the following ones are enabled:

    • GUILDS (1 << 0)
    • GUILD_MEMBERS (1 << 1)
    • GUILD_BANS (1 << 2)
    • GUILD_EMOJIS_AND_STICKERS (1 << 3)
    • GUILD_INTEGRATIONS (1 << 4)
    • GUILD_WEBHOOKS (1 << 5)
    • GUILD_INVITES (1 << 6)
    • GUILD_VOICE_STATES (1 << 7)
    • GUILD_PRESENCES (1 << 8)
    • GUILD_MESSAGES (1 << 9)
    • GUILD_MESSAGE_REACTIONS (1 << 10)
    • GUILD_MESSAGE_TYPING (1 << 11)
    • DIRECT_MESSAGES (1 << 12)
    • DIRECT_MESSAGE_REACTIONS (1 << 13)
    • DIRECT_MESSAGE_TYPING (1 << 14)

    The problem is you've added lots of unnecessary ones but missing the MESSAGE_CONTENT intent. It means message.content doesn't have any value.

    To solve this, you can add 32768 (1 << 15) to the current number:

    const client = new Client({
      intents: [65535],
    });
    

    or even better, just use the ones you actually need:

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