Search code examples
javascriptnode.jsdiscorddiscord.js

Discord bot doesn't execute commands


I'm trying to create a bot that plays music, can ban and kick people, and shows the number of members and online numbers on the server.

I tried my best but it didn't write anything even when I wrote "hi" to test it.

Can you help me with this?

const { Discord ,Client, Intents, MessageEmbed } = require('discord.js');
const { createAudioResource, createAudioPlayer, joinVoiceChannel, StreamType, AudioPlayerStatus } = require('@discordjs/voice');
const ytdl = require('ytdl-core-discord');
const SpotifyWebApi = require('spotify-web-api-node');
const client = new Client({ intents: [32509] });
require('dotenv').config();
const { TOKEN, ID, SECRET } = process.env;

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

const spotifyApi = new SpotifyWebApi({
  clientId: ID,
  clientSecret: SECRET,
});

client.on('message', msg => {
  if (msg.content === 'hi') {
    msg.reply('hi, how are you?');
  }
});

client.on('message', message => {
    if (!message.guild) return;
  
    if (message.content.startsWith('!kick')) {
      const user = message.mentions.users.first();
      if (user) {
        const member = message.guild.member(user);
        if (member) {
          member.kick('Information is in logs').then(() => {
            message.reply(`${user.tag} kicked`);
          }).catch(err => {
            message.reply('Kick was not successful!');
            console.error(err);
          });
        } else {
          message.reply("User is not in this server");
        }
      } else {
        message.reply("You must specify a user to kick");
      }
    }
  
    if (message.content.startsWith('!ban')) {
      const user = message.mentions.users.first();
      if (user) {
        const member = message.guild.member(user);
        if (member) {
          member.ban({
            reason: 'Information is in logs',
          }).then(() => {
            message.reply(`${user.tag} banned`);
          }).catch(err => {
            message.reply('Ban was not successful!');
            console.error(err);
          });
        } else {
          message.reply("User is not in this server");
        }
      } else {
        message.reply("You must specify a user to ban");
      }
    }
  });

  client.on('messageCreate', async message => {
    if (!message.content.startsWith('!')) return;
  
    const args = message.content.slice(1).trim().split(' ');
    const command = args.shift().toLowerCase();
  
    if (command === 'play') {
      if (!message.member.voice.channel) {
        message.reply('Please join a voice chat');
        return;
      }
  
      const connection = joinVoiceChannel({
        channelId: message.member.voice.channel.id,
        guildId: message.guild.id,
        adapterCreator: message.guild.voiceAdapterCreator,
      });
  
      const link = args[0];
      if (!link) {
        message.reply('Please enter a YouTube or Spotify link.');
        return;
      }
  
      if (!link.includes('youtube.com') && !link.includes('youtu.be') && !link.includes('spotify.com')) {
        message.reply('Please enter a valid YouTube or Spotify link.');
        return;
      }
  
      try {
        if (link.includes('spotify.com')) {
          const id = link.split('/').pop().split('?')[0];
          const data = await spotifyApi.clientCredentialsGrant();
          const token = data.body['access_token'];
          spotifyApi.setAccessToken(token);
          const track = await spotifyApi.getTrack(id);
          const stream = await ytdl(track.body.preview_url, { filter: 'audioonly' });
          const resource = createAudioResource(stream, { inputType: StreamType.Opus });
          const player = createAudioPlayer();
          connection.subscribe(player);
          player.play(resource);
          player.on(AudioPlayerStatus.Idle, () => {
            connection.destroy();
          });
          message.reply(`The song called \`${track.body.name}\` is playing...`);
        } else if (link.includes('youtube.com') || link.includes('youtu.be')) {
          const stream = await ytdl(link, { filter: 'audioonly' });
          const resource = createAudioResource(stream, { inputType: StreamType.Opus });
          const player = createAudioPlayer();
          connection.subscribe(player);
          player.play(resource);
          player.on(AudioPlayerStatus.Idle, () => {
            connection.destroy();
          });
          const info = await ytdl.getBasicInfo(link);
          message.reply(`The video called\`${info.videoDetails.title}\` is playing...`);
        }
      } catch (error) {
        console.error(error);
        message.reply('An error occured.');
      }
    }
  });

  client.on('voiceStateUpdate', async (oldState, newState) => {
    if (!oldState.channel && newState.channel) {
      const guild = newState.guild;
      const voiceChannel = guild.channels.cache.find(channel => channel.name.includes('Members: '));
      if (voiceChannel) {
        const memberCount = guild.members.cache.filter(member => !member.user.bot).size;
        const onlineCount = guild.members.cache.filter(member => !member.user.bot && member.presence?.status === 'online').size;
        voiceChannel.setName(`Members: ${memberCount} (${onlineCount} online)`);
      }
    }
  });

client.login(TOKEN);

When I tried to log in as bot there is no problem. it says its logged in.

But when i try any of these commands bot doesn't do anything.

Even I get no errors in terminal.


Solution

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

    • GUILDS (1 << 0)
    • 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_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 unnecessary ones but missing the MESSAGE_CONTENT intent. It means message.content doesn't have any value. Also, make sure you enable the necessary intents on the developer portal (see the linked answer).

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

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

    You should also replace client.on('message' with client.on('messageCreate' and make sure you only have one event listener.