#archive-voice

30636 messages · Page 22 of 31

winged plover

The error will occur if I try to use the joinVoiceChannel method that I importec from the d.js voice module; The resource is available, I've confirmed that too

I tried it on my Windows 10 machine, and my CentOS 8 Stream VM, both on Node 16.6.1; Same error on both

I'm 95% sure this is an issue with the library itself

rugged sky

I'm not sure about the specific error that you're getting, but it seems like it's getting some bad inputs from misc errors in your code of which I can see a few.

First of all, you don't create an AudioPlayer like so new AudioPlayer(), use the method createAudioPlayer() from the @discordjs/voice package.

Additionally, your joinVoiceChannel() method parameter must include an adapterCreator property like so:

const connection = joinVoiceChannel({
    channelId: channelId,
    guildId: guildId,
    adapterCreator: <Guild>.voiceAdapterCreator,
    selfDeaf: true,
})

The next problem your code probably doesn't even reach yet, but you'll run into it. You cannot parse a link as a resource to play into the <AudioPlayer>.play() method. You must first create an AudioResource using the createAudioResource() method once again from the @discordjs/voice package. This method doesn't take a URL either so you will have to find a way to turn the resource into a readable stream first using potentially another package, but I can't help you much on that front since I've only used packages that do it for youtube.

@winged plover

winged plover

It could be the adapterCreator I am missing, I did not realise that was required 🤦‍♂️

As for the audioplayer, I don't see why I couldn't just create the player (see here https://discord.js.org/#/docs/voice/stable/class/AudioPlayer)
I was taking a look at the AudioResource docs and it mentioned streams, It's been ages since I had used D.js and before it accepted a URL that was outputting an audio stream, so I figured it would do the same now - thanks! I'll try a few things here with that info

rugged sky
winged plover

You're all good! I appreciate the help

rugged sky

No problem, good luck!

winged plover

Ended up figuring it out - for anyone who searches for this, you'll need the adapterCreator- easy as pie - without it, there's that bizzare error; It isn't very well documented, so personally I just passed in the voiceAdapterCreator function from the message.member.voice object

Thanks again!

sudden hawk

Guys I want to do that if the member's voice channel id is not the bot's voice channel id it just returns,
I already tried to do it, but the problem is that when the bot is not in a voice channel it obviously fails and crashes because it can't read the voice channel id, how can I make that if the bot is not in a voice channel it just executes the play command but if the bot is in a voice channel it checks if the bot's voice channel id is the user's voice channel id?

twilit lion
carmine timber
fleet glen

is there any way to see who is watching the stream? have been trying to see if i can find any function to check for it

it worked :D

teal nymph

👍

sudden hawk

I just don't want that people can control the bot's player in another voice channel (obviously different from the bot's voice channel)

wintry steeple

Guys, how do I mute all the members in the same voice channel as the message author? Tried doing this:

let channel = message.guild.channels.cache.get(message.member.voice.channel.id);
    for (const [memberID, member] of channel.members) {
    member.voice.setMute(true);
}

But i'm getting an error:

        let channel = message.guild.channels.cache.get(message.member.voice.channel.id);
                                                                                    ^   

TypeError: Cannot read properties of null (reading 'id')
whole flare

You need to make sure that your audio resource is a playable audio resource. For example you wouldn't be able to play a YouTube video with the default url, in this case you would need the url of the resource of the audio

subtle granite
pseudo forum
const Discord = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice');

module.exports = {
    name : 'play',
    args: true,
    /**
     * 
     * @param {Discord.Message} message 
     * @param {Array<string>} args 
     */
    async execute(message, args) {
        const channel = message.member.voice.channel;

        if (!channel) return message.reply(`Vous devez tout d'abord de rejoindre un salon vocal !`)

        const connection = joinVoiceChannel({
            channelId: channel.id,
            guildId: channel.guild.id,
            adapterCreator: channel.guild.voiceAdapterCreator,
        });

        const player = createAudioPlayer();
        const ressource = createAudioResource(args[0]);

        player.play(ressource);
        connection.subscribe(player);

        player.on(AudioPlayerStatus.Idle, () => connection.destroy());

        player.on('error', error => {
            console.error(error);
        });
    },
};

my bot joins the vc and immediatly leave it ._.

subtle granite

args[0] is not a valid audioresource

pseudo forum
main ferry

how can I make an audio player play a youtube video url?

rugged sky
main ferry
abstract saffron

I'm pretty new here with this version of djs, so can you guys guide me how to integrate my lavacord to the bot? it says that it's playing music in the variables but it's not actually playing it on discord

chrome summit

How can I find the total duration on an Audio Resource in discord.js/voice?

hoary kernel

anyone?

sudden hawk

Does somebody know how to make a playlist? I have more audio files and I want to play them when I type the play command

prime fossil
hoary kernel

no

forest stag

hi, i need i little help
my bot plays youtube videos on chat but there is one specific video that always crashes at 1:52 with aborted error
does anyone knows how to solve this?

main ferry

how can I lower the volume of my audio player

main ferry

whenever my bot is playing audio it sometimes just randomly disconnects

nvm, it doesn't disconnect, sometimes it just stops playing due to some "unhandled error"

smoky ore

I made music bot, but I have some errors.

First, I have reject Promise Error.

reject Promise {
  [
    {
      status: 'connecting',
      adapter: [Object],
      networking: [Networking]
    },
    { status: 'ready', adapter: [Object], networking: [Networking] }
  ]
} AbortError: The operation was aborted
    at abortListener (node:events:838:14)
    at EventTarget.<anonymous> (node:events:874:47)
    at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
    at EventTarget.dispatchEvent (node:internal/event_target:504:26)
    at abortSignal (node:internal/abort_controller:97:10)
    at AbortController.abort (node:internal/abort_controller:122:5)
    at Object.entersState (C:\Users\middl\Desktop\Litium\node_modules\@discordjs\voice\dist\util\entersState.js:20:56)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ABORT_ERR'
}

And Next, Reject Promise Again.

reject Promise { { ip: '121.###.##.###', port: 63202 } } Error: Cannot perform IP discovery - socket closed
    at Socket.<anonymous> (C:\Users\middl\Desktop\Litium\node_modules\@discordjs\voice\dist\networking\VoiceUDPSocket.js:120:52)
    at Object.onceWrapper (node:events:509:28)
    at Socket.emit (node:events:402:35)
    at socketCloseNT (node:dgram:755:8)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)

How can I fix it?

I can give source code if needed

lofty warren

my bot joins the voice channel, but it doesn't plays nothing and no error is logged in the console. what's happening?

const connection = joinVoiceChannel({
    channelId: interaction.member.voice.channelId,
    guildId: interaction.guildId,
    adapterCreator: interaction.guild.voiceAdapterCreator
});
const player = createAudioPlayer({
    behaviors: {
        noSubscriber: NoSubscriberBehavior.Pause
        }
});
const resource = createAudioResource('./audio.mp3');
player.play(resource);
connection.subscribe(player);
interaction.reply('playing :thumbsup:');```
plush kraken

new here but how do you make the bot join vc?

plush kraken
smoky ore

hm

plush kraken

help please? ^_^

plush kraken
lofty warren
lofty warren

ok, but what's the problem in there?

plush kraken

i've been following some old tutorials to make a simple yt-search and player bot

lofty warren

gimme a second

plush kraken

well first help would be to just have the bot join the vc

it can detect voice_state_updates in logs and even the channels the user is in.

lofty warren

i thought it was removed in v13

plush kraken

no idea, i was getting type errors all over the place.

i have a bot. but how do i make it join vc in the latest version?

dusty needleBOT

_ discordjs.guide results:
• Getting Started: Introduction

icy maple

Voice got a complete rewrite

plush kraken

yeah indeed

icy maple

There’s more sections in the guide that covers the rest of voice

lofty warren
plush kraken

look i have the ytd-search working fine. like i can ask the bot to search a song on yt and it'll return with a url

just need to have him join vc and stream it

icy maple

The voice guide covers that

lofty warren
icy maple

It’s not a simple find and replace fix

plush kraken

can i put my code here?

icy maple

What for?

plush kraken
const connection = joinVoiceChannel({
    channelId: message.member.voice.channel,
    guildId: message.guild.id,
    adapterCreator: message.guild.voiceAdapterCreator,
  });

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

  connection.subscribe(player);

but he still doesn't join the vc

icy maple

Did you enable the guide voice states intent in the client?

plush kraken
// Create a new client instance
const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.DIRECT_MESSAGES,
    Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
    Intents.FLAGS.DIRECT_MESSAGE_TYPING,
  ],
});

do you mean this?

okay i'll try with that. what's the intent for vc?

icy maple

GUILD_VOICE_STATES

smoky ore

I made music bot, but I have some errors.

First, I have reject Promise Error.

reject Promise {
  [
    {
      status: 'connecting',
      adapter: [Object],
      networking: [Networking]
    },
    { status: 'ready', adapter: [Object], networking: [Networking] }
  ]
} AbortError: The operation was aborted
    at abortListener (node:events:838:14)
    at EventTarget.<anonymous> (node:events:874:47)
    at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
    at EventTarget.dispatchEvent (node:internal/event_target:504:26)
    at abortSignal (node:internal/abort_controller:97:10)
    at AbortController.abort (node:internal/abort_controller:122:5)
    at Object.entersState (C:\Users\middl\Desktop\Litium\node_modules\@discordjs\voice\dist\util\entersState.js:20:56)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ABORT_ERR'
}

And Next, Reject Promise Again.

reject Promise { { ip: '121.###.##.###', port: 63202 } } Error: Cannot perform IP discovery - socket closed
    at Socket.<anonymous> (C:\Users\middl\Desktop\Litium\node_modules\@discordjs\voice\dist\networking\VoiceUDPSocket.js:120:52)
    at Object.onceWrapper (node:events:509:28)
    at Socket.emit (node:events:402:35)
    at socketCloseNT (node:dgram:755:8)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)

How can I fix it?

plush kraken
lofty warren ```joinVoiceChannel({ channelId: <VoiceChannel>.id, guildId: <Guild>.id...

uhh my bot still isn't joining vc, i'm passing these values joinVoiceChannel();

channelID: [#903034211757940757](/guild/222078108977594368/channel/903034211757940757/) // changed a bit here and there
guildID 909094138240172043
adapterCreator methods => {
      this.client.voice.adapters.set(this.id, methods);
      return {
        sendPayload: data => {
          if (this.shard.status !== Status.READY) return false;
          this.shard.send(data);
          return true;
        },
        destroy: () => {
          this.client.voice.adapters.delete(this.id);
        },
      };
    }
plush kraken
lavish idol

315 // 3.15 I want to get output like this how do I do it

uncut oriole

the sound from the url does not play, how to fix it?

rugged sky
uncut oriole

uh, i'm understood my error

thanks

plush kraken
rugged sky
plush kraken

Has anyone here tried converting YouTube urls to stream data and playing that as a resource file before?

crisp tangle
const voice = require('@discordjs/voice');
//...
const member_channel = message.member.voice.channel;
//...
if (!member_channel) {
    return message.channel.send('**You have to be in a voice channel to use this command**');
};
//...
const connection = voice.joinVoiceChannel({
    channelId: member_channel.id,
    guildId: member_channel.guild.id,
    adapterCreator: member_channel.guild.voiceAdapterCreator,
});
//...
connection.once(voice.VoiceConnectionStatus.Ready, () => {
    message.channel.send(`**Joined** \`${member_channel.name}\``);
    queue(connection);
    return;
});

Yesterday, joining worked perfectly. Today for some reason, the connection status of the bot is stuck on SIGNALLING indefinitely
note: I'm using GUILD_VOICE_STATES, so that shouldn't be the problem

(I've been printing the connection each second in the image below)

rugged sky
rugged sky
plush kraken

thanks!

rugged sky

np

winged plover

Alright, so I'm getting slightly annoyed with the lack of documentation for the voice lib- but I'll ask anyway; Is there a way to not use FFmpeg to play audio? I'd like to just pass in a readable stream and be done with it

But for some ungodly reason, no matter if I set the type in the options, it runs ffmpeg and reprocesses the data

And yes, it is already in an Opus encoded format

crisp tangle
plush kraken

line for making the bot leave a vc?

connection.unsubscribe(player); // something like this? 
crisp tangle
rugged sky
winged plover

I wasn't planning on using it no

Is there even a way to disable it?

The docs are setup in like, the most confusing way, it's legitimately infuriating

rugged sky
winged plover

Amazing, good

rugged sky
winged plover

Sure thing

Lemme give you the snippet that actually outputs the audio, 1 sec

rugged sky

Sure

winged plover

should also mention this.streamable is a Node PassThrough stream (readable & writable)

rugged sky
winged plover

You're good! I appreciate you taking a look

rugged sky

np

winged plover

I have a feeling it may be the PassThrough not being recognised as a readable stream, even though it is

plush kraken

how would you ask the bot to pause the currently playing music?
i'm thinking player.pause(resource) but do i have to re create the player and resource objects for this?

crisp tangle
plush kraken
crisp tangle

it won't pause if you don't have a reference to the player you want to pause (how exactly you bring the reference to your function is something I can't help you with)
it will error since it doesn't know what player is
player.unpause(); is indeed the way to unpause/resume the player

if the playing and pausing/resuming functions are in the same file you could just simply use a variable

plush kraken

right now i have a playCommand(title) function which makes the bot join a vc and start playing the music with that title (which it gets from youtube).

Now i want to create a separate function pauseCommand() which should pause the music that's playing inside playCommand() but of course since it's different from playCommand() i'll have to create the player objects for both separately correct?

crisp tangle

no, don't create 2 audio players
just declare a variable like var audioPlayer = null at the start, then in playCommand(title) when you start playing assign your player to the variable audioPlayer = (player here), then in pauseCommand() you have to check if audioPlayer even exists if (audioPlayer !== null) {} and then if it exists just pause audioPlayer.pause();

though this is basic javascript and doesn't really have much to do with discord.js so I would just look online on how to do stuff in javascript

plush kraken

oh wait can i do it like this? I.e have them both share a common player declared at the top of the file? 👀

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

async function playCommand() {};

function pauseCommand() {
  player.pause()
};

crisp tangle

yes that is simpler than my suggestion (I usually think too overcomplicated for these things, sorry)

plush kraken
crisp tangle

but I don't know if it will error if the player isn't currently playing any resource and you pause it
you should check what happens then

plush kraken

yup although i have to close and sleep in like 5 mins ;-;

uni tom

yo @crisp tangle MY MAN IT WORKS LIKE A CHARM!

crisp tangle

nice

plush kraken

EXACTLY LIKE HOW YOU'D THINK

thanks again bruh @crisp tangle

crisp tangle

no probs, done this before so I would be confused it didn't work for u

rugged sky
lofty warren

uhh... no

crisp tangle
lofty warren
lofty warren

well, this intent is not in documentation, but ok

rugged sky

Yeah, it's a bit obscure.

lofty warren

but it's necessary to get members' voice states? because i don't have that and i got a voice state from a member

so, what it does is getting the bot's voice state?

rugged sky
lofty warren

ok, let me try it

rugged sky

Yeah, it needs it's own connection state because otherwise it will always be 'signalling' even though it looks like it has joined.

Additionally, I don't think createAudioResource() takes relative paths. I'd make that absolute just in case.

lofty warren

it worked, thanks 👍

lofty warren

but why the functions aren't in the documentation? like joinVoiceChannel(), createAudioResource(), etc.

the documentation only shows how to do it with the constructors

rugged sky
crisp tangle

^ what Touché said
you have to switch from Main Library to Voice on the documentation site

lofty warren
lofty warren
rugged sky
rugged sky
crisp tangle

I found out when I had Voice and was searching for text channels but it didn't come up

lofty warren

but how do i use AudioResource constructor?

rugged sky
lofty warren
wide mirage

I suppose that the memory leak with inLineVolule hasn't be fixed yet and will never be fixed

rugged sky
wide mirage
crisp tangle

In v12 I used a StreamDispatcher to play music and I could use StreamDispatcher.streamTime/StreamDispatcher.totalStreamTime to get the time the dispatcher has been playing audio for

Is there a way to do this in v13? (I've been searching for a way, haven't found one though)

wide mirage
rugged sky
crisp tangle
rugged sky
crisp tangle

hmm, if the state of the audioPlayer has such useful things, maybe I should look more into it

rugged sky
azure pollen

Hello,
Can someone help me with my code for music bot.
I have TypeError: voiceChannel.join is not a function

And this is my code

crisp tangle
crisp tangle
azure pollen
crisp tangle I've never used `import` before, since the one time I did, it errored try `requi...

Now I have different error

(node:13348) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)
node:internal/modules/cjs/loader:960
  const err = new Error(`Cannot find module '${request}'`);
              ^

Error: Cannot find module 'C:\Users\mgali\Desktop\Projects\DiscordBot\node_modules\@discordjs\voice\dist\index.js'
    at createEsmNotFoundErr (node:internal/modules/cjs/loader:960:15)
    at finalizeEsmResolution (node:internal/modules/cjs/loader:953:15)
    at resolveExports (node:internal/modules/cjs/loader:482:14)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.execute (C:\Users\mgali\Desktop\Projects\DiscordBot\commands\play.cjs:11:38)
    at Client.<anonymous> (file:///C:/Users/mgali/Desktop/Projects/DiscordBot/main.js:41:37) {
  code: 'MODULE_NOT_FOUND',
  path: 'C:\\Users\\mgali\\Desktop\\Projects\\DiscordBot\\node_modules\\@discordjs\\voice\\package.json'
}
crisp tangle
azure pollen Now I have different error ```js (node:13348) DeprecationWarning: The message ev...

You can get rid of the deprecation warning by replacing message with messageCreate

- client.on('message', message => {...}               (This is from discord.js v12)
+ client.on('messageCreate', message => {...}

(^ This should be in your index file)

For the actual error it seems that it cannot find the voice module, have you installed it? (you have to install it separately than discord.js)

npm install @discordjs/voice
yarn add @discordjs/voice
pnpm add @discordjs/voice
azure pollen
crisp tangle
azure pollen
crisp tangle does it say the same thing now?

Yeah..

node:internal/modules/cjs/loader:960
  const err = new Error(`Cannot find module '${request}'`);
              ^

Error: Cannot find module 'C:\Users\mgali\Desktop\Projects\DiscordBot\node_modules\@discordjs\voice\dist\index.js'
crisp tangle

can you send your code again (of the play file)?

rugged sky
azure pollen
azure pollen
crisp tangle
azure pollen Here it is

There shouldn't be a problem with your code (up until line 37 at least)
and since the error says that it cannot find the module voice\dist\index.js, I would try reinstalling the @discordjs/voice module, just to be sure.

azure pollen
crisp tangle
azure pollen Okey, now it's better, now I have new error... ```js TypeError: joinVoiceChannel...

yeah joinVoiceChannel.join is not a thing
If you want to connect to a voice channel you'll have to do

joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
});

and if you want to have the connection as a reference for other stuff just put that in a constant variable

const connection = voice.joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
});

