Discord.js not playing sound

29 views Asked by At

I have been trying all day to write a simple bit of code that makes a Discord Bot join a channel and then play a sound. But for some reason I can't seem to get it to work. I have tried many different things but it just doens't play the sound. I also get no error or anything. Could somebody explain to me what I am doing wrong? The code can be found below.

const Discord = require("discord.js");
const discordTTS = require('discord-tts');
const { Client, GatewayIntentBits } = require('discord.js');
const { joinVoiceChannel } = require('@discordjs/voice');
const { createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice');
const { createAudioResource } = require('@discordjs/voice');
const { join } = require('node:path');
const { AudioPlayerStatus } = require('@discordjs/voice');
const path = require('path');

const player = createAudioPlayer({
  behaviors: {
    noSubscriber: NoSubscriberBehavior.Pause,
  },
});

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

client.on('ready', (c) => {
  console.log(c.user.tag + " is online!");
});

client.on('messageCreate', (message) => {
  if (message.content === 'hello') {
    const connection = joinVoiceChannel({
      channelId: message.member.voice.channel.id,
      guildId: message.member.voice.guild.id,
      adapterCreator: message.member.voice.guild.voiceAdapterCreator,
      selfDeaf: false,
    });
    const player = createAudioPlayer();
    connection.subscribe(player);
    resource = createAudioResource(path.join(__dirname, 'sounds', 'alert.mp3'));
    player.play(resource);
  }
});

It joins the channel fine but then doens't play the sound. I double checked and the file (alert.mp3) is in the sounds folder.

1

There are 1 answers

4
jepozdemir On BEST ANSWER

You may missing some intents such as 'GuildVoiceStates':

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildVoiceStates,
  ],
});

Also it's better to set absolute path to the resource.

const path = require('path');
...

resource = createAudioResource(path.join(__dirname, 'sounds', 'alert.mp3'));