channel is the channel you will be joining. In your code that would be voiceChannel

azure pollen
crisp tangle
pseudo forum
const Discord = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus, StreamType } = require('@discordjs/voice');
const ytdl = require('ytdl-core');
const config = require('../../config.json');

module.exports = {
    name : 'play',
    /**
     * 
     * @param {Discord.Message} message 
     * @param {Array<string>} args 
     */
    async execute(message, args) {
        if (!args.length) return message.reply(`Exécutez la commande en insérant le lien d'une vidéo YouTube.`)

        const channel = message.member.voice.channel;

        if (!channel) return message.reply(`Vous devez tout d'abord de rejoindre un salon vocal !`);

        const connection = joinVoiceChannel({
            channelId: channel.id,
            guildId: channel.guild.id,
            adapterCreator: channel.guild.voiceAdapterCreator,
        });

        const player = createAudioPlayer();
        const stream = ytdl(args[0], { filter: 'audioonly' });
        const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });

        player.play(resource);
        connection.subscribe(player);

        player.on(AudioPlayerStatus.Idle, () => connection.destroy());

        player.on('error', error => {
            console.error(error);
        });
    },
};

I don't hear my bot in VC

crisp tangle
crisp tangle
pseudo forum

can you also use a console.log('Idle') here?
just to check if it starts playing and then maybe instantly goes back to idle

crisp tangle

ah yes, that's because the player is always idle when it's not currently playing anything, so basically before and after playing

pseudo forum

oh I see

azure pollen
crisp tangle
azure pollen I see, I need to install FFmpeg, so that I can gather resources for playing musi...

Yeah, in short: to play music you'd have to create an audio player (also don't create a new audio player each time someone uses your play function/command, only have one)

const audioPlayer = createAudioPlayer();          //you'll have to import {createAudioPlayer} from @discordjs/voice as well, don't forget

and then subscribe your connection to that audio player.

connection.subscribe(audioPlayer);

You can then create an audio resource with your ytdl stream like so

const stream = ytdl(args[0], {filter: 'audioonly'});
const resource = createAudioResource(stream);    //you'll have to import {createAudioResource} from @discordjs/voice as well, don't forget

then you can play that resource with your created audio player

audioPlayer.play(resource);

and FFmpeg has to convert your stream to an opus stream, if it isn't one

crisp tangle

you want to fix it? (continued in DMs)

pseudo forum

yes?

azure pollen
crisp tangle

👍 I've been updating my bot to v13 for the past 2 days, so I have some experience with @discord.js/voice

meager gorge

Hello I am updating my bot to v13 and I cannot figure out how to get the audio working. My bot joins the audio channel, but does not play any audio and get stuck in the playing state. Any advice would be appreciated.

        const connection = joinVoiceChannel({
          channelId: channel.id,
          guildId: channel.guild.id,
          adapterCreator: channel.guild.voiceAdapterCreator,
          selfDeaf: false,
          selfMute: false
        });

        //check to see if connection is valid
        if(connection)
        {
          //playing here NOT WORKING
          connection.subscribe(player);
          player.play(resource);
        }```
plush kraken

Also does anyone know how to setup music queue's using play-dl?

lofty warren

i know i already asked this earlier, but nobody knows how to use AudioResource constructor?

meager gorge
upper drum

i'm having trouble in general connecting to a voice channel and playing an audio clip. is there a quick script someone could make as a base so i could use that?

plush kraken
upper drum i'm having trouble in general connecting to a voice channel and playing an audio...

// imports 

const {
  joinVoiceChannel,
  createAudioPlayer,
  createAudioResource,
  NoSubscriberBehavior,
  StreamType,
} = require("@discordjs/voice");

// joining a vc from a message

  const channelID = message.member.voice.channel
    .toString()
    .replaceAll("<", "")
    .replaceAll(">", "")
    .replaceAll("#", "");

  console.log(`VoiceChannel ID: ${channelID}`);

  const connection = joinVoiceChannel({
    channelId: channelID,
    guildId: message.guild.id,
    adapterCreator: message.guild.voiceAdapterCreator,
  });

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

connection.subscribe(player);

I did the string manipulation because the channel id returned always contained <,>,# which made it invalid you can also just do a string.match() instead.

NOTE: YOU NEED TO HAVE THIS IN YOUR INTENT


const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.DIRECT_MESSAGES,
    Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
    Intents.FLAGS.DIRECT_MESSAGE_TYPING,
    Intents.FLAGS.GUILD_VOICE_STATES, //<-- important for vc
  ],
});

I don't know how to play resource from your local library right now though I'm just streaming stuff from youtube.

rigid abyss

I'm trying to play internet radio urls and using the code javascript const res = await fetch(fileId); if (!res.ok) console.log("Had a problem fetching!"); return res.body;
works perfectly for something like an mp3 hosted on a webserver, but the moment I try to play something from an icecast server i get the error attached. I assume this is because the bot isn't able to load the whole stream so it times out. Any way I can get around this?

vivid hemlock

Anyone know a good hosting service for a music bot?

abstract acorn

is there a way to get an mp3 file playback duration which is on discord cdn?

the reason it is on cdn is because we used to put mp3 files straight into discord for Groovy to play (what used to be -p f command)

potent pebble

After moving a member to another voice channel, getting their voice channel id logs the previous channel id, is there like a time that I need to wait for it to update?
I do fetch member before loggin to be sure

Do I need the voice library orrrr?

Figured it out, was missing GUILD_VOICE_STATES intent

facepalm

rugged sky
sudden hawk
rigid abyss
sudden hawk

local files

rigid abyss

How confident are you with discordjs/voice already. When I get home tonight I can send some code to do that

crisp tangle

You said you wanted to play multiple songs

sudden hawk
rigid abyss
sudden hawk

making a queue

crisp tangle

that doesn't have much to do with @discord.js/voice itself, you can use some kind of array for the queue
I use a linked list for the queue

rigid abyss

True. That is more so just standard js stuff

sudden hawk

oh

rigid abyss
crisp tangle

So for today and yesterday now, I've been trying to figure out why my bot's connection is always stuck on signalling, when I run my joinVoiceChannel() function. This is what I get when I print the connection itself

<ref *1> K {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  rejoinAttempts: 0,
  _state: {
    status: 'signalling',
    adapter: {
      sendPayload: [Function: sendPayload],
      destroy: [Function: destroy]
    }
  },
  joinConfig: {
    selfDeaf: true,
    selfMute: false,
    group: 'default',
    channelId: '694105448822997022',
    guildId: '432175548169584642',
    adapterCreator: [Function (anonymous)]
  },
  packets: { server: undefined, state: undefined },
  receiver: q {
    voiceConnection: [Circular *1],
    ssrcMap: L {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      map: Map(0) {},
      [Symbol(kCapture)]: false
    },
    subscriptions: Map(0) {},
    connectionData: {},
    speaking: se {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      users: Map(0) {},
      speakingTimeouts: Map(0) {},
      [Symbol(kCapture)]: false
    },
    onWsPacket: [Function: bound onWsPacket],
    onUdpMessage: [Function: bound onUdpMessage]
  },
  debug: null,
  onNetworkingClose: [Function: bound onNetworkingClose],
  onNetworkingStateChange: [Function: bound onNetworkingStateChange],
  onNetworkingError: [Function: bound onNetworkingError],
  onNetworkingDebug: [Function: bound onNetworkingDebug],
  [Symbol(kCapture)]: false
}

Nothing seems wrong with it, so I'm confused.

I've also been printing connection.state every 3 seconds. And it always outputs status: signalling, like I said before

{
  status: 'signalling',
  adapter: {
    sendPayload: [Function: sendPayload],
    destroy: [Function: destroy]
  }
}

The voice channel that I want to connect to exists, its ID string exists, the @discordjs/voice package is up-to-date (also reinstalled it) and I have the GUILD_VOICE_STATES intent.
I have absolutely no idea what the problem is, and this worked perfectly 2 days ago. Any ideas?

subtle granite

This might seem pretty obvious but does your bot have permissions to join the requested voice channel?

crisp tangle

yes, he has ADMINISTRATOR permissions
also when I do my play command, the bot itself joins my VC on discord physically, but the actual connection is still in the signalling state
thanks for trying to help though, that is appreciated

subtle granite

Hm have you tried playing some audio?

crisp tangle

I have 2 listeners, one for when the connection has been disconnected and one for when it's ready and connected
(below is my ready listener)

connection.once(voice.VoiceConnectionStatus.Ready, () => {
      if (first_state !== 'none') {
              //console.log(`First state isn't none! First state: ${first_state}`);
              return;
      };

      first_state = 'ready';
      message.channel.send(`**Joined** \`${member_channel.name}\``);
      queue(connection);
      return;
});

It would have played the music with queue(connection), if it ever went to ready, though it hasn't had any state changes at all

But I will try to forcefully play music, and I'll report back.
(edit/report: my audio player starts playing, though the connection doesn't channel the audio)

subtle granite

If you use ```js
const connection = getVoiceConnection(guildId)
//console.log the state of that connection

crisp tangle
subtle granite

Ok that's a weird one... I really have no idea right now sorry

crisp tangle

it's okay 👍

subtle granite

@crisp tangle which package.json dependencies do you have?

astral summit
       const { joinVoiceChannel } = require('@discordjs/voice');
 const connection = joinVoiceChannel(
            {
                channelId: message.member.voice.channel,
                guildId: message.guild.id,
                adapterCreator: message.guild.voiceAdapterCreator
            });

 
        const videoFinder = async (query) => {
            const videoResult = await ytSearch(query);
 
            return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
 
        }
 
        const video = await videoFinder(args.join(' '));
 
        if(video){
            const stream  = ytdl(video.url, {filter: 'audioonly'});
            connection.play(stream, {seek: 0, volume: 1})
            .on('finish', () =>{
                voiceChannel.leave();
            });``` why do i get this error ```js
 connection.play is not a function
crisp tangle
{
  "name": "discord-bot",
  "version": "1.2.0",
  "description": "Bot from scratch",
  "main": "index.js",
  "scripts": {
    "test": "echo yes"
  },
  "author": "TheKiller101555",
  "license": "ISC",
  "dependencies": {
    "@discordjs/opus": "^0.7.0",
    "@discordjs/voice": "^0.7.5",
    "axios": "^0.24.0",
    "cheerio": "^1.0.0-rc.10",
    "discord.js": "^13.3.1",
    "discord.js-musicbot-addon": "^13.9.1",
    "eslint": "^8.2.0",
    "ffmpeg": "0.0.4",
    "ffmpeg-static": "^4.4.0",
    "install": "^0.13.0",
    "jquery": "^3.6.0",
    "jsdom": "^18.1.0",
    "libsodium-wrappers": "^0.7.9",
    "opus": "0.0.0",
    "opusscript": "0.0.8",
    "request": "^2.88.2",
    "updated-youtube-info": "^1.4.7",
    "ytdl": "^1.4.1",
    "ytdl-core": "^4.9.1",
    "ytdl-core-discord": "^1.3.1"
  }
}
subtle granite

I took the code you send above and created a small bot which joins the voice channel perfectly fine

const voice = require('@discordjs/voice');
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [
  Intents.FLAGS.GUILDS,
  Intents.FLAGS.GUILD_MESSAGES,
  Intents.FLAGS.GUILD_VOICE_STATES
]});

console.log(process.version)

client.login(process.env.TOKEN);

client.on('messageCreate', async(message)  => {

  //...
  const member_channel = message.member.voice.channel;
  //...
  if (message.author.bot) return;
  if (!member_channel) {
      return message.channel.send('**You have to be in a voice channel to use this command**');
  };
  //...
  const connection = voice.joinVoiceChannel({
      channelId: member_channel.id,
      guildId: member_channel.guild.id,
      adapterCreator: member_channel.guild.voiceAdapterCreator,
  });
  //...

  console.log(connection.state)

  connection.on('ready', () => {
    console.log(connection.state)
    message.channel.send(`**Joined** \`${member_channel.name}\``);
    //queue(connection)
    return;
  });
});

using the following dependecies

   "@discordjs/opus": "^0.7.0",
   "@discordjs/voice": "^0.7.5",
   "discord.js": "^13.3.1",
   "ffmpeg-static": "^4.4.0",
   "libsodium-wrappers": "^0.7.9"

seems like it's the same

crisp tangle
subtle granite

also seek doesn't exist in v13 anymore

slim jay

I have a question about inline audio. The docs says "Enabling it will allow you to modify the volume of your stream in realtime.". Is there a way to modify the volume once when you create the resource without a performance decrease?

subtle granite
// Will use FFmpeg with volume control enabled
resource = createAudioResource(join(__dirname, 'file.mp3'), { inlineVolume: true });
resource.volume.setVolume(0.5);```
that's what the guide says so I assume no (not with djs)
slim jay

Ok, the speciation of "in realtime" made me think it was possible

hoary widget
Error: Error: Cannot find module '/home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm-glibc-2.28/opus.node'
Require stack:
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/@discordjs/opus/lib/index.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/prism-media/src/util/loader.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/prism-media/src/opus/Opus.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/prism-media/src/opus/index.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/prism-media/src/index.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/dist/index.js
- /home/pi/NodeBot/commands/music/play.js
- /home/pi/NodeBot/handlers/command_handler.js
- /home/pi/NodeBot/bot.js

anyone know how to fix this error? (i fixed it by reinstalling @discordjs/opus and @discordjs/voice one by one)

subtle granite

connection.destroy()

real reef

connection.destroy() to delete the connection

smoky ore

I have socket closed error and abort_err how can I fix this

mental adder

Anyone can help me? I'm trying to install sodium but it giving an error

abstract acorn

is there a way to get an MP3 song length which is on a URL?

main ferry

I keep randomly getting emmited errors when my bot plays music at @discordjs\voice\dist\index.js:8:288

I figured it had something to do when my bot wasn't idle and something about the audio resource

icy maple

What is the error?

frozen sierra

i want to make a seek command and audio filters with the help of stream url and ffmpeg , is there any repo examples or snippet ? I am lost right now , i tried ffmpeg from prism-media

nimble pelican

how can i make the bot join the vc using @discordjs/voice?

simple sapphire

I'm trying to play audio from one vc to another but im getting this error

Cannot play a resource that has already ended.

Code: https://sourceb.in/6yc7Y5oUBk

rugged sky
errant arch

Hi, I just deployed my bot from my windows machine to my linux server. Everything worked perfectly fine, but when I switched to linux I suddenly have no sound when playing something without any errors. Do I need to do something differently when using a linux system?

rugged sky

You can install python or use opusscript instead.

steel summit

I get this error: SyntaxError: Unexpected token '.' from the /node_modules/@discordjs/voice/dist/index.js:1 file and since the first line is really, really long I can't see where the error is

the terminal only says line 1 but not the position in that line so I don't know how to fix this

this is the whole line 1 in that file

could someone help me pls?

nevermind, I think I found a way to find the errors, thanks anyways

humble birch
const opusStream = connection.receiver.subscribe(userId, {
      end: {
        behavior: EndBehaviorType.AfterSilence,
        duration: 100,
      },
    });
    const resource = createAudioResource(opusStream, {
      inputType: StreamType.Opus,
    });

the player playing this audioressource is going into idle state after the first pause (while speaking e.g. starting a next sentence), while streaming to a file or listen through a browser is no problem and the stream doesn't stop at the first speakingpause

true portal

i'm using discord.js v12 with ytdl-core and discordjs/opus
is there any way to change the volume?
my current code looks something like this:

                filter:'audioonly',
                highWaterMark: 1 << 25
            });
            dispatcher = connection.play(stream,{seek: 0,volume: 1})
            /*dispatcher = connection.play(ytdl(musicq[0],{
                filter:'audioonly',
                highWaterMark: 1 << 25
            }));*/
            clearTimeout(autodc);
            playing = true;
            dispatcher.on('finish',()=>{
                musicq.shift();
                music(message);
                playing = false;
            });```
(the commented out part is what i used before, the other part from var stream = ... is what i tried from reading random stuff on the internet, but that does not change the volume)
rugged sky
true portal

and how would i do that in v13?

rugged sky
true portal

oh alright, thank you very much for the help!

rugged sky

np

humble birch
digital bobcat

How to get the bot deaf himself?

fervent estuary

Pass setSelfDeaf as true when joining a channel

Its true by default anyways tho

blissful zephyr

how do i get a player from a play command to a pause command?

rose saffron

hey, how would I go about recieving audio?

also what is duration in end?

crisp tangle
crisp tangle Nothing seems wrong with it, so I'm confused. I've also been printing `connect...

It seems that the error was that the joinVoiceChannel() function was called in an async function? I removed async and it worked perfectly, but I require it to await client_user..

const client_user = await message.guild.members.fetch(message.client);
const client_channel = client_user.voice.channel;

I use client_user to check for the client_channel, which is the channel, that the bot is currently in, since I don't want anyone outside that voice channel to be able to use the music commands.

Any ideas on how to wait on client_user (other than await, since it breaks @discordjs/voice) or on how to get the bot's channel in a different way?

humble birch
crisp tangle
humble birch
message.member.voice.channel.members.has(message.client.id)

could work

crisp tangle
const voice = require('@discordjs/voice');

async execute(message, args) {
    const client_user = await message.guild.members.fetch(message.client);
    const client_channel = client_user.voice.channel;
    const client_connection = voice.getVoiceConnection(message.guild.id);
    const member_channel = message.member.voice.channel;

    if (client_channel) {
        if (!member_channel) {
            return message.channel.send('**You have to be in a voice channel to use this command**');
        };

        if (client_channel !== member_channel) {
            return message.channel.send('**You have to be in the same voice channel to use this command**');
        };

        if (client_connection) {
            if (client_connection.state.status !== voice.VoiceConnectionStatus.Ready) {
                return console.log('Connection is not ready');
            };
            console.log('Client is already in channel | Running queue function')
            //queue(client_connection);
            return;
        };
    };
    
    if (!member_channel) {
        return message.channel.send('**You have to be in a voice channel to use this command**');
    };

    const connection = voice.joinVoiceChannel({
        channelId: member_channel.id,
        guildId: member_channel.guild.id,
        adapterCreator: member_channel.guild.voiceAdapterCreator,
    });

    var first_state = 'none'
    connection.once('ready', () => {
        if (first_state !== 'none') {
            return;
        };

        first_state = 'ready';
        message.channel.send(`**Joined** \`${member_channel.name}\``);
        //queue(connection);
        return;
    });

    connection.once('disconnected', () => {
        if (first_state !== 'none') {
            return;
        };
        first_state = 'disconnected';
        return message.channel.send(`Something went wrong while trying to join \`${member_channel.name}\``);
    });
},

Here's the short version (edited down), since the queue() & play() functions would be too long and aren't really the problem here.

Before in v12 discord.js, I was able to do const client_voice = message.guild.voice; and I could get the bot's voice channel from there on with client_voice.channel, but now guild.voice has been removed (I can't find this in the docs anymore) and I have no idea how to get the bot's channel/voice. I've been searching around for hours to see how others have coded their music bots (youtube tutorials, other open source bots.. bla bla bla) and I've seen how they all check if the member is in a voice channel, but not one that checks if the member is in the same voice channel as the bot. Maybe I'm just unlucky..

humble birch

you're trying to join a voicechannel, but you're saying the bot is already in a voicechannel?!

crisp tangle

I'm not sure I understand what you're trying to say, but what I want is:
If the bot is already in a voice channel (joined someone in some voice channel earlier), then a member who isn't connected to the voice channel the bot is currently in shouldn't be able to use the music commands.
I have to go to sleep now though

winged plover

Okay so i spent 12 goddamn hours trying to figure this out, so I'm putting this here in-case anyone else runs into this.

If you are using the same audioplayer and changing what it is playing via the .play method, and it happens to be a stream URL, you can never use that URL again unless you make a brand new audioplayer and subscribe the VC to it

My workaround was just to pass in the audio data via axios, vs letting discord.js handle the URL on it's own

It's literally the most confusing thing, and debug shows nothing about it- literally the only reason I figured this out was by wondering to myself if the docs reference to " the existing resource is destroyed (it cannot be reused, even in another player)" could possibly mean a passed in string to a createAudioResource method

and low and behold, it somehow was.

late vigil
const connection = joinVoiceChannel({
    channelId: message.channel.id,
    guildId: message.guild.id,
    adapterCreator: message.guild.voiceAdapterCreator
});

const player = createAudioPlayer();

player.on("error", err => {
    throw err;
});

// don't get any error when i delete the part below

player.play(ytdl(video.url, {filter: "audioonly"}));

connection.subscribe(player);

this is my code to play song in a channel but everytime i got this error

humble birch
crisp tangle ```javascript const voice = require('@discordjs/voice'); async execute(message,...

try:

async execute(message, args) {
    const client_user = await message.guild.members.fetch(message.client);
    const client_connection = voice.getVoiceConnection(message.guild.id);
    const client_channel = !client_connection ? null : client_connection.joinConfig.channelId;
    const member_channel = message.member.voice.channel;
...
if (client_channel !== member_channel.id) {
            return message.channel.send('**You have to be in the same voice channel to use this command**');
        };
fervent estuary
late vigil
fervent estuary

Looking at the second line there seems like ur trying to play a resource tvag has already ended

late vigil

no this is some code

idk for why but that send me the whole code of a file

fervent estuary

Does that occur everytime?

late vigil

yep

but nvm i just go to 12.5.3 version cause 13.3.1 is horrible

crisp tangle
crisp tangle
late vigil
crisp tangle

👍

late vigil
const connection = Voice.joinVoiceChannel({
    channelId: inChannel.id,
    guildId: inChannel.guildId,
    adapterCreator: inChannel.guild.voiceAdapterCreator
});

const audioPlayer = Voice.createAudioPlayer();

audioPlayer.play(ytdl(video.url, {filter: "audioonly"}));

connection.subscribe(audioPlayer);

i got the same big error...

winged plover

The number of times I see this error in this channel is astounding. You need to create an audio resource to play in it

late vigil

but in the docs that say that you can pass a stream data

winged plover

Inside an audio resource

late vigil

AAAAAAAAAAAAAAH

that version trigered me soo much

crisp tangle

have you seen the guide for the v13 voice library @late vigil, it explains everything

winged plover

ex:

import { createAudioResource } from "@discordjs/voice"

createAudioResource(streamDataHere, { optionsifany })

and you will play the audio resource, as in, what the method above returns

Admittedly, the docs aren't super clear on that^ so I understand the confusion! hope this helps

late vigil

yeah don't worry i get it now, its just the v12 that made me don't paid attentions to details

winged plover

nah you're all good. I've had my fair share of troubles with the voice lib myself because of lackluster documentation lol

late vigil

the olds devs have left discord xD

crisp tangle

hmm, I haven't had to look at the docs for the voice library at all to get my bot to play music (maybe I'm lucky)

is it just me who read the entire guide to the voice library?

late vigil

i have to cause the intelisense of vscode is broken else idk how did you know how to get variables

winged plover

Personally I'm doing a lot of unconventional things with it, splitting streams, piping data to and from remote nodes, etc; for the avg joe it's pretty good, but for the more complex things, I've run into lots of odd gimmicks that aren't noted anywhere lol cc: @crisp tangle

late vigil

that triggered me a lot more to see that we have to go with function instead of classes or object, the v13 change so much, idk why they did this

winged plover

It's actually super nice quite honestly, because everything is modular

Like I have many of my own classes, and instead of needing to extend off an existing class like in some prior versions, I can just import what I need

slim jay

This may not be directly related to to the voice library, but was hoping a lovely person could help. I am currently using node-fetch to get an audio stream and then piping that ReadableStream through a transformer, and then passing that ReadableStream to .play(). The problem is sometimes the stream will go to idle suddenly, I figure it's a network problem but I really don't know how to recover gracefully and restart the stream if this happens

I would just listen to the idle statechange and just play the stream again but the idle event is fired when theres no subscribers to the stream

slim jay

Werid thing is that I didn't have this issue with the same code on v12

south lark

Any idea why this would be happening:

Error: Cannot find module '(directory-name)/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-x64-glibc-2.31/opus.node'
south lark

Okay I was able to fix it actually.

Appears to have been because I accidentally installed on an older node version (I think I installed on v14).
Removing node_modules and reinstalling (via npm install of course) fixed the problem yay

@celest basalt may wanna add another pin for this or something since there is a v0.7, specifically a v0.7.4 as of now Eyes
Up to you of course shibaheart

neat wing

any ideas?

rose helm

How does the player determine when to throw the player idle event? I've attached listeners to all of the streams including the probe to listen for the end event, but none of them throw that event.
I'm running into the issue of the player ending prematurely

rose helm

Yeah. It's just the AudioResource.playStream being closed. None of the other streams are emitting close before the playStream, so it's coming from the pipeline

The problem ended up being that I assigned the playStream as the result of a pipe from the stream to a FFMPEG class from prism-media. Instead, I now just manually specify the stdin and stdout

real vapor
        const connection = getVoiceConnection(int.guildId);

        if (connection) {

            const player = //HOW DO I GET THE PLAYER WHILE IS PLAYING, ive defined the player in a different file!

            console.log(player.pause());
        }
    },
icy maple

connection.state.subscription.player

tight lodge

Can someone tell me what I am doing wrong here ?

    const voicechannel = interaction.member.voice.channel;
    const player = createAudioPlayer({
      behaviors: {
        noSubscriber: NoSubscriberBehavior.Pause,
      },
    });

    async function connectToChannel(channel) {
      const connection = joinVoiceChannel({
        channelId: channel.id,
        guildId: channel.guild.id,
        adapterCreator: channel.guild.voiceAdapterCreator,
      });
      try {
        await entersState(connection, VoiceConnectionStatus.Ready, 30_000);
        return connection;
      } catch (error) {
        connection.destroy();
        throw error;
      }
    }

    const record = interaction.options.getString("record");
    const audiosPath = __dirname + "../Audios/";

    const resource = createAudioResource(audiosPath + record);
    const connection = await connectToChannel(voicechannel);
    player.play(resource);
    connection.subscribe(player);
  },

Its joining the voice channel but not playing the opus stream

crisp tangle
teal nymph

also check the path is correct

real vapor

is it still possible to record user voices with the bot?

shut apex

thanks for posting this code , I am newbee

lament saffron

Hello, I tried making a music discord bot using ytdl. Here's my code:

const Discord = require("discord.js");
const Commando = require('discord.js-commando');
const ytdl = require('ytdl-core');

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

client.on('message', async message => {
let args = message.content.split(' ');
    const command = args.shift().toLowerCase();

if (command == "amogus!p") {
        if(!message.member.voice.channel)
            message.channel.send(`${message.author.name} sussy bot`);
        
            const connection = await message.member.voice.channel.join();
            
            let url = "";
            for(let i = 0; i < args.length; i++)
                url += args[i];
            connection.play(ytdl(url));
    } else if(command == "!leave") {
        message.guild.me.voice.channel.leave();
    }

});

client.login("unknown");

I've installed the following packages:

root@1.0.0 /root
├── @discordjs/opus@0.5.3
├── @discordjs/voice@0.7.5
├── discord.js-commando@0.12.3
├── discord.js@12.5.3
├── discordjs-ytdl@2.2.0
├── ffmpeg-static@4.4.0
├── mongoose@6.0.12
├── node@16.6.1
└── openweather-apis@4.4.2
```.

My bot is joining the channel, but after awhile I get this error:

/root/node_modules/discord.js/src/client/voice/VoiceConnection.js:303
this.emit('error', new Error(reason));
^

Error [VOICE_CONNECTION_TIMEOUT]: Connection not established within 15 seconds.
at VoiceConnection.authenticateFailed (/root/node_modules/discord.js/src/client/voice/VoiceConnection.js:303:26)
at /root/node_modules/discord.js/src/client/voice/VoiceConnection.js:324:61
at Timeout.<anonymous> (/root/node_modules/discord.js/src/client/BaseClient.js:83:7)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
[Symbol(code)]: 'VOICE_CONNECTION_TIMEOUT'

The bot is running on my ssh client

Feel free to tag me if you get anything.

odd kite
lament saffron

Yeah, I forgot about that, but it still the same

real vapor

@deep dome i have looked everywhere sry for @

deep dome

This feature isn't documented in the Voice API by Discord and is prone to breaking quite a lot. We have basic support for it in the voice library currently, but there is still work going on to add utilities to make it easier to work with.
pinned message

lament saffron

Should I open a thread about my problem ?

crisp tangle
real vapor

thank you

tight lodge

The funny thing is its saying it ended playing the resource but there is no sound coming from the bot

lament saffron

Playing youtube music via ytdl

tight lodge

Also my resource is a opus audio file

crisp tangle
tight lodge

Its the interaction option value

which is the file name with the extension

I am pretty sure its not a path issue

crisp tangle
tight lodge I am pretty sure its not a path issue

I also just tried playing a opus file locally saved, and it worked for me. I'm not exactly sure why it wouldn't work for you. You said the path is not the issue, does that mean you've console logged it and checked it already?

crisp tangle
tight lodge Yes

C:\Users\name\Desktop\discord-bot-test../discord-bot-test/Audios/music_test.opus is what I get when I console log my audiosPath + filename (filename = record) and it doesn't seem to be quite correct.. since it just has a random ../ in the middle of it (also the bot didn't play anything like you said as well)

wouldn't const audiosPath = "./../Audios/" suffice? I tested it with just that and it worked.

teal nymph

Or const audiosPath = "../Audios/";

crisp tangle
teal nymph

no pb

subtle granite

How can I detect when the songs are finished?

crisp tangle
subtle granite

I did something like this it didn't even print the new state :/

crisp tangle
subtle granite

My song finished but didn't give any response

crisp tangle
subtle granite

try AudioPlayerStatus.Idle instead of 'play' just in case (don't forget to import/require AudioPlayerStatus)

player.on(AudioPlayerStatus.Idle, () => {
    guild.nowPlaying++;
    player.play(guild.queue[guild.nowPlaying]);
    guild.connection.subscribe(player);
    console.log('Next Song')
});
subtle granite

@crisp tangle ,
What exactly does this event entail?

crisp tangle

oh wait... I put in the wrong event

ok basically:
It is in Idle when it's not currently playing any resource.
And it is in Playing when it's currently playing a resource.

I've had the thought that it could fire my Idle listener before I even start playing anything, but I've dealt with that and your code is structured in a way that I think that wouldn't happen

crisp tangle
subtle granite

Didn't catch :/ 😦

subtle granite
crisp tangle
crisp tangle
subtle granite I'm waiting

Problem is that you're returning when you add to queue or start the queue, so the listerner's code isn't even being ran/registered

pale jackal

Does anyone know how to specify input stream parameters in prism-media ffmpeg module?

empty crescent

Every once and a while I randomly get this error. Any idea why?

AudioPlayerError: aborted
  at connResetException (node:internal/errors:691:14)
  at TLSSocket.socketCloseListener (node:_http_client:407:19)
  at TLSSocket.emit (node:events:402:35)
  at node:net:672:12
  at TCP.done (node:_tls_wrap:580:7)

should I just reconnect the bot if I get this?

subtle granite
crisp tangle

👍

crisp tangle
opaque geyser

Music stop event for player?

opaque geyser

help

carmine timber
crisp tangle
opaque geyser

need I get music duration and do setTimeout?

crisp tangle
opaque geyser

and how to get all memvers in vchannel?

crisp tangle
ornate stratus

Is this an ongoing issue? I cannot install @discordjs/opus at all, its giving me some weird node-pre-gyp errors with it trying to find python for some reason

ornate stratus
trail spire
golden leaf
ornate stratus

yeah i know that, so is the package not supported in it?

pine oar

can we make it so that on joining a stage a bot starts the stage as well

crisp tangle
pine oar
ornate stratus

i think i figured it out though, the project I'm using as a fork in repl lacks builds so its difficult to achieve this

digital bobcat
crisp tangle
digital bobcat But how do I deaf/undeaf the bot when it is already connected to the voice chann...

I do not know of a way where a bot can deaf itself (self deaf), but if I wanted to do something like that I would have done the closest thing possible:

const client_user = await message.guild.members.fetch(message.client);
client_user.voice.setDeaf(false, 'no');  //.setDeaf(boolean, reason);

I'm fetching the bot as a member in message's guild and getting its voicestate, after that I can server mute/deaf the bot, but that isn't self-mute/-deaf.

Though why would you want the bot to self-deaf/undeaf anyways?

icy maple

Music bots usually self deaf bc it’s a waste of load to receive voice

crisp tangle

They can receive voice?

icy maple

Bots can receive voice

Server mute and self mute is different

Anyone with perms can edit other member's server mute status, but not self mute

crisp tangle

I know that much, that's why I stated it's different than what they wanted
but if the bot does have the permission, instead of self-muting on join, it can server-mute/server-deafen itself, achieving what ragepappa wanted

eh whatever, I have no idea what I'm talking about and what uses the option to self-mute/self-deafen would have anyway

icy maple

I don’t think self deaf can be edited once the connection has been created due to the way voice is structured

digital bobcat

Okay

final jay

this <AudioResource>.playStream doesn't look very reliable

any idea about this error? Error: Premature close

happens when I try to play (again) a <AudioResource>.playStream

crisp tangle
final jay

running what as a function?

crisp tangle

.playStream, or what did you do to get that error?

final jay

doesn't really look like a function to me but

crisp tangle

I know, that's why I asked

I'm not sure what this property is, do you know?

final jay

I guess it is the stream of this resource?

in case, <AudioResource>||<- THIS resource||.playStream

main ferry

I'm currently facing an issue where the audio player constantly and randomly aborts songs while playing

does anyone know why this is the case?

crisp tangle
main ferry
crisp tangle what does your code look like for creating an audio resource?
// Convert youtube URLs to audio resources
// @param song - The song to be converted into an audio resource
// @return - no return value
function convertURL(song) {

    const resource = ytdl(song.url, { filter: "audioonly" });
    return createAudioResource(resource , { inputType: StreamType.Arbitrary });

}

// Convert the song url and create an audio resource
    =queue.audioPlayer = createAudioPlayer();
    queue.resource = convertURL(queue.songs[0]);

    // Play the song
    queue.audioPlayer.play(queue.resource);
    sendMessage(queue, client);

    // subscribe to the connection
    connection.subscribe(queue.audioPlayer);

    // Catch any errors/disconnects
    queue.audioPlayer.on('error', error => {
        console.log(`Error: ${error.message} with resource ${queue.resource.metadata}`);
    });

    // Wait for the song to finish and play the next song
    queue.audioPlayer.on(AudioPlayerStatus.Idle, () => {

        // Shift queue and play next song
        queue.songs.shift();
        queue.audioPlayer.stop();
        this.play(client, guildId);

    });```
crisp tangle

okay, it seems you don't have the same problem I had, I'll leave this up to others, since I don't know the exact issue

what I had done is createAudioResource(resource, { inputType: StreamType.WebmOpus }); and that caused the issue of my audio player just stopping and erroring abort somewhere in the middle of the song, and when I just completely removed inputType, it worked again. I think it had to do something with if ffmpeg converted or not. I don't if Arbitrary gets converted by ffmpeg

main ferry

I'm converting youtube URLs so it told me to use Arbitrary stream typ

crisp tangle
main ferry
crisp tangle

yes I am

main ferry
crisp tangle

👍

crisp tangle
main ferry what is highWaterMark?

from what I found out, it's the buffer for the stream (how much it downloads/pre-caches before)
and apparently 1 << 25 is 32mb (default is 16mb)

main ferry

hmm ok, is there a detailed documentation for audio player and resources?

crisp tangle
crisp tangle

👍 no problem, I'm going to bed now though

main ferry

alright

main ferry

does anyone know why sometimes an audio player speeds up

raven seal

I want to find out the number of users on the channel

"discord.js": "v13.3.1"
TypeError: Cannot read properties of undefined (reading 'members')
const cd = client.channels.cache.get(oldChannel).members.size
cd === members count size
wide mirage

Hello! how can i fix it ? reject Promise {
[
{
status: 'connecting',
adapter: [Object],
networking: [Networking]
},
{ status: 'ready', adapter: [Object], networking: [Networking] }
]
} AbortError: The operation was aborted
at abortListener (node:events:838:14)
at EventTarget.<anonymous> (node:events:874:47)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
at EventTarget.dispatchEvent (node:internal/event_target:504:26)
at abortSignal (node:internal/abort_controller:97:10)
at AbortController.abort (node:internal/abort_controller:122:5)
at Object.entersState (/home/runner/Music-Bot/node_modules/@discordjs/voice/dist/util/entersState.js:20:56)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}

carmine timber
opaque geyser

How to play specific hz?

subtle granite

is the AudioReceiveStream for recording a voice channel?

final jay

seek when? 😩

jade viper

Hello message.member.voice.channel; is always undefined I don't know why

crisp tangle
final jay

aka GUILD_VOICE_STATES

safe swallow

hey! how can i get a whole voice channel's audio?

i want to record a voice channel and then save it to mp3 file

final jay

who's the owner of djs/voice?

jade viper
summer pawn
AbortError: The operation was aborted
    at abortListener (node:events:842:14)
    at AbortSignal.<anonymous> (node:events:878:47)
    at AbortSignal.dispatchEvent (D:\CracklesCreeper\Discord Bots\Orders\Mega Joshy\node_modules\event-target-shim\dist\event-target-shim.js:818:35)
    at abortSignal (D:\CracklesCreeper\Discord Bots\Orders\Mega Joshy\node_modules\abort-controller\dist\abort-controller.js:52:12)
    at AbortController.abort (D:\CracklesCreeper\Discord Bots\Orders\Mega Joshy\node_modules\abort-controller\dist\abort-controller.js:91:9)
    at Timeout._onTimeout (D:\CracklesCreeper\Discord Bots\Orders\Mega Joshy\node_modules\shoukaku\src\guild\ShoukakuConnection.js:139:53)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7) {
  code: 'ABORT_ERR'
}``` this is the full error I get when I try to connect my bot to a voice channel. How do I fix it?

I am trying to use lavalink btw

whole flare
summer pawn

Yes

whole flare

Is your source also playable?

summer pawn

Yes

whole flare

Try to do it again and log all messages with the debug event on your client to check if your bot can really connect to the Discord API

summer pawn

It doesn't log anything

I tried

whole flare

Can you show your code?

summer pawn

I was using a framework

whole flare

This is not @discordjs/voice so I won't be able to help you with this

summer pawn

Oh ok, but it gives error while connecting so thought it was related

jade viper

Hello ```js
if (!voiceChannel) return message.channel.send('I'm sorry but you need to be in a voice channel to play music!');

var connection = await joinVoiceChannel(
    {
        channelId: message.member.voice.channel,
        guildId: message.guild.id,
        adapterCreator: message.guild.voiceAdapterCreator
    });

    
const stream = ytdl(video_url, { filter: 'audioonly' });
const resource = createAudioResource(stream, { inlineVolume: true });
resource.volume.setVolume(0.5);
connection.play(resource); ```

This code return my this error : ```js
connection.play(resource);
^

TypeError: connection.play is not a function
at Client.<anonymous>

rugged sky
final jay

how do I seek?

cloud vine

Today i can kick my bot in voice channels by this

if(message.member.voice?.channelId) and connection.destroy()

But i can also kick from just being in a voice channel, any way to make bot understand not to leave the channel if you are in any other channel that the actual one that bot are in?

subtle granite

Get the connection of that guild and check whether the channelId of the bot's connection is the same as the one of the message.member @cloud vine

subtle granite
final jay

but I don't know if I'm doing something wrong

because, it's taking A LOT to seek, about 20 seconds to seek to 2 min of a song

subtle granite
final jay
subtle granite

prism-media npm package I believe

final jay

makes sense, and songurl can be the stream?

or what?

final jay

nvm

just found it

const FFMPEG_OPUS_ARGUMENTS = [
     '-analyzeduration',
     '0',
     '-loglevel',
     '0',
     '-acodec',
     'libopus',
     '-f',
     'opus',
     '-ar',
     '48000',
     '-ac',
     '2',
];
subtle granite

Yeah that one work😀👍

final jay

or that, ye

final jay
subtle granite

Uhm I downloaded the song and than used seek on it... I don't know whether you can directly use it on the stream (I don't think so)

And then just passed the file path

final jay

'-'

final jay

and apparently you can input a readable stream too
so I'll try that
thanks for the help

subtle granite

Great 👍

final jay

I tried for a long time
check this out: I have my args here

I tried creating the ffmpeg transcoder, pipe, and then play

the bot appeared with the green ball of speaking, but wasn't playing anything

I also tried using -i ytdlStream, same result

subtle granite

I used ```js
const info = await ytdl.getInfo('url')
await ytdl.downloadFromInfo(info, { quality: 'highestaudio'}).pipe(fs.createWriteStream('./filename')

final jay

well, doesn't look like you used ffmpeg at all

subtle granite

And than ```js
const FFMPEG_ARGUMENTS = [
'-analyzeduration', '0',
'-loglevel', '0',
'-f', 's16le',
'-ar', '48000',
'-ac', '2',
];

const stream = new prism_media.FFmpeg({
args: ['-ss', 00:00:10, '-i', './filename' , ...FFMPEG_ARGUMENTS],
});

const resource = createAudioResource(stream, { inputType: StreamType.Raw });

final jay

oohh
now we talking

final jay

no, we not talking

same thing as always 😭 not working

jade viper
rugged sky `play()` is not a function of `VoiceConnection` objects. To play an `AudioResour...

Tanks ! ```js
var connection = await joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});

const player = createAudioPlayer();
const stream = ytdl(video_url, { filter: 'audioonly' });
const resource = createAudioResource(stream, { inlineVolume: true });
resource.volume.setVolume(0.5);
player.play(resource);
connection.subscribe(player); ``` But my bot doesn't join the channel
rugged sky
main ferry

does anyone know what Error: Status code: 410 with resource null means?

// Catch any errors/disconnects
queue.audioPlayer.on('error', error => {
    console.log(`Error: ${error.message} with resource ${queue.resource.metadata}`);
});```
carmine timber
summer crow

How to change volume of resource?

summer pawn
{
  library: 'SSL routines',
  function: 'ssl3_get_record',
  reason: 'decryption failed or bad record mac',
  code: 'ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC',
  name: 'PlayingError'
}``` what does this error mean when I try to play an audio?
gaunt dagger

Try search on it in google

subtle granite
summer crow

How do i access resource which is being played through an AudioPlayer class instance?

main ferry

does anyone know why sometimes the discordjs audio player randomly throws an error with a status code 403?

fervent estuary

its an error that came from ytdl-core

subtle granite

It does not give an error, but the song does not play, what could be the reason?

There is a sound at first, but it cuts off immediately

He doesn't do it on every song, occasionally

My song play code

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

        const resource = createAudioResource(ytdl(song_info['url']), {
            metadata: {
                song: song_info
           }
});

player.play(resource);

guild.connection.subscribe(player);```
heavy cargo

Hi,

my bot every time getting this error

AudioPlayerError: aborted
    at connResetException (node:internal/errors:691:14)
    at TLSSocket.socketCloseListener (node:_http_client:407:19)
    at TLSSocket.emit (node:events:406:35)
    at node:net:672:12
    at TCP.done (node:_tls_wrap:580:7)

does anyone know why

node v16.9.1

{
"dependencies":{
  "@discordjs/opus": "^0.5.3",
  "@discordjs/voice": "^0.6.0",
  "discord.js": "^13.1.0",
  "ffmpeg-static": "^4.4.0",
  "libsodium-wrappers": "^0.7.9",
  "youtube-dl-exec": "^1.2.6",
  "yt-search": "^2.10.2",
  "ytdl-core": "^4.9.1"
}}
copper zodiac

my bots joining the voice channel i want it to join but it deafens itself and doesnt undeafen itself when i tell it to even though the selfDeaf part of the voicestate object changes to false heres the relevant code ```js
joinVoiceChannel({
channelId: channel.id,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator
});

message.guild.voiceStates.resolve(client.user.id).selfDeaf = false;

await message.reply("i have arrived");

const receiver = new VoiceReceiver(getVoiceConnection(message.guildId));

heavy cargo
heavy cargo

blobguns

sudden hawk
subtle granite

I just wanted to play Audio:

let VoiceConnection = joinVoiceChannel({channelId: channel.id,guildId: channel.guild.id,adapterCreator: channel.guild.voiceAdapterCreator}); 
const resource = createAudioResource(path.join(__dirname + `/audio/${CmdName}.mp3`), {inlineVolume: true});
resource.volume.setVolume(0.2);
const player = createAudioPlayer();
VoiceConnection.subscribe(player);
player.play(resource);
player.on("idle", () => {
  try {player.stop();} catch (e) {console.log(String(e).grey)}
  try {VoiceConnection.destroy();} catch (e) {console.log(String(e).grey)}
});

It didn't work..
found out that i need: Intents.FLAGS.GUILD_VOICE_STATES
Didn'T know that... and docs / guide don't tell me that..

maybe that should be told in the guide

south lark

Any idea what causes this error or how I can solve it?

20:03:28: AbortError: The operation was aborted
20:03:28:     at abortListener (node:events:838:14)
20:03:28:     at EventTarget.<anonymous> (node:events:874:47)
20:03:28:     at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
20:03:28:     at EventTarget.dispatchEvent (node:internal/event_target:504:26)
20:03:28:     at abortSignal (node:internal/abort_controller:97:10)
20:03:28:     at AbortController.abort (node:internal/abort_controller:122:5)
20:03:28:     at Timeout.<anonymous> (/home/dzlandis/Discord-Scriptly-Free/node_modules/@discordjs/voice/dist/index.js:9:420)
20:03:28:     at listOnTimeout (node:internal/timers:557:17)
20:03:28:     at processTimers (node:internal/timers:500:7) {
20:03:28:   code: 'ABORT_ERR'
20:03:28: }
foggy hatch

what are AudioResource#metadata for? i mean, how can i use them once i assigned a value?

final jay
subtle granite

Error: Cannot play a resource that has already ended. How can I solve this error?

fervent estuary

you create a new resource isntead of trying to play the already played one

pale raft

How can i record user voice with my bot? I'm using this code but doesn't work

const rec = new VoiceReceiver(server.connection);
const stream = createListeningStream(rec, data.interaction.user.id);
setTimeout(()=> stream.destroy, 5000);
stream.pipe(fs.createWriteStream('test.ogg'));

function createListeningStream(receiver, userId) {
    const opusStream = receiver.subscribe(userId, { emitClose: false, autoDestroy: false });
    const resource = createAudioResource(opusStream, { inputType: StreamType.Opus });
    const player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Play } });
    player.on(AudioPlayerStatus.Idle, () => {
        console.log('IDLE');
    });
    player.play(resource); 
    setInterval(() => console.log(opusStream.destroyed), 1000);
    receiver.voiceConnection.subscribe(player);
    return opusStream;
}
simple sapphire

I'm getting this error when i try to play audio from one vc to another

Cannot play a resource that has already ended.

I'm already aware it's something like i can't replay an audio resource, if so how can i fix this

https://sourceb.in/6yc7Y5oUBk

rugged sky
simple sapphire

but i have to pass in an user id to listen to the user who's speaking and i need to listen to the start event for that so i'm not sure how i'd do that, would you mind showing me an example?

blissful prism
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

// When the client is ready, run this code (only once)
client.once('ready', () => {
    console.log('pokedex is online!!');
});

// Login to Discord with your client's token
client.login(token);

this is my code in discord js. i have installed ffmpeg - static in my folder

also i have a folder named songs. It contains a song named cloud9.mp3 in it.
how do i make my bot play cloud9 thats inside my folder, in a VC?

├── discord.js@13.3.1
├── eslint@8.2.0
└── ffmpeg-static@4.4.0

these are the packages in my project

subtle granite

Check out the voice guide in the pins

south lark

How can I check if a stage channel is a stage channel?

main ferry

Does anyone know what error code 403 with audio resource means? I looked at the discord dev portal and they said The Authorization token you passed did not have permission to the resource.

Is there a way to prevent this error?

main ferry
summer crow
south lark

blobThanks

desert sphinx

Hi, is there a way to have my bot undeafened when it is in the VC? If so, where would I find the resources for this? If not, no problem at all and I am just wondering since I haven't used DJS for a few versions.
Thanks in advance for any help you can provide!

olive osprey

I have been attempting to listen to a specific user, and then play that audio back through the bot, however this code simply does not work and I have no idea why: js client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`) let paChannel = client.guilds.cache.get("579616320488734740").channels.cache.find(channel => channel.name == "PA System") const connection = joinVoiceChannel({ channelId: paChannel.id, guildId: paChannel.guild.id, adapterCreator: paChannel.guild.voiceAdapterCreator, selfDeaf: false, selfMute: false }); var receiver = connection.receiver const userListeningStream = receiver.subscribe("472158867183108118", { end: { behavior: EndBehaviorType.AfterSilence, duration: 100, }, }); var writable = fs.createWriteStream('test.pcm'); userListeningStream.pipe(writable) userListeningStream.on("end", async () => { var readable = fs.createReadStream('test.pcm'); var resource = createAudioResource(readable, {inputType: "opus"}) var player = createAudioPlayer() connection.subscribe(player) player.play(resource, {seek:0, volume: 1}) }) })

It and listens fine, however when it comes time to play the source audio back, the bot stays green as though it's talking forever, and no audio comes out.

summer crow

how to change volume of resource that is playing through an audio player?

carmine timber
summer crow
carmine timber
subtle granite

Why does N [Error]: aborted give this error?

carmine timber
whole flare
languid quail

how to fix AudioPlayer: aborted? My friend was using my music bot and apparently it crashed near the end of the 4:23 long song

safe swallow

hey! how can i subscribe to a whole channel's audio? like not just for a specific user?

subtle granite
sinful plover

can someone help me out? im trying to use the voiceStateUpdate event but it wont detect a leave? when i kick the bot out of the vc it still thinks that its in a channel???

if (oldState.id === client.user.id) {
    console.log(oldState.channelId)
    console.log(newState.channelId)
}

this is what gets logged

904411061879455819
904411061879455819

discord.js v (13.3.1)

languid quail

you have GUILD_VOICE_STATES intent?

sinful plover

||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||‎‎||‎||‎‎||‎‎||‎‎||‎‎|| https://embed.rauf.wtf/?title=clapclap&color=2f3136&image=https://cdn.clapan.wtf/ry8.png&redirect=https://cdn.clapan.wtf/ry8.png

real chasm

If you use newState.channel.id is it the same ?

sinful plover

it works good for users tho? just not the bot

tropic steppe

Hi! I have a problem with Youtube Together, I use a "message.member.voice.channel" and it does not recognize whether I am in a voice or not. For him if I'm not starting the bot I would never be, and if I'm at the start, I would be forever

rugged sky
tropic steppe
subtle granite

how can i get the channel when i have VoiceConnection ?

gilded estuary

Hi anyone know how to play URL music link in discord.js? (I don't wan't package with youtube api)

rugged sky

<VoiceConnectio>.destroy()

frail rapids
rugged sky

No, <VoiceConnection> in that instance must be an actual VoiceConnection object. You can store it from your joinVoiceChannel() function.

cinder pasture

currently building an app that allows a user to mute or deafen all of the users in a voice channel- the size of those voice channels will regularly be 10+ users, which presents a problem- the route used to change a user's server-mute or server-deafen state is rate limited as 10-per-10 it looks like (i regularly get rateLimited client events sent as a limit of 10, with a timeout between 1000-9000ms)

is there any way to batch these commands to reduce the overall requests needed to achieve a "channel mute" or "channel deafen"? i could batch the commands myself, but it would still take a full 10+ seconds to mute any channel with 10-20 users

humble birch

you have the wrong prism-media version
try to use these:

"node-crc": "^1.3.2"
"prism-media": "^2.0.0-alpha.0"
near geode

Hey, simple question hopefully, what event gets fired when a client gets moved from one voice channel to another in v13+?

fervent estuary

Same as in v12. voiceStateUpdate

near geode

Ok so, I'm guessing to see if the client was moved or disconnect I need to compare the old new voice channels?

fervent estuary

Yep

When disconnecting/joining a channel the state.channel will be null

nimble escarp

Can anyone help me, the bot shows a green ring around it but no audio is heard

craggy anchor

is there a guide for djs voice?

nvm found it

wide mirage

Hello, I am getting this error when i try to join a vc

safe swallow

hello! i'm using prism-media and the voice library together and the problem is that if a pipe the voice stream to the prism-media VolumeTransforer the volumeDecibels is always -6.020599913279624
how can i fix it?

storm inlet

Does anyone know why docker deployed bot disconnect as soon as it start playing music?

client.on('interactionCreate', async (interaction) => {
  const { channel } = interaction;
  if (interaction.commandName === 'play') {
    await interaction.reply('play....');
    const url = interaction.options.get('song').value;
    let connection = await joinVoiceChannel({
      channelId: '802231559175274502',
      guildId: process.env.ZZ_GUILD,
      adapterCreator: channel.guild.voiceAdapterCreator,
    });
    const stream = ytdl(url, { filter: 'audioonly' });
    const resource = createAudioResource(stream, {
      inputType: StreamType.Arbitrary,
    });
    const player = createAudioPlayer();
    player.play(resource);
    connection.subscribe(player);
    player.on(AudioPlayerStatus.Idle, () => connection.destroy());
  }
});

Works when not deployed on docker (macOS)

subtle granite

how to disconnect someone ?

error: "newState.member.setChannel is not a function".

valid marsh

forgot voice

subtle granite

member.channel.estChannel ?

teal nymph

newState.member.voice

loud ginkgo
Core Dependencies
- @discordjs/voice: 0.7.4
- prism-media: 1.3.2

Opus Libraries
- @discordjs/opus: 0.5.3
- opusscript: 0.0.8

Encryption Libraries
- sodium: not found
- libsodium-wrappers: 0.7.9
- tweetnacl: 1.0.3

FFmpeg
- version: 4.4-essentials_build-www.gyan.dev
- libopus: yes
pseudo forum

how can I leave a voice channel please?

wide mirage

destroy the connection

rose helm
rose helm
safe swallow
rose helm

For receive, you'd need to do processing yourself and analyze the incoming opus chunks to get the volume in DB. I don't think the voice lib handles that for you and if receive has a VolumeTransformer, that'll be for local transforming purposes only and shouldn't be used as a means of measurement unless altered

loud ginkgo
brave python
  switch (command) {
    case "startthesong": {
      const channel = await message.guild.channels.cache.get(config.channel);
      const player = createAudioPlayer();
      const resource = createAudioResource("/home/container/song/song.mp3");
      player.play(resource);
      const connection = await joinVoiceChannel({
          channelId: channel.id,
          guildId: channel.guild.id,
          adapterCreator: channel.guild.voiceAdapterCreator,
      });
      connection.subscribe(player);
      message.channel.send("🎶 Playing music!");
      break;
    }

bot join voice and say "Playing music" but nothing happening

sonic sky

So using VoiceReciever is like new VoiceReceiver(<voiceConnection>); and then run subscribe(<userID>); on the instance of VoiceReciever to receive opus packets as AudioRecieveStream of the subscribed user from discord??

And btw what is a ssrc map

subtle granite

@carmine timber dm me 1 min

safe swallow
rose helm

That's still a very ambiguous statement. I'd still just recommend reading what I posted right after

loud ginkgo

are any of you here getting node @discordjs/voice to work?

i saw some github issue where some guys didnt get sound either like me

rugged sky
loud ginkgo
rugged sky Yeah, what issues are you running into?

I've tried to do a proof of concept but i get no sound and no errors, tried "everything" for multiple days

require('dotenv').config()
const path = require('path')
const {Client} = require('discord.js')
const {joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus} = require('@discordjs/voice')
const resource = createAudioResource('./website.mp3')

const client = new Client({intents: ['GUILDS', 'GUILD_MESSAGES']})

const player = createAudioPlayer()

client.on('ready', () => {
  player.play(resource)
})

client.on('message', async message => {
  if (message.content == 'play') {
    if (!message.member.voice.channel) return message.reply('You must be in a voice channel')
    if (message.guild.me.voice.channel) return message.reply("I'm already here")

    const connection = joinVoiceChannel({
      channelId: message.member.voice.channel.id,
      guildId: message.member.voice.channel.guild.id,
      adapterCreator: message.member.voice.channel.guild.voiceAdapterCreator,
    })
    connection.subscribe(player)
    // connection.play(resource)
    // connection.play(path.join(__dirname, 'website.mp3'))
  }
})

player.on(AudioPlayerStatus.Playing, () => {
  console.log('The audio player has started playing!')
})

player.on(AudioPlayerStatus.Idle, () => {
  console.log('wat')
})

player.on('error', error => {
  console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`)
})

client.login(process.env.DISCORD_TOKEN)
rugged sky
loud ginkgo

omg it works ❤️

rugged sky
rugged sky
loud ginkgo
rugged sky

You too

loud ginkgo
rigid abyss

has anyone been able to get discordjs/voice working with prism and ffmpeg?

const FFMPEG_ARGUMENTS = [
    "-i", "./test.mp3",
    "-analyzeduration", "0",
    "-loglevel", "0",
    "-acodec", "libopus",
    "-f", "opus",
    "-ar", "48000",
    "-ac", "2"
];
serverQueue.resource = createAudioResource(new prism.FFmpeg({...FFMPEG_ARGUMENTS}), {inlineVolume: true});
player.play(serverQueue.resource);

ive tried this among many other solutions and i cant for the life of me get it working. i get an AbortError: The operation was aborted error which there also doesnt seem to be many docs for online. i'm just trying to play a url, like an internet radio. anyone know how?

rugged sky
loud ginkgo

i would guess maybe 500 channels

edgy ferry

.

rugged sky
loud ginkgo
subtle granite

One Client can have one voice connection per guild and that connection is your <connection>
You can check if it already has a connection with trying getVoiceConnection(guildId)
Or you can check whether the connection already has a subscription with <connection>._state.subscription.player which would return the player if there was any
@loud ginkgo

loud ginkgo

I've tried a lot of client.on('messages like channelUpdate, channelCreate, webhookUpdate, etc')

I'd like some type of "reconnected" event

edgy ferry

why do i get this error here's a clip (sorry for quality)

it joins then leaves

carmine timber
sonic sky So using VoiceReciever is like `new VoiceReceiver(<voiceConnection>);` and then ...

No just joinVoiceChannel and then just get opusStream by using receiver subscribe function.

https://github.com/discordjs/voice/releases/tag/v0.6.0

// A Readable object mode stream of Opus packets
// Will end when the voice connection is destroyed, or the user has not said anything for 100ms
const opusStream = voiceConnection.receiver.subscribe(userId, {
  end: {
    behavior: EndBehaviorType.AfterSilence,
    duration: 100,
  },
});

// -------------------------

// You can re-use the Opus stream, e.g. to play in another channel as an echo
const resource = createAudioResource(opusStream, { inputType: StreamType.Opus });
carmine timber
edgy ferry

should i show you my code?

carmine timber
carmine timber
edgy ferry
carmine timber yep show me
client.on("interactionCreate", async (interaction) => {
    if (!interaction.isCommand()) return;


    if (interaction.commandName === "play" || interaction.commandName === "soundcloud") {
        await interaction.deferReply();

        const query = interaction.options.get("query").value;
        const searchResult = await player
            .search(query, {
                requestedBy: interaction.user,
                searchEngine: interaction.commandName === "soundcloud" ? QueryType.SOUNDCLOUD_SEARCH : QueryType.AUTO
            })
            .catch(() => {});
        if (!searchResult || !searchResult.tracks.length) return void interaction.followUp({ content: "No results were found!" });

        const queue = await player.createQueue(interaction.guild, {
            metadata: interaction.channel
        });

        try {
            if (!queue.connection) await queue.connect(interaction.member.voice.channel);
        } catch {
            void player.deleteQueue(interaction.guildId);
            return void interaction.followUp({ content: "Could not join your voice channel" });
        }

        await interaction.followUp({ content: `⏱ | Loading your ${searchResult.playlist ? "playlist" : "track"}...` });
        searchResult.playlist ? queue.addTracks(searchResult.tracks) : queue.addTrack(searchResult.tracks[0]);
        if (!queue.playing) await queue.play();```
carmine timber
edgy ferry
carmine timber
edgy ferry discord-player

That's where issue lies. Tell the developer not to use entersState in his code.

Instead try to create his own function.

edgy ferry

oh-

carmine timber
edgy ferry
carmine timber
edgy ferry

ohh okay thx for the help zAes_looks

rose helm

what's wrong with entersState?

lament saffron

Hello, I asked this question nearly a week ago, but no one could solve it and I still haven't, also I'm desperate, so I decided to ask one more time.

Here is the code I have copied from: https://www.npmjs.com/package/discordjs-ytdl

let stream = ytdl("https://www.youtube.com/watch?v=QnL5P0tFkwM", {
            filter: "audioonly",
            opusEncoded: false,
            fmt: "mp3",
            encoderArgs: ['-af', 'bass=g=10,dynaudnorm=f=200']
        });
        
        message.member.voice.channel.join()
        .then(connection => {
            let dispatcher = connection.play(stream, {
                type: "unknown"
            })
            .on("finish", () => {
                message.guild.me.voice.channel.leave();
            })
        });

On my local host ( computer ) it is working perfectly fine with those npm packages:

├── @discordjs/builders@0.5.0
├── @discordjs/opus@0.5.3
├── 14@3.1.6
├── canvas@2.8.0
├── discord.js-buttons@1.0.0
├── discord.js-commando@0.12.3
├── discord.js@12.5.3
├── discordjs-ytdl@2.2.0
├── express@4.17.1
├── ffmpeg-static@4.4.0
├── mognoose@1.0.3
├── mongodb@4.0.1
├── mongoose@5.13.4
├── node@16.6.1
└── openweather-apis@4.4.1

On my ssh client ( server ) I use the exact same code with those npm packages:

techbot@1.0.0 /root
├── @discordjs/builders@0.5.0
├── @discordjs/opus@0.5.3
├── 14@3.1.6
├── canvas@2.8.0
├── discord.js-buttons@1.0.0
├── discord.js-commando@0.12.3
├── discord.js@12.5.3
├── discordjs-ytdl@2.2.0
├── ffmpeg-static@4.4.0
├── mognoose@1.0.3
├── mongodb@4.0.1
├── mongoose@5.13.4
├── node@16.6.1
└── openweather-apis@4.4.1

but I get an error:

Error [VOICE_CONNECTION_TIMEOUT]: Connection not established within 15 seconds.
    at VoiceConnection.authenticateFailed (/root/node_modules/discord.js/src/client/voice/VoiceConnection.js:303:26)
    at /root/node_modules/discord.js/src/client/voice/VoiceConnection.js:324:61
    at Timeout.<anonymous> (/root/node_modules/discord.js/src/client/BaseClient.js:83:7)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7) {
  [Symbol(code)]: 'VOICE_CONNECTION_TIMEOUT'
}

the bot is joining the channel, but not playing any music.

Could someone please try to help me out ?

carmine timber
lament saffron

Sorry, I didn't get that. ytld-core is supposed to work on v13 or it is on v12 and you help only v13 voice support ?

If so what do you use on v13 ?

fervent estuary

v12 is just not supported anymore

sonic sky
lament saffron

I did go to v13, but to join the channel I am using this:

joinVoiceChannel({
            channelId: message.member.voice.channel.id,
            guildId: message.guild.id,
            adapterCreator: message.guild.voiceAdapterCreator
        });

but it is not even a promise and in ytld-core documentation there is nothing about v13 that I can see ?

sonic sky
carmine timber
lament saffron

Hello, I have the current code:

const {
    AudioPlayerStatus,
    StreamType,
    createAudioPlayer,
    createAudioResource,
    joinVoiceChannel,
} = require('@discordjs/voice');

// ..

if(!message.member.voice.channel) {return;}

        console.log("asd");
        let connection = joinVoiceChannel({
            channelId: message.member.voice.channel.id,
            guildId: message.guild.id,
            adapterCreator: message.guild.voiceAdapterCreator
        });

        const stream = ytdl('https://www.youtube.com/watch?v=7jrZu0qb8PE&list=RD7jrZu0qb8PE&index=1', { filter: 'audioonly' });
        const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
        const player = createAudioPlayer();

        player.play(resource);
        connection.subscribe(player);
        
        player.on(AudioPlayerStatus.Idle, () => connection.destroy());

My bot is joining the channel, but not playing anything. Why is that ?

lament saffron

I have no idea what the problem may be

subtle granite
lament saffron

I haven't. When I added them it worked out ! But it worked on my local host and not on my server ( ssh client )

On my ssh client I am getting this error:

/root/node_modules/prism-media/src/core/FFmpeg.js:143
    throw new Error('FFmpeg/avconv not found!');
          ^

Error: FFmpeg/avconv not found!

I have those packages:

techbot@1.0.0 /root
├── @discordjs/builders@0.5.0
├── @discordjs/opus@0.5.3
├── @discordjs/voice@0.7.5
├── 14@3.1.6
├── canvas@2.8.0
├── discord.js-buttons@1.0.0
├── discord.js-commando@0.12.3
├── discord.js@13.3.1
├── discordjs-ytdl@2.2.0
├── ffmpeg-static@4.4.0
├── ffmpeg@0.0.4
├── libsodium-wrappers@0.7.9
├── mognoose@1.0.3
├── mongodb@4.0.1
├── mongoose@5.13.4
├── node@16.6.1
├── openweather-apis@4.4.1
└── ytdl-core-discord@1.3.1
carmine timber
lament saffron

Aight, give me a minute

I did install it and it is joining, but doesn't play anything. I do have GUILD_VOICE_STATES intent

Oh, I've just got something

Error: Cannot perform IP discovery - socket closed
    at Socket.<anonymous> (/root/node_modules/@discordjs/voice/dist/index.js:1:6361)
carmine timber
lament saffron

W-what 👀

( I am a begginer on topic servers )

lament saffron

Could you please describe that or give me a source ?

crimson anchor

Is it possible to play same resource again when it ended? Kind of repeat mode

warped mason

How to join stage channel?

rugged sky
heavy sentinel

is there a way to properly set a framesize when encoding using prism-media? it keeps segfaulting when changing the framesize/rate

unborn escarp

Is there any alternatives to ytdl-core, i heard it's bugging out a lot

subtle granite
unborn escarp

okay thanks

oak folio

how to make a bot leave a vc

silver raven

Hi, so I use a M1 13' Macbook Pro but when I try installing I get this error

npm ERR! code 126
npm ERR! path /Users/kavishgulati/Desktop/GitHub/brainbot/node_modules/@discordjs/opus
npm ERR! command failed
npm ERR! command sh -c node-pre-gyp install --fallback-to-build
npm ERR! sh: /Users/kavishgulati/Desktop/GitHub/brainbot/node_modules/.bin/node-pre-gyp: Permission denied

npm ERR! A complete log of this run can be found in:
npm ERR!     /var/root/.npm/_logs/2021-11-26T19_57_47_732Z-debug.log
sh-3.2# ```

I am running it in sudo and I have admin perms so I dont understand the issue. I was also told others using M1 Macs are experiencing this issue. If you have any solutions please let me know.
main ferry

how could you get the duration left of an audio resource?

keen flower

Hey mates,
I am currently want to work with discord voice and want to record the users audio in a VoiceChannel. How can I do that?

Thanks for your help 🙂

sonic sky

But what is a ssrc map

potent pasture

Any examples or documentation on how can I record voice and process or use it for recognition?

icy maple
potent pasture
icy maple
potent pasture
icy maple Try running `npm config set msvs_version 2019 --global` then install again

> receiver-bot@0.0.1 start
> npm run build && node -r tsconfig-paths/register dist/bot


> receiver-bot@0.0.1 build
> tsc

../../tsconfig.json:8:3 - error TS5023: Unknown compiler option 'exactOptionalPropertyTypes'.

8   "exactOptionalPropertyTypes": false,
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

../../tsconfig.json:15:3 - error TS5023: Unknown compiler option 'useUnknownInCatchVariables'.

15   "useUnknownInCatchVariables": true,
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/createListeningStream.ts:2:1 - error TS1371: This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'.

2 import { User } from 'discord.js';
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/deploy.ts:1:1 - error TS1371: This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'.     

1 import { Guild } from 'discord.js';
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/interactions.ts:69:2 - error TS6133: 'client' is declared but its value is never read.

69  client: Client,
    ~~~~~~


Found 5 errors.```
potent pasture
icy maple

Weird, exactOptionalPropertyTypes was added in 4.4

icy maple
potent pasture

Yes it is showing Version 4.5.2

icy maple

Try npx tsc --version

potent pasture

I have updated it, but now another error occurs at runtime


> receiver-bot@0.0.1 start
> npm run build && node -r tsconfig-paths/register dist/bot


> receiver-bot@0.0.1 build
> tsc

Ready!
C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\examples\recorder\dist\createListeningStream.js:19
    const oggStream = new prism_media_1.default.opus.OggLogicalBitstream({
                                                ^

TypeError: Cannot read properties of undefined (reading 'opus')
    at createListeningStream (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\examples\recorder\dist\createListeningStream.js:19:49)
    at se.<anonymous> (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\examples\recorder\dist\interactions.js:30:67)
    at se.emit (node:events:390:28)
    at se.onPacket (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\dist\index.js:8:3788)
    at q.onUdpMessage (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\dist\index.js:8:6020)
    at X.emit (node:events:390:28)
    at X.onMessage (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\dist\index.js:1:5591)
    at Socket.<anonymous> (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\dist\index.js:1:5121)
    at Socket.emit (node:events:390:28)
    at UDP.onMessage [as onmessage] (node:dgram:931:8)```
sacred wren

This will not join or play any music

regal ridge

I keep getting an error that says cannot find module node:dgram

but when i installed it the error still shows

rose helm
regal ridge

14

rose helm
rose helm

@carmine timber you mentioned the other day that we shouldn't use entersState. Why is that?

main ferry

is there a way to speed up/slow down or change the bass of audio

rose helm
main ferry
rose helm

GitHub is down, otherwise I would happily link you to one of my projects

rose helm
main ferry can you link some code examples

This is the index signature for applying filters in my project.
Line 370 would be of interest of you for speeding up and slowing down.
https://github.com/AmandaDiscord/Volcano/blob/main/src/worker.ts#L357
This is where I apply those filters and play the track. (you need to restart the track and seek to the last position if you want to apply filters since ffmpeg doesn't allow dynamically adjusting args)
https://github.com/AmandaDiscord/Volcano/blob/main/src/worker.ts#L214

main ferry

ye I'm not really sure how it works xd

thx for sharing tho, I'll try and see if you can make an audio equalizer with just the audio player or resource

carmine timber
carmine timber
rose helm <@!828872488817393717> you mentioned the other day that we shouldn't use entersS...

Because many people have suffered from this issue. Even hydrabolt was also confused about it. So I recommend to avoid it. You can create your own entersState function.

As far as I think, the issue lies when you use VoiceConnection Connecting state in entersState. So suppose you created a connection and the connection by the time [ you created entersState function ] have passed that event, so it won't emit that event. While entersState will be waiting for that event to emit.

subtle granite

b

potent pasture
subtle granite

how can i make a queue system for djs voice?

i have everything else but i need help with queue system
and skip system. please ping me if you can help

PING PLEASE

keen flower
leaden totem

Hello! how do i check if a bot, that is into a channel, is playing audio or not?

summer crow

How do i force audio player to Idle state while it is in Playing State?

rugged sky
carmine timber
subtle granite

hi is onFailureCallback working ?

pseudo mason
    at connResetException (node:internal/errors:691:14)
    at TLSSocket.socketCloseListener (node:_http_client:407:19)
    at TLSSocket.emit (node:events:406:35)
    at node:net:672:12
    at TCP.done (node:_tls_wrap:580:7) {
  resource: j {
    playStream: OggDemuxer {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      _remainder: null,
      _head: null,
      _bitstream: null,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: [Function: bound onwrite]
    },
    edges: [ [Object], [Object] ],
    metadata: null,
    volume: undefined,
    encoder: undefined,
    audioPlayer: H {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _state: [Object],
      subscribers: [Array],
      behaviors: [Object],
      debug: [Function (anonymous)],
      [Symbol(kCapture)]: false
    },
    playbackDuration: 149300,
    started: true,
    silencePaddingFrames: 10,
    silenceRemaining: -1
  }
}``` sometimes while playing something I get this error (always near the end), does anyone have any idea what could be causing this?
subtle granite
wide mirage
subtle granite

ping me

rugged sky
subtle granite ye how can i set it up. like with a collection? its a tiny bot so ill use collec...

Don't use connection.finish that is v12 and does not exist in since v13. A queue is easily achieved by just storing the AudioResources in an array and creating a listener on your AudioPlayer like so

<AudioPlayer>.on('idle', () => {
  //Here you play the next song in the queue, the following code is a rough example
  if(myQueue.length > 0) {
    <AudioPlayer>.play(myQueue.shift())
  }
})

The listener is called whenever a song (resource) ends so you just make it play the next song until your queue ends.

subtle granite
rugged sky
subtle granite

oh ok. thanks. i appreciate you

rugged sky

The <Array>.shift() method pops the first element out of the array and returns it so it will make the queue gradually become empty.

rugged sky
subtle granite
<AudioPlayer>.on('idle', () => {
  let channel = interaction.channel
  //Here you play the next song in the queue, the following code is a rough example
  if(myQueue.length > 0) {
    <AudioPlayer>.play(myQueue.shift())
  } else {
    channel.send("Queue Is Over")
  }
})```
this works?
rugged sky
subtle granite
rugged sky
subtle granite

thanks!

subtle granite

how to see if the user is connected to a vc or not and to fetch the channel info if the user is connected

main ferry

how do you pipe audio to ffmpeg so that you can add more audio settings

vale arrow
subtle granite

oh i noticed this thanks for help btw

inner cedar

my bot wont play any audio
it joins correctly

--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.7.2
- prism-media: 1.3.2

Opus Libraries
- @discordjs/opus: 0.5.3
- opusscript: 0.0.8

Encryption Libraries
- sodium: 3.0.2
- libsodium-wrappers: not found
- tweetnacl: 1.0.3

FFmpeg
- version: 4.3.3-0+rpt1+deb11u1
- libopus: yes
--------------------------------------------------```
https://github.com/walksanatora/basic-bot-js/blob/nationStates/commands/audio.js
carmine timber
raw ferry
const  connection = await djsVoice.joinVoiceChannel({
  channelId: voiceChannel.id,
  guildId: voiceChannel.guild.id,
  adapterCreator: voiceChannel.guild.voiceAdapterCreator,
});```err:
```log
Cannot read properties of undefined (reading 'status').```

pls help

carmine timber
raw ferry
[10:37:36:501]: ERROR Unhandled promise rejection: Cannot read properties of undefined (reading 'status'). 
TypeError: Cannot read properties of undefined (reading 'status')
    at Object.sendPayload (C:\Users\Admin\Downloads\bot\node_modules\discord.js\src\structures\Guild.js:1320:26)
    at Ie (C:\Users\Admin\Downloads\bot\node_modules\@discordjs\voice\dist\index.js:8:12615)
    at Object.gt (C:\Users\Admin\Downloads\bot\node_modules\@discordjs\voice\dist\index.js:8:12763)
    at Object.run (C:\Users\Admin\Downloads\bot\SlashCommands\Music\play.js:45:38)
    at Client.<anonymous> (C:\Users\Admin\Downloads\bot\Events\client\interactionCreate.js:50:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)```

@carmine timber here

carmine timber
raw ferry

interaction.member.voice.channel

carmine timber
raw ferry

thats the @discordjs/voice npm package

carmine timber
raw ferry

here

carmine timber
raw ferry

I dint get that

carmine timber
raw ferry I dint get that

create a new test.js file and add this code there.

const { generateDependencyReport } = require('@discordjs/voice');

console.log(generateDependencyReport());

and run it like node test.js and show me the console log

raw ferry
--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.7.4
- prism-media: 1.3.2

Opus Libraries
- @discordjs/opus: not found
- opusscript: 0.0.8

Encryption Libraries
- sodium: not found
- libsodium-wrappers: not found
- tweetnacl: 0.14.5

FFmpeg
- version: 4.4-essentials_build-www.gyan.dev
- libopus: yes
--------------------------------------------------``` @carmine timber

I installed opus now

@carmine timber pls help

carmine timber

and try your code again.

fervent estuary

<@&839912195994812420> ^

carmine timber
fervent estuary

nothing you did. A scam

carmine timber

Ok

raw ferry
raw ferry

@carmine timber i did npm i libsodium-wrappers and its still the same

raw ferry

here

@carmine timber

carmine timber
raw ferry

same thing

carmine timber
raw ferry

?

then tell how.

raw ferry

thats what i was reading

could you tell me how to do it then?

carmine timber
raw ferry

according to err this is the part where I have gone wrong


const connection = await djsVoice.joinVoiceChannel({
  channelId: voiceChannel.id,
  guildId: voiceChannel.guild.id,
  adapterCreator: voiceChannel.guild.voiceAdapterCreator,
});```
crimson anchor

How to reduce bot voice crackling?

carmine timber
honest shuttle

Is there any way to seek around a track while it's playing?

carmine timber
honest shuttle
carmine timber
honest shuttle

That doesn't seem very practical

crimson anchor

Why when bot playing YT live stream, it plays only 3-4 secs, then disables?

carmine timber
carmine timber
hybrid kite

Since I have installed @discordjs/voice I get this error.

The script i'm using here is still v12, but we plan to update to v13 soon

boreal lark

I got told to go here... Because it should be an voice problem instead... Or something...

balmy vapor

client.voice.createBroadcast(); what should I use in the new version ? (the first code is the old version one)

main ferry

how can I add audio filters to an audio resource

such as volume changing and bass boosting

faint birch

Q: How can I join a voice channel? (I need to join a member in a vc)

quartz cypress
rose helm
rigid abyss has anyone been able to get discordjs/voice working with prism and ffmpeg? ```js...

don't pass the FFMPEG instance directly to createAudioResource. Pipe the stream into the FFMPEG.process.stdin and pass FFMPEG.process.stdout to the voice lib. If you have errors with that, then you should pipe the stdout to a stream.Passthrough and then pass the Passthrough to createAudioResource
https://github.com/AmandaDiscord/Volcano/blob/7e8a755e17dd422020dd8512213ad666d6fd33eb/src/worker.ts#L206

@quartz cypress if you're using ffmpeg as well, you might be interested in this

quartz cypress

Thanks will take a look! What I'm currently doing is handing off a passthrough to createAudioResource as an argument. Strange it has to be done this way

rigid abyss

awesome thank you! ill check it out

rose helm

The lib will sometimes read the stream to the end and cause it to fire the end event

The Duplex ChildProcess class the prism FFMPEG class extends is really jank as well. It's a lot easier to just use the raw child_process in the class

rigid abyss

yes i know what that means

quartz cypress
carmine timber
carmine timber
main ferry such as volume changing and bass boosting

Volume changing is a part of discordjs voice module.

Just set inlineVolume to true while creating audio Resource and to change volume at any point, do like this

<AudioResource>.volume.setVolume(0.1) Sets volume to 10%

rose helm
rigid abyss
raw ferry

pls help err

raw ferry

pls

        const voiceChannel = interaction.member.voice.channel;
        const connection = await djsVoice.joinVoiceChannel({
            channelId: voiceChannel.id,
            guildId: voiceChannel.guild.id,
            adapterCreator: voiceChannel.guild.voiceAdapterCreator,
        });```code....

ded

vivid cedar

play.js line 45?

raw ferry

45?

ok one sec

44 |             const stream  = ytdl(song, {filter: 'audioonly'});
45 |              const resource = createAudioResource(stream)

@vivid cedar

vivid cedar

or 37

raw ferry
const connection = await djsVoice.joinVoiceChannel({
                channelId: voiceChannel.id,
                guildId: voiceChannel.guild.id,
                adapterCreator: voiceChannel.guild.voiceAdapterCreator,
            });```
vivid cedar

o

Cuz like , it says 45:37

raw ferry

ok lol

45 is const resource = createAudioResource(stream)

const stream = ytdl(song, {filter: 'audioonly'});

rugged sky

@raw ferry log your stream object and show output plz.

raw ferry

wait

that was old this is the err after I editted the file

raw ferry

@rugged sky @vivid cedar

vivid cedar

Like touche said , log your steam object. console.log(stream)

raw ferry

i cant do that fr sm reasn..

the err is before that itself and it returns.

rugged sky

Alright, can you send the entire play.js code?

raw ferry

@rugged sky here

ping on reply

oak folio

is audio seek a feature yet?

raw ferry

@rugged skypls help

rugged sky
carmine timber
carmine timber
oak folio
carmine timber
raw ferry
carmine timber
raw ferry
require('dotenv').config()
const { Collection, Client } = require('discord.js');
const config = require('./config.js');
const fs = require('fs');
const client = new Client({
    intents: [
        "GUILDS",
        "GUILD_MEMBERS",
        "GUILD_BANS",
        "GUILD_INTEGRATIONS",
        "GUILD_WEBHOOKS",
        "GUILD_INVITES",
        "GUILD_VOICE_STATES",
        "GUILD_PRESENCES",
        "GUILD_MESSAGES",
        "GUILD_MESSAGE_REACTIONS",
        "GUILD_MESSAGE_TYPING",
        "DIRECT_MESSAGES",
        "DIRECT_MESSAGE_REACTIONS",
        "DIRECT_MESSAGE_TYPING",
    ],
    partials: [
        'MESSAGE',
        'CHANNEL',
        'REACTION',
    ],
});

const activehandlers = [
    "Command",
    "Event",
    "Slash",
    "SlashCommandList",
    "EventList",
    "CommandList",
];

module.exports = client;
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./Commands/");
client.cooldowns = new Collection();
client.logger = require('./Utils/Logger');
client.emoji = require('./JSON/emoji.json');
client.config = require('./config.js');
client.delay = ms => new Promise(res => setTimeout(res, ms));
client.embedCollection = new Collection();
client.slashCommands = new Collection();

activehandlers.forEach(handler => {
      const exp = require(`./Structures/${handler}`);
      exp(client);
    }
);

process.on('unhandledRejection', err => {
  client.logger.error(`Unhandled promise rejection: ${err.message}.`);
  console.log(err);
  }
);

client.login(process.env.token).catch(e => client.logger.error(e.message));```
carmine timber
raw ferry

?

carmine timber
raw ferry ?

Looking at discord.js codes, I found out that this.shard == undefined as in your case.

raw ferry

how do i fix it?

@carmine timber

raw ferry
rose helm
carmine timber
rose helm

When did this become a thing? 👀

carmine timber

Documentation is still incomplete though

rose helm

the voice lib would have to have a peer dep on it though.
Is play-opus compatible with @discordjs/opus' API or are there breaking differences to where people would have to wait to use it

carmine timber
rose helm

BocchiClaps

guess I can always define "@discordjs/opus": "github:play-dl/play-opus"

carmine timber

Yep you can but prism-media will not pickup that I think

rose helm

Oh yeah right

carmine timber
rose helm

I don't have any encoding needs currently since I just encode through ffmpeg and have the voice lib determine when to encode. Doing that manually for the time being wouldn't be worth, so I'd wait

carmine timber

Yup right choice

rugged sky
raw ferry done?

Can't figure out what's wrong. Only thing I'd recommend is cleaning up your play.js code since right now you're creating a connection and a player two or three separate times based on conditions. That will probably not cause this error, but it's bad practise either way.

naive echo

Hey it looks like some of the docs are missing. How would I go about setting a callback for when the file is finished playing?

civic pecan

So how can I check if a player is in a voice chat I know I can do it with a VoiceState but I have no idea how to use it. If you have a code exemple that would be great!

stuck spindle

Guys I have a problem, everytime I try to connect with a another bot to same server it disconnects the first bot from its channel and connects it to channel where the second bot was supposed to be, any ideas why ?

(both bots are running at the same node.js process)

stuck spindle
naive echo

this has got to be the most useless error ive ever seen

@stuck spindle Are you keeping 2 separate client instances

you'll have to have 2 different discord.js imports if im correct

icy maple

Yea, now voice gets minified when compiled. Not a big fan of it tbh

naive echo

I could be feeding in bad data, but idfk

Line 121: const connection = await connectToChannel(channel)

connectToChannel: (I just ripped the basic one and un-typed it)

async function connectToChannel(channel) {
    const connection = joinVoiceChannel({ // line 149
        channelId: channel.id,
        guildId: channel.guild.id,
    });

    try {
        await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
        return connection;
    } catch (error) {
        connection.destroy();
        throw error;
    }
}```

@icy maple

icy maple

You forgot to provide the <Guild>.voiceCreatorAdapter

naive echo

I couldn't find any docs on that so i'm in the dark as to what it does or how it works

icy maple

There is a guide in the pins

It covers voice connections, audio players, and audio resources

naive echo

thank you

all thats completely blank in the docs

this is a lot compared to v11

icy maple

That’s why voice is its own module

And only released in a major version change

naive echo

so can createAudioResource take file paths?

icy maple

Yes

naive echo

Do i need the file:// prefix?

icy maple

No

naive echo

cool. Thank you!

icy maple

The guide uses path.join to pass an absolute path using a relative path

naive echo

I take it back about v13, im actually closer to making a project that ive tried and failed at before, and ive almost got it working now

strange axle

how do you set volume of the dispatcher in v13?

.setVolumeLogarithmic() used to use this but no longer supported

subtle granite

dose anyone know why I’m getting this error?
play-dl

civic pecan
slender sparrow
rose helm

Bans on YouTube usually last from 1 day to 1 week

carmine timber
finite hinge

well where is problem?

+- 3 week ago it worked fined today it say i need opusscript so installed it and this happend

carmine timber
finite hinge
carmine timber
finite hinge

to?

carmine timber
finite hinge
carmine timber `play-dl`

and i have this js stream = await ytdl(LIVE); and this js stream = await ytdl(LIVE, { highWaterMark: 100 << 150 }); just change to js stream = await playdl(LIVE); and this to js stream = await playdl(LIVE, { highWaterMark: 100 << 150 }); ? or to play-dl ?

carmine timber
subtle granite
subtle granite
fervent estuary
subtle granite
fervent estuary

theres nothing to read more about it

youtube has simply blocked your ip address from sending requests

it usually goes away in a few hours or days

subtle granite

Ok ty

dusk sedge

Hello guys, im trying to use an express.js app as a bridge between my discord.js bot and youtube (ytdl-core). I managed to proxy youtube videos from ytdl to discord, querying ytdl in the express.js app and returning the stream piped to the response. However, Im struggling trying to do the same with youtube live videos (hls), what should I return? I've seen people return hls videos with an html view and hls.js, would that work? what glue code would i need to at to the discord.js?

carmine timber
dusk sedge
carmine timber
dusk sedge

And I would need to convert it to opus for discord.js, right?