#archive-voice

30636 messages · Page 7 of 31

bold cairn

Is there anything like that?

bold cairn

lol, it's literally .joinable

teal marten

how to join voice channel, this doesn't work:

if (message.content === 'join') {
         if (message.member.voice.channel) {
            const connection = await message.member.voice.channel.join();
         } else {
            message.reply('You need to join a voice channel first!');
         }
      }
icy maple
teal marten

Thanks

icy maple

And make sure to enable the GUILD_VOICE_STATES intent

teal marten

Yes

Discord js v13 like, Discord js v12 dislike )))

teal marten

how to connect to the voice channel

joinVoiceChannel() dosen't work

whole inlet

<VoiceChannel>.join()?

icy maple
icy maple
whole inlet
teal marten

Nothing happens

if (message.content == "jointest") {
         const connection = joinVoiceChannel({
            channelId: message.channel.id,
            guildId: message.channel.guild.id,
            adapterCreator: message.channel.guild.voiceAdapterCreator,
         });
      }
icy maple

It’s prob not running then

What message are you sending?

teal marten
icy maple

Log message.content before the if statement, and a different log inside

teal marten

from the pinned message in this channel, it is a little unclear how to make the bot connect to the voice channel

icy maple

Did you add the logs and retest yet?

teal marten

?

icy maple

Log message.content before the if statement, and a different log inside

teal marten

testing

Code:

if (message.content == "jointest") {
         const connection = joinVoiceChannel({
            channelId: message.channel.id,
            guildId: message.channel.guild.id,
            adapterCreator: message.channel.guild.voiceAdapterCreator,
         });
         console.log(connection)
      }

Log:

VoiceConnection {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  debug: null,
  rejoinAttempts: 0,
  onNetworkingClose: [Function: bound onNetworkingClose],
  onNetworkingStateChange: [Function: bound onNetworkingStateChange],
  onNetworkingError: [Function: bound onNetworkingError],
  onNetworkingDebug: [Function: bound onNetworkingDebug],
  _state: {
    status: 'signalling',
    adapter: {
      sendPayload: [Function: sendPayload],
      destroy: [Function: destroy]
    }
  },
  packets: { server: undefined, state: undefined },
  joinConfig: {
    selfDeaf: true,
    selfMute: false,
    group: 'default',
    channelId: '870800077357219870',
    guildId: '839607527460044860',
    adapterCreator: [Function (anonymous)]
  },
  [Symbol(kCapture)]: false
}
icy maple

Should prob use await enterState(…) and wait for ready to make sure the bot actually connects

teal marten

enterState?

teal marten

ReferenceError: player is not defined

player.on(AudioPlayerStatus.Playing, (oldState, newState) => {
            console.log('Audio player is in the Playing state!');
         }); 

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

icy maple

You can view the other sections of the guide using the hamburger menu in the top right

keen flume

this happens when i follow the guide and i have NO CLUE on what this error means

spare wave

^ Just ignore it for now, it a typing discrepancy between discord.js newest commit against voice module. @keen flume

keen flume

ty

i still seem to get this issue though

spare wave

It's more to TS compiling when there is error it stop compile, not really sure how to disable it, gotta ask ts user. But supposedly it should working.

keen flume

so i have this code, but the connection never gets destroyed! there are no logs printed afterwards and i want to know how i would fix this

cold geode

Cannot play audio as no valid encryption package is installed

empty torrent
cold geode

How can I add FFMPEG config?

const resource = createAudioResource(ytdl(song.url, options), { inputType: StreamType.Opus });

const options = {
    opusEncoded: true,
    filter: 'audioonly',
    quality: 'highestaudio',
    highWaterMark: 1 << 25,
    encoderArgs: 'asetrate=48000*1.25,aresample=48000,bass=g=5',
    dlChunkSize: 0
}

P.S. This is not worked :(

cold geode

Guys, help, pls

subtle granite

Can we stream video? Or that is still imporssible?

cold geode

Sorry, no

onyx moss

does anyone happen to know the new way of which to change the volume (when the audio is already playing)?

cold geode

Getting <AudioResource> and change <AudioResource>.volume

P.S. Not worked.

carmine timber
lost oyster

What's the reason for AudioPlayerError: Status code: 403? It seems to happen randomly when music is playing. Internet has been stable (that's the only answer I've found so far).
Regardless, how do I handle this error? The bot refuses to play anything or even leave voice channels unless I completely restart the client

knotty socket

Ok. I added that. The player don't get random event.autopause but the sound still stop randomly. I try use

player.stop(true);
connection.dispatchAudio()
connection.disconnect();
connection.destroy();```
 But get a error notice me: "*Connection cannot be destroy because is destroyed*" and the bot still appear online into the `voicechannel` but no streaming. If I kick/disconnect the bot from the channel and sending a new songURL; the bot will be connect to the voiceChannel again and continue playing the last "stoped" song. 

Why the connection autodestroyed? 
What is the code to send a disconnect the bot if connection was destroy and bot not leave from the channel?
muted remnant

how to stop bot from playing music and leave vc

carmine timber
knotty socket Ok. I added that. The `player` don't get random `event.autopause` but the sound ...

Ok, so basically stopping the player like this might create issue as silence frames are not played and this might be create issue in Discord API itself as it requires some silence packets to be passed before stopping

So use player.stop() without any Boolean and remove connection.dispatchAudio() .

So before attempting below steps make sure you are on voice 0.5.5 and latest dev build of discord.js.

I want to check what is going with your bot so attach event listeners to following:

connection.on('debug' ,(message) => {
      console.log(`===================== Voice Connection ===================== \n${message}`)
})

connection.on('error', (error) => {
    console.log(`===================== Error : Voice Connection ===================== \n${error}`)
})

player.on('error', (error) => {
    console.log(`===================== Error : Audio Player ===================== \n${error}`)
})

player.on('debug', (message) => {
    console.log(`===================== Voice Player ===================== \n${message}`)
})

carmine timber
carmine timber
lost oyster
carmine timber
muted remnant
cold geode

TypeError [ERR_INVALID_ARG_TYPE]: The "source" argument must be of type function or an instance of Stream, Iterable, or AsyncIterable. Received undefined
How I can fix this error?

empty torrent

Please send the full log and code generating the error.

rustic carbon

Hi people, do you know how to get the id of the channel where the bot is connected on guild ?

cold geode
empty torrent Please send the full log and code generating the error.

Error:

Error: write EPIPE
    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:94:16)
Emitted 'error' event on FFmpeg instance at:
    at FFmpeg.onerror (internal/streams/readable.js:760:14)
    at FFmpeg.emit (events.js:315:20)
    at Socket.processError (/root/tests/dpm_test/node_modules/prism-media/src/core/FFmpeg.js:65:40)
    at Socket.emit (events.js:315:20)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}

Code:

function createStream(url, type, mode, options) {
    let FFmpegArgs;

    switch(mode) {
        case '1': {
            const inputStream = ytdl(url, options);
            FFmpegArgs = [ '-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5', '-i', url, '-analyzeduration', '0', '-loglevel', '0', '-f', options && options.format && typeof options.format === 'string' ? options.format : 's16le', '-ar', '48000', '-ac', '2' ];

            FFmpegArgs.concat(options.filters);

            let transcoder = new prism.FFmpeg({ shell: false, args: FFmpegArgs });
            const output = inputStream.pipe(transcoder);

            if(options && !options.opusEncoded) {
                for(const event of events) {
                    inputStream.on(event, (...args) => output.emit(event, ...args));
                }

                inputStream.on('error', error => transcoder.destroy(error));
                output.on('close', () => transcoder.destroy());
                console.log(output)
                return output;
            }

            const opus = new prism.opus.Encoder({ rate: 48000, channels: 2, frameSize: 960 });
            const outputStream = output.pipe(opus);

            for (const event of events) {
                inputStream.on(event, (...args) => outputStream.emit(event, ...args));
            }

            const _destroy = error => {
                if (!transcoder.destroyed)
                    transcoder.destroy();
                if (!opus.destroyed)
                    opus.destroy();
            }

            outputStream.on('close', _destroy).on('error', _destroy);
            console.log(outputStream)
            return outputStream;
        }

        case '2': {
            //
        }
    }
}
const connection = getVoiceConnection(guild.id);
const stream = ytdl(song.url, 'Raw', '2', { type: '', opusEncoded: true, filter: 'audioonly', format: '', filters: queue.filter, dlChunkSize: 0 })
const resource = createAudioResource(stream, { inputType: StreamType.Raw, inlineVolume: true });

this.audio.play(resource);
connection.subscribe(this.audio);

P.S. I'm currently testing 1, but the error write EPIPE and the one that was thrown on the server discord.js. createStream() = ytdl(). Discord.js v13

narrow jetty

How can I play audio in specific channel?

umbral gyro

Hewwo. Since there's @discordjs/voice, do I need @discordjs/opus anymore?

spare wave
umbral gyro

Oh ok

carmine timber
cold geode Error: ```JS Error: write EPIPE at WriteWrap.onWriteComplete [as oncomplete]...

You are providing FFMPEG with url (youtube) and at same time, piping another stream into ffmpeg. I think you need to learn how things work in ytdl and ffmpeg before creating any more code.

const { FFmpeg } = require('prism-media')

function filter(format) {
    var results = []
    format.forEach((ele) => {
        if(ele.codecs === 'opus' && ele.container === 'webm' && ele.audioSampleRate === '48000' && ele.audioQuality === 'AUDIO_QUALITY_MEDIUM'){
            results.push(ele)
        }
    })
    return results
}
//Put these at top

async function createStream(url, type, mode, options) {
    let FFmpegArgs;

    switch(mode) {
        case '1': {
            const inputURL = await ytdl.getInfo(url);
            const FFMPEG_OPUS_ARGUMENTS = [
        '-analyzeduration',
        '0',
        '-loglevel',
        '0',
        '-acodec',
        'libopus',
        '-f',
        'opus',
        '-ar',
        '48000',
        '-ac',
        '2',
          ];
          var filtered_url = filter(inputURL.formats)[0].url
          var output = new FFmpeg({
          args : ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5', '-i', filtered_url, ...FFMPEG_OPUS_ARGUMENTS]
})
        return output;
        case '2': {
            //
        }
    }
}
digital girder

?stage

bronze swanBOT

Stage channels support has not landed on a stable release yet
• update to v12.5.3 to prevent hard crashes npm i discord.js@​​​​​​​​​​​​latest
• check for voice channels to exist whenever you are trying to use them.
• you can check out pins in #djs-help-v14 to test the development build

subtle granite

Hello, to play music in the voice channel, I need to install one of the next libraries: sodium, tweetnacl or libsodium-wrappers. But I can't install them. Can someone help me with that? I'll send error log in next file.

Sodium:

Tweetnacl

Libsodium wrapper

steel crescent

The problem actually lies with erlpack here

So just uninstall that

subtle granite

ok

thx, it works <3

brazen peak

is there an event like speaking on voiceConnection@djs12?

brazen peak

is audio receiver automatically get data from speaking users?

cold geode

How I can fix this error?
(node:1977295) UnhandledPromiseRejectionWarning: TypeError: adapterCreator is not a function

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

npm list @discordjs/voice ??

cold geode
subtle granite

what has message.guild.me.voice.channel.leave
changed to?

cold geode

Main question. <AudioPlayer> needs to be created separately for each server, yeah?

undone epoch

how do i make the bot join a voice channel and create a connection?

subtle granite
brazen peak

joinVoiceChannel will returns voice connection

then you could just call disconnect from it

subtle granite

ah ty, i was just trying to make if command === 'disconnect' then disconnect from vc

rustic carbon

Does anyone know what the startime alternative is?

forest topaz

Is there an option to make the bot appear as if it's speaking all the time? (ie not stop speaking when the audio resource playing finishes)

ah I figured it out - set the silencePaddingFrames on your audio resource to 0

subtle granite
soft talon

help?....

any one?

unkempt aurora

Hi how to make the music bot to join stage channel..

rustic carbon
subtle granite

Hi, has new voice module something like seek option?

subtle granite

thx

calm steeple

How can i understand that the audio player has finished the song?

subtle granite

state changes to idle
there should be a section about this in the guide

calm steeple
subtle granite
calm steeple

subscribe new resource

and i restart vs code and fixed now

subtle granite

👍

calm steeple
        player.on('stateChange', (oldState, newState) => {
          console.log(`Audio player transitioned from ${oldState.status} to ${newState.status}`);
        });
``` and if someone needs help about stateChange thats code may help
teal marten

how to join a voice channel?
interaction.member.voice.channel.join not working

red nest

How to make a nowplaying command?

@discordjs/voice removed streamTime and pauseTime

red nest

Oh bruh I saw it

elfin lynx

how can i play 1 file at one guild at a time ?

hm

i know how to make the bot join the channel, but idk how to make the bot play music from a file

old:

connection.play(`./assets/playdata/${fileName}`, { volume: volume });
red nest

How to join stage Channel and play music 🤔

oh I get it

unkempt aurora

Can anyone tell me how to make a bot to play songs on stages?

empty torrent

What should i do so the bot instantly leaves VC after i restart/re-deploy the bot?

carmine timber
carmine timber
carmine timber
empty torrent
carmine timber

Okay

empty torrent
carmine timber
empty torrent
carmine timber
empty torrent

I know, i had a filter in which i did -
If there is a stageInstance already created then there was no suppress method. If not then setSuppressed. Had to modify that.

carmine timber

Ok 👍

carmine timber
empty torrent

I made the client to have admin perms by default.

All done. Thank you very much for your help!

empty torrent
carmine timber
empty torrent

Hmm. I hope they are available on message soon as i can’t get them if i’m doing interaction.send.

empty torrent

I am trying to do all the song play updates (eg. onStart, onFinish, onError etc) on a single message by editing it. If i do interaction#reply(), i can’t edit that reply anymore after 15 mins due do discord limitations but that’s not enough as the queue list exceeds song’s length of 15 mins easily.

soft talon

how can i make my bot join a vc?

proud spindle
empty torrent
empty torrent
little berry

I'm trying to play a song using youtube-dl-exec and prism-media, but no sound is playing for some reason. Here is my code: https://sourceb.in/b2xOm3VuPx

brisk aspen

Im trying to get voice connections with this method

client.voice.connections.size```

its worked for me in v12 has the method been changed?
subtle granite

today i´ve tried to port my whole bot to v13 since i was really looking forward to use threads. But after spending most of the day on voice section, i was not able to play any sound. Even both examples are not working.

floral cloak

What would be the best way to get a number of people that are in a VC with the bot globally?

bright quartz

I'm using the example in the Github for testing, and I'm not sure why but the Connection state is still signalling, it is fine and connected when i tried to connect to vc with normal Discord, not for bot.

carmine timber
bright quartz

Oh, was it Intents problem? It rings a bell when you said that

bright quartz
carmine timber
bright quartz
carmine timber

👍

carmine timber
carmine timber
carmine timber

No problem 😄

floral cloak
carmine timber No problem 😄

Had a bit of an issue with it
(node:9832) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'members' of null

Is there an intent I need to enable or is it a code error?

ripe orchid

if the bot isnt in a vc voice.channel will be null

carmine timber
floral cloak

seems to just print out null now Thonk

will keep looking

carmine timber
floral cloak

total_members

carmine timber
floral cloak

great question tbh,

ive got it running on an express web server. it prints 0 before the bot starts, after its started it prints out null

carmine timber

So let me check and tell you the results.

floral cloak

Sounds good, appreciate it 🙂

alright so i console logged it, it returns the 0 from the end of the statement on all of them or undefined on others

floral cloak
carmine timber
carmine timber
floral cloak aha, got it with .size instead of .length

I prefer you do this, rather than size :

let total_members = 0
client.guilds.cache.forEach((guild) => {
      if(guild.me.voice?.channel){
      guild.me.voice.channel.members.each((member) => {
          if(member.id !== client.user.id) total_members++
          else return
      })
      }
})

It will just only count no of members excluding your own bot

floral cloak

you my friend are an absolute legend, tysm ♥️

carmine timber

No problem

edgy beacon

Anyone know why this doesn't work? The bot doesn't connect to voice channel with no error.

if (interaction.commandName === 'music') {
        await interaction.reply('노래를 틀어드릴게요')
        const connection = await voice.joinVoiceChannel({
            channelID: interaction.member.voice.channel.id,
            guildId: interaction.guild.id,
            adapterCreator: interaction.guild.voiceAdapterCreator,
        })
        connection.on(voice.VoiceConnectionStatus.Ready, () => {
            console.log('The connection has entered the Ready state - ready to play audio!');
        });```
edgy beacon

The Debug Log says that the bot closed because of unknown opcode

carmine timber
edgy beacon

And I don't know what to do

I did what the thread said and nothing has been changed

neon ibex
dusky hatch
    at new VoiceConnection (C:\Users\Julian\Documents\Discord Bots\TheFirstBot\node_modules\@discordjs\voice\dist\VoiceConnection.js:74:25)
    at Object.createVoiceConnection (C:\Users\Julian\Documents\Discord Bots\TheFirstBot\node_modules\@discordjs\voice\dist\VoiceConnection.js:480:29)
    at joinVoiceChannel (C:\Users\Julian\Documents\Discord Bots\TheFirstBot\node_modules\@discordjs\voice\dist\joinVoiceChannel.js:18:30)

what the

edgy beacon
neon ibex

한국분 맞으셨구나 ㅋㅋ

dusky hatch
honest shuttle

Is it just me or are the createAudioResourceOptions missing from the docs

honest shuttle

There doesn't seem to be many, based on the examples. But still.

carmine timber
honest shuttle

i needed the input type

Found it in an example.

carmine timber
honest shuttle

Yeah i wanted to see the options but figured the types existed in the module.

soft talon

how to undefine my bot plz help

brisk aspen
edgy beacon
soft talon

in vc

subtle granite
wispy junco

how to make bot speaker when join stage channel

carmine timber
brisk aspen

Ight

soft talon

how my bot can talk

        const player = createAudioPlayer();
        const resource = createAudioResource('C:/Users/נעים/Documents/INBAR/musicmp3/help.mp3');
        //player.play(resource);
        const { AudioPlayerStatus, entersState } = require('@discordjs/voice');
        async function start() {
            player.play(resource);
            try {
                await entersState(player, AudioPlayerStatus.Playing, 1_000);
                // The player has entered the Playing state within 5 seconds
                console.log('Playback has started!');
            } catch (error) {
                // The player has not entered the Playing state and either:
                // 1) The 'error' event has been emitted and should be handled
                // 2) 5 seconds have passed
                console.error(error);
            }
        }
        //Discord.voiceState.setSuppressed(true);

        void start();

this is my code this is not working
help

solemn current

how to use filters pn my bot?

soft talon

@eager lake
help?...

eager lake

?r6

bronze swanBOT

6. Do not mention or DM individual members just for help. You may not get a reply quickly, if at all. Post your question in the public channels where more people can see it.

soft talon

oops sorry

solemn current
soft talon
carmine timber
wispy junco
      oldVoice.guild.me.voice.setSuppressed(false);         }
```                                                                                                                                        why channel type is return null
lapis vortex

oldVoice.channel.type
hmm...

cosmic prawn

how do i end the current song which is playing
before it was like connection.dispatcher.end();
please help

cosmic prawn

oh, so it will end the whole current song and not all ?

neon ibex

yes maybe same behavior as dispatcher.end() (v12)

cosmic prawn

oh, okay, trying

neon ibex

good!

cosmic prawn

yeah, thank you, it worked perfectly


The connection has entered the Ready state - ready to play audio!
Audio player transitioned from buffering to playing
Audio player transitioned from playing to idle
Connection transitioned from ready to ready
Audio player transitioned from buffering to playing
Audio player transitioned from playing to idle
Connection transitioned from ready to destroyed
Connection transitioned from ready to destroyed
The connection is destroyed
neon ibex

:)

quick fjord

can someone help me? My bot doesn't get all the members in one voice.Like 2 members but it only get 1

little berry
verbal moth

what is djs new voice ?

warm field
if(oldVoice.channel.type === "GUILD_STAGE_VOICE"){
  	oldVoice.guild.me.voice.setSuppressed(false);

}
honest shuttle

Can i access AudioPlayer properties and methods from a subscribed connection?

honest shuttle

The guide is using connection.pause(), but doesn't show the context, e.g. what does the connection variable represent

honest shuttle
honest shuttle

I am looking at making a separate command for pausing and unpausing and would prefer avoiding having to export the player, or the subscription.

solemn current

idk

clear bridge

Does type: 'voice', still work in v13?

When creating a channel? Idk if this is the right channel to ask

meager river

Does anyone know why joinVoiceChannel() isn't working? I am sending it the right Voice Channel/Guild ID and the voiceAdapterCreator.

honest shuttle
meager river
olive musk

hmm may i know what's this error Error: Did not enter state ready within 30000ms

olive musk

huh

carmine timber
olive musk

wdym

carmine timber
olive musk
carmine timber

Add one more intent : Intents.FLAGS.GUILD_VOICE_STATE

olive musk

ok

olive musk
carmine timber
olive musk
carmine timber
olive musk
carmine timber code please
async function connectToChannel(channel) {

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

    try {

        await entersState(connection, VoiceConnectionStatus.Ready,30000);

        return connection;
    } catch (error) {
      console.log(error)
    }
}
  await connectToChannel(vc)```
carmine timber
carmine timber
olive musk

yes

lament sail

How to get my bot join stage Channel

merry parcel
carmine timber
olive musk

but cannot play audio

carmine timber
carmine timber
merry parcel
let err = new MessageEmbed().setAuthor("You must to be in a voice channel to use that command" , "http://assets.stickpng.com/thumbs/5a5798809538462e5a82d431.png").setColor("RED")
    if(!message.member.voice.channel /*|| !message.member.stage.channel*/) return message.channel.send({ embeds: [err] })
    if(message.guild.me.voice.channel && message.guild.me.voice.channel == message.member.voice.channel) 
      return message.channel.send('', { embeds: [err = err.setAuthor("I am already in your voice channel!" , "http://assets.stickpng.com/thumbs/5a5798809538462e5a82d431.png")] })
    
    let conn = await message.member.voice.channel.join() /*|| await message.member.stage.channel.join();*/
    message.channel.send("🎶 Joined and ready for disco");
olive musk
carmine timber Show me playing code
  const stream = ytdlCore('youtube_video_url', { filter: 'audioonly' }); //ytdl-core
    const audio = createAudioResource(stream, {
        inputType: StreamType.Arbitrary,
    });// idk how but doesn't require this on v12
const player = createAudioPlayer(); 

   player.play(audio);
//msg.guild.me.voice.setSuppressed(false);
   await entersState(player, AudioPlayerStatus.Playing, 5e3);```
**everything is working fine on v12 but i have to update the code to v13**
i've defined everything and i assume that you've know what that is
carmine timber
lament sail
carmine timber
carmine timber
olive musk
merry parcel

Hey @carmine timber not worked

Now my code is this ```js
let err = new MessageEmbed().setAuthor("You must to be in a voice channel to use that command" , "http://assets.stickpng.com/thumbs/5a5798809538462e5a82d431.png").setColor("RED")
if(!message.member.voice.channel) return message.channel.send({ embeds: [err] })
if(message.guild.me.voice.channel && message.guild.me.voice.channel == message.member.voice.channel)
return message.channel.send({ embeds: [err = err.setAuthor("I am already in your voice channel!" , "http://assets.stickpng.com/thumbs/5a5798809538462e5a82d431.png")] })

await message.member.voice.channel.join()
message.channel.send("🎶 Joined and ready for disco");
carmine timber
carmine timber
olive musk

@carmine timber hmm not working i got this error ```js
Error: Did not enter state ready within 30000ms

and TypeError: Cannot read property 'subscribe' of undefined

merry parcel

Thx @carmine timber I changed my code like this and it worked

carmine timber
olive musk

ahh i guess you'll have to see this lol ```js
async function play(client ,msg, ...args) {
const vc = msg.member.voice.channel;
async function connectToChannel(channel) {

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

try {

    await entersState(connection, VoiceConnectionStatus.Ready,30000);

    return connection;
} catch (error) {
  console.log(error)
}

}
const connection = await connectToChannel(vc)
const video = await findVideo(args.join(' '));
const player = createAudioPlayer();
if (video) {
const stream = downloadYT(video.url, { filter: 'audioonly' });
const audio = createAudioResource(stream, {
inputType: StreamType.Arbitrary,
});

 await connectToChannel(vc)

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

msg.guild.me.voice.setSuppressed(false);
await entersState(player, AudioPlayerStatus.Playing, 5e3);

await msg.reply(`Now playing \`${video.title}\`.`);

} else {
await msg.reply(No results found.);
}
}

@carmine timber

carmine timber

You are running connect to channel twice.

Remove Connect to channel from here :

     await connectToChannel(vc)
   player.play(audio);
warm field

how to make bot speaker when join stage channel

I am getting eror

olive musk

hmm idk why but i've made some changes @carmine timber ```js
async function play(client, msg, ...args) {
//const vc = msg.member.voice.channel;
const connection = joinVoiceChannel({
channelId: '872642620457906236',
guildId: '818300592610476093',
adapterCreator: msg.guild.voiceAdapterCreator,
});
async function connectToChannel(channel) {
await entersState(connection, VoiceConnectionStatus.Ready);
return connection;
}

msg.guild.me.voice.setSuppressed(false);
const connect = getVoiceConnection('818300592610476093')
const video = await findVideo(args.join(' '));
await connectToChannel(client.channels.cache.get('818300592610476093'));
if (video) {
try{
const stream = downloadYT(video.url, { filter: 'audioonly' });
const player = createAudioPlayer();
player.play(stream, { seek: 0, volume: 1 });
connect.subscribe(player);

await msg.reply(`Now playing \`${video.title}\`.`);
}catch(e){
  console.log(e)
}

} else {
await msg.reply(No results found.);
}
}

dusty needleBOT

Documentation suggestion for @warm field:
djsatdev VoiceState#setSuppressed()
Suppress/unsuppress the user. Only applicable for stage channels.

olive musk
carmine timber
olive musk

got the [Symbol(code)]: 'VOICE_NOT_STAGE_CHANNEL' and Error: Did not enter state ready within undefinedms error

olive musk
carmine timber
carmine timber
olive musk
carmine timber
olive musk hmm idk why but i've made some changes <@!828872488817393717> ```js async funct...

Change this to :

async function play(client, msg, ...args) {
  //const vc = msg.member.voice.channel;
const connection = joinVoiceChannel({
        channelId: '872642620457906236',
        guildId: '818300592610476093',
        adapterCreator: msg.guild.voiceAdapterCreator,
    });
   async function connectToChannel(connection ,channel) {
        await entersState(connection, VoiceConnectionStatus.Ready, 30000);
        return connection;
}

if(msg.guild.me.voice.channel.type === 'GUILD_STAGE_VOICE'){msg.guild.me.voice.setSuppressed(false);}
  const video = await findVideo(args.join(' '));
await connectToChannel(connection ,client.channels.cache.get('818300592610476093'));
  if (video) {
    try{
    const stream = downloadYT(video.url, { filter: 'audioonly' });
    const player = createAudioPlayer();
    player.play(stream, { seek: 0, volume: 1 });
    connection.subscribe(player);

    await msg.reply(`Now playing \`${video.title}\`.`);
    }catch(e){
      console.log(e)
    }
  } else  {
    await msg.reply(`No results found.`);
  }
}
olive musk

hmm it didn't play and i got this error ```TypeError: Cannot read property 'once' of undefined

@carmine timber
carmine timber
olive musk
carmine timber
olive musk
carmine timber
olive musk

lts

carmine timber

Not a djs error anymore

olive musk

hmm but its working well on djsv12

carmine timber
olive musk

their dependencies were out of date but nvm i'll give it a try

@carmine timber still getting the same error

carmine timber
olive musk
carmine timber
olive musk

@carmine timber

carmine timber
olive musk

umm

carmine timber
olive musk

no lol

olive musk
carmine timber

XD

olive musk

@carmine timber js TypeError: Cannot read property 'type' of null at play (/home/runner/commands.js:28:31) at Client.<anonymous> (/home/runner/index.js:69:12) at Client.emit (node:events:377:35) at MessageCreateAction.handle (/home/runner/node_modules/discord.js/src/client/actions/MessageCreate.js:23:14) at Object.module.exports [as MESSAGE_CREATE] (/home/runner/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32) at WebSocketManager.handlePacket (/home/runner/node_modules/discord.js/src/client/websocket/WebSocketManager.js:345:31) at WebSocketShard.onPacket (/home/runner/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)

carmine timber
carmine timber
olive musk
carmine timber
olive musk
carmine timber Show me play function
async function play(client, msg, ...args) {
  //const vc = msg.member.voice.channel;
const connection = joinVoiceChannel({
        channelId: '872642620457906236',
        guildId: '818300592610476093',
        adapterCreator: msg.guild.voiceAdapterCreator,
    });
   async function connectToChannel(connection ,channel) {
        await entersState(connection, VoiceConnectionStatus.Ready, 30000);
        return connection;
}

if(msg.guild.me.voice?.channel?.type === 'GUILD_STAGE_VOICE'){msg.guild.me.voice.setSuppressed(false);}
  const video = await findVideo(args.join(' '));
await connectToChannel(connection ,client.channels.cache.get('872642620457906236'));
  if (video) {
    try{
    const stream = downloadYT(video.url);
    const player = createAudioPlayer();
    player.play(stream);
    connection.subscribe(player);

    await msg.reply(`Now playing \`${video.title}\`.`);
    }catch(e){
      console.log(e)
    }
  } else  {
    await msg.reply(`No results found.`);
  }
}
carmine timber
carmine timber
olive musk nope still not working

After this line : const player = createAudioPlayer();

add this line : player.on('debug', (msg) => console.log(msg))

Then show me console logs

olive musk

@carmine timber from {"status":"idle","resource":false,"stepTimeout":false} to {"status":"buffering","resource":true,"stepTimeout":false}

olive musk

hmm nothing

carmine timber

After buffering, Nothing ??

olive musk

ye

carmine timber

Interesting

olive musk
carmine timber
olive musk

yes

async function play(client, msg, ...args) {
  //const vc = msg.member.voice.channel;
const connection = joinVoiceChannel({
        channelId: '872642620457906236',
        guildId: '818300592610476093',
        adapterCreator: msg.guild.voiceAdapterCreator,
    });
   async function connectToChannel(connection ,channel) {
        await entersState(connection, VoiceConnectionStatus.Ready, 30000);
        return connection;
}

//if(msg.guild.me.voice?.channel?.type === 'GUILD_STAGE_VOICE'){
//}
  const video = await findVideo(args.join(' '));
await connectToChannel(connection ,client.channels.cache.get('872642620457906236'));
  msg.guild.me.voice.setSuppressed(false);

  if (video) {
    try{
const stream = downloadYT(video.url, { filter: 'audioonly' });
    const player = createAudioPlayer();
    player.on('debug', (msg) => console.log(msg))
    player.play(stream);
    connection.subscribe(player);

    await msg.reply(`Now playing \`${video.title}\`.`);
    }catch(e){
      console.log(e)
    }
  } else  {
    await msg.reply(`No results found.`);
  }
}
carmine timber
olive musk

um ytdl-core-discord

carmine timber
olive musk ```js async function play(client, msg, ...args) { //const vc = msg.member.voic...

I forgot, you didn't create audio resource

OMG

Make sure to get createAudioResource and StreamType from voice module

Change code to this :

async function play(client, msg, ...args) {
  //const vc = msg.member.voice.channel;
const connection = joinVoiceChannel({
        channelId: '872642620457906236',
        guildId: '818300592610476093',
        adapterCreator: msg.guild.voiceAdapterCreator,
    });
   async function connectToChannel(connection ,channel) {
        await entersState(connection, VoiceConnectionStatus.Ready, 30000);
        return connection;
}

//if(msg.guild.me.voice?.channel?.type === 'GUILD_STAGE_VOICE'){
//}
  const video = await findVideo(args.join(' '));
await connectToChannel(connection ,client.channels.cache.get('872642620457906236'));
  msg.guild.me.voice.setSuppressed(false);

  if (video) {
    try{
    const stream = downloadYT(video.url);
    const player = createAudioPlayer();
    let resource = createAudioResource(stream, { inputType : StreamType.Opus })
    player.on('debug', (msg) => console.log(msg))
    player.play(resource);
    connection.subscribe(player);

    await msg.reply(`Now playing \`${video.title}\`.`);
    }catch(e){
      console.log(e)
    }
  } else  {
    await msg.reply(`No results found.`);
  }
}

Sorry my bad @olive musk , Change this :

player.play(resource)
carmine timber
olive musk
carmine timber
olive musk
carmine timber

So change @olive musk to this & try again :

const stream = await downloadYT(video.url);

@olive musk Worked ??

olive musk

@carmine timber didn't work 😢

carmine timber

Errors ??? and player logs

olive musk

no error, player log state change: from {"status":"idle","resource":false,"stepTimeout":false} to {"status":"buffering","resource":true,"stepTimeout":false}

fervent estuary

so your audioPlayer just gets stuck at buffering?

olive musk

everything seems to be working fine on djsv12 but when it comes to v13 i'm literately confused

carmine timber
fervent estuary

can you try smth for me?

olive musk

we've been doing this for hours

olive musk
fervent estuary

in ur node_modules navigate to the discordjs/voice source

fervent estuary

so full path would be node_modules/@discordjs/voice/dist/audio/AudioResouce.js

open that file

olive musk

alright, now ?

fervent estuary

replace lines 40-42 with this.playStream.once('readable', () => (this.started = true));

see if that fixes ur problem

olive musk

hmm still didn't work

fervent estuary

so the player still just stays buffering?

olive musk

yeah pretty much the same state change: from {"status":"idle","resource":false,"stepTimeout":false} to {"status":"buffering","resource":true,"stepTimeout":false}

fervent estuary

ic

try listening for AudioResouce.playStream readable event

see if that fires

carmine timber
fervent estuary

use an once listener preferrably

olive musk

lol the time i coded in v12 it took me like 1 hours and for now just to change it to v13 i spend like 6 hours lol

fervent estuary
carmine timber

Yes

fervent estuary

that shouldnt be possible

the playStream is always a readable stream

fervent estuary

ok thats weird

can you just send your current play function code?

fervent estuary

yeah i just saw that. If possible id like to see the current one

@olive musk can you do this?

carmine timber

@olive musk play function code ??

olive musk

huh

warm field

@fervent estuary

how to make bot speaker when It join stage channel


let stage = oldVoice.guild.me.voice


if(stage.channelId){
    
let id =client.channels.cache.get(stage.channelId)    

if(id.type === "GUILD_STAGE_VOICE"){

oldVoice.guild.me.voice.setSuppressed(false) 
}   
    
}
fervent estuary
olive musk
olive musk
fervent estuary can you send your current play function?
async function play(client, msg, ...args) {
  //const vc = msg.member.voice.channel;
const connection = joinVoiceChannel({
        channelId: '872642620457906236',
        guildId: '818300592610476093',
        adapterCreator: msg.guild.voiceAdapterCreator,
    });
   async function connectToChannel(connection ,channel) {
        await entersState(connection, VoiceConnectionStatus.Ready, 30000);
        return connection;
}

//if(msg.guild.me.voice?.channel?.type === 'GUILD_STAGE_VOICE'){
//}
  const video = await findVideo(args.join(' '));
await connectToChannel(connection ,client.channels.cache.get('872642620457906236'));
  msg.guild.me.voice.setSuppressed(false);

  if (video) {
    try{
    const stream = await downloadYT(video.url);
    const player = createAudioPlayer();
    console.log(stream)
    let resource = createAudioResource(stream, { inputType : StreamType.Opus })
    player.on('debug', (msg) => console.log(msg))
player.play(resource)
    connection.subscribe(player);

    await msg.reply(`Now playing \`${video.title}\`.`);
    }catch(e){
      console.log(e)
    }
  } else  {
    await msg.reply(`No results found.`);
  }
}```

i don't think something went wrong with other packages i think @discordjs/voice causes the issue

also i commented
//if(msg.guild.me.voice?.channel?.type === 'GUILD_STAGE_VOICE'){ //} this cuz it just stop the bot to become a speaker

carmine timber

@olive musk

Create a new file (let's name it as test.js)

Add this in there

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

console.log(generateDependencyReport());

Then do node test.js

olive musk

sure

@fervent estuary ```

Core Dependencies

  • @discordjs/voice: 0.5.5
  • prism-media: 1.3.1

Opus Libraries

  • @discordjs/opus: 0.5.3
  • opusscript: 0.0.8

Encryption Libraries

  • sodium: not found
  • libsodium-wrappers: not found
  • tweetnacl: not found

FFmpeg

carmine timber
olive musk

i mean like i don't have python 3 installed, wait its an npm

carmine timber
olive musk

i'm just confused, why discordjs decided to separate voice with discordjs

carmine timber
fervent estuary

actually it wont

carmine timber

Oh that's weird

carmine timber
olive musk
carmine timber
olive musk

an object

olive musk
carmine timber

Ok I understand

fervent estuary

can u listen to a few events on that. readable, close, end and error

for readable i recommend using a once listener as otherwise ur console will get flooded with logs

olive musk
fervent estuary

this is for the stream you got from downloadYT()

not resouce.playStream

olive musk
fervent estuary

listen for those events on stream

olive musk

ya but it will say .once is not a function

fervent estuary

and just log something to console that tells u which events fired

on stream?

olive musk

you mean client.stream ?

fervent estuary

no

i mean the stream you have there

const stream = await downloadYT(video.url);

olive musk

oh, it returns an object

slender sparrow
olive musk

i don't think there's any event or stuff

fervent estuary

what editor are you using?

also if theres no event stuff on that id guess thats the problem

olive musk
fervent estuary

ok...

so what is downloadYT()?

can you show where that is defined

olive musk

downloadYT is actually a node module ( ytdl-core-discord )

last time i was using ytdl-core and it works fine

honest shuttle
fervent estuary

ytdl-core-discord returns an opus stream

so that has events on it

olive musk

but @fervent estuary i do see this in the object _events: [Object: null prototype] { prefinish: [Function: prefinish], close: [ [Function (anonymous)], [Function: onclose], [Function] ], end: [Function: onend], finish: [ [Function: onfinish], [Function] ], error: [ [Function: onerror], [Function: onerror] ], unpipe: [Function: onunpipe] },

fervent estuary

yeah thats an event emitter

olive musk

so just log them all

fervent estuary

sure

olive musk

wait how do i listen to the events ? TypeError: stream._events is not a function

fervent estuary

stream.on(...)

just like any other events

olive musk

and inside the function ?

fervent estuary

id assume you know how listening to evnets works at this point...

olive musk

okay

hmm is this how i listen to events ? stream.on('finish', msg => console.log)

fervent estuary

there are no parameters in the finish event

also u arent calling the console.log properly

olive musk

uh but none of them works

olive musk
fervent estuary

stream.on("event name", () => console.log("event fired!"));

olive musk

nope didn't work stream.on('prefinish', msg => { console.log(msg) })

fervent estuary

msg is not a parameter there

its going to be undefined

olive musk

oh wait then what am i suppose to log ?

fervent estuary

a string that lets you know which event it was that fired

olive musk

like the event didn't fire at all, basically all of them

fervent estuary

yes they dont until the stream ends

olive musk

i mean like i have all the events on and they're not firing

fervent estuary

see if readable event fires

olive musk
fervent estuary

Ok thats good

olive musk

fun fact : it fires after the player's debug event

fervent estuary

So if u do resource.playStream.one(...) does it work?

See if readable fires there

fervent estuary

Do it right after you create the resource

olive musk

define nothing inside the function?

fervent estuary

Do the same thing u did for the stream readable event

Just chnage what it logs so u know its from the resouce

fervent estuary

Dont log exactly the same string as u did from the stream.on readable

olive musk

oh like other events ?, they all aren't going to fire lol

olive musk
fervent estuary

So does resource.playStream readable event fire?

warped egret

how to join a vc through this package?
the channels.cache.get().join() won't work

nvm found

olive musk

should i do resource.playStream() only ?

fervent estuary

Thats not a function

And its once not one

warped egret

eh?

fervent estuary

Try re-installing

warped egret

oh, ok

same err

olive musk
fervent estuary Thats not a function

hmm i think i need to define something but what should i define ```TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received undefined
{
code: 'ERR_INVALID_ARG_TYPE'
}

warped egret

this is right, right?

olive musk
warped egret

oh

fervent estuary
warped egret
olive musk
fervent estuary

resource.playStream.on(...

warped egret

wait can i not use the module for js?

fervent estuary

U can

Which npm and nodejs version are u on btw?

olive musk
fervent estuary

Still

fervent estuary
warped egret

idk let me check

7.9.0

fervent estuary

Seems alright

warped egret

=\

carmine timber
warped egret

oh

rustic belfry

how to make the bot joins vc

warped egret

yeah the index.js file is missing

olive musk
rustic belfry
warped egret

my bot's?

rustic belfry

yes and ig you need index.js

warped egret

my bot's package.json is correct

meager river

I am trying to use joinVoiceChannel() but it's not joining the channel even though I am giving it the id of vc id of guild and the voiceadapter

carmine timber
rustic belfry

how to make the bot joins vc

meager river

my bot won't even join vc idk why

rustic belfry

idk how to make the bot joins vc

burnt hull

hi

Is it possible to make a bot that has a voice chat recording feature?

fervent estuary
burnt hull

What api can you rely on

fervent estuary

Do u still have the fix implemented i instructed about earlier?

olive musk
fervent estuary

U still got the fix i told about before implemented?

fervent estuary

The first one. Where u changed that listener within node_modules

sly bear

Hey

fervent estuary

And the audioPlayer still just got stuck at buffering?

olive musk

yeah

sly bear

so how do i make my bot join a voice channel it is so confusing

olive musk
fervent estuary
olive musk yeah

Did the readable event fire after or before the state change from idle to buffering

meager river

dude at this point I would get farther smashing me head into my keyboard. I can't get my bot to join the vc.

fervent estuary
meager river

@sly bear do you have the GUILD_VOICE_STATES intent?

olive musk

damn look at how long i've spend on this

meager river

same

sly bear

what do i even do to make my bot join the vc , in v12 it was so easy ffs

fervent estuary

Read the documentation

sly bear

i did]

fervent estuary

So whats the problem?

short fulcrum
fervent estuary
olive musk
fervent estuary

Is that all u got?

olive musk

ye

fervent estuary

Looks like its slighly different to what i got. For me the AudioPlayer state went from buffering to buffering

Tho that might be related to how my player system handles timeouts etc

Tbh i really dont have a solution for u now

If possible try it with ytdl-core or youtube-dl instead of ytdl-core-discord

Unfortunately i dont rly have time to assist you further now

olive musk

me too, i'm so sick of this now LOL but thanks for helping

rustic belfry
olive musk

@carmine timber you too, thanks

rustic belfry
burnt hull

Is it possible to make a bot that has a voice chat recording feature?؟؟؟؟

fervent estuary

Yes

VoiceReceiving docs are still a wip tho

burnt hull
fervent estuary

I havent experimented with it yet

Id just suggest u take a look at djs/voice code and trial and error from that

fervent estuary

Just look at the repo

burnt hull
meager river

I am getting error 4001

carmine timber
meager river
try{
    console.log(generateDependencyReport())
    const connection = joinVoiceChannel({
        channelID: voice_channel.id,
        guildID: voice_channel.guild.id,
        adapterCreator: voice_channel.guild.voiceAdapterCreator,
    });
    await entersState(connection, VoiceConnectionStatus.Ready, 10000);
    queue_constructor.connection = connection;
    video_player(interaction.guild, queue_constructor.songs[0]);
} catch (err) {
    queue.delete(interaction.guild.id);
    interaction.channel.send('There was an error connecting!');
    throw err;
}
carmine timber
meager river

const voice_channel = interaction.member.voice.channel;

my bot isn't joining the channel at all

carmine timber
carmine timber
carmine timber
meager river

this is the output:

Preparing to connect to the gateway...
[WS => Manager] Fetched Gateway Information
    URL: wss://gateway.discord.gg
    Recommended Shards: 1
[WS => Manager] Session Limit Information
    Total: 1000
    Remaining: 974
[WS => Manager] Spawning shards: 0
[WS => Shard 0] [CONNECT]
    Gateway    : wss://gateway.discord.gg/
    Version    : 9
    Encoding   : json
    Compression: none
[WS => Shard 0] Setting a HELLO timeout for 20s.
[WS => Shard 0] [CONNECTED] Took 193ms
[WS => Shard 0] Clearing the HELLO timeout.
[WS => Shard 0] Setting a heartbeat interval for 41250ms.
[WS => Shard 0] [IDENTIFY] Shard 0/1 with intents: 641
[WS => Shard 0] [READY] Session 68361649e0712f1dc0148aca7e0db43a.
[WS => Shard 0] [ReadyHeartbeat] Sending a heartbeat.
[WS => Shard 0] Shard received all its guilds. Marking as fully ready.
Ready!
[WS => Shard 0] Heartbeat acknowledged, latency of 54ms.
Montero
869188941591490603
869188940924588043
[Function (anonymous)]
--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.5.5
- prism-media: 1.3.1

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

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

FFmpeg
- version: 4.4-essentials_build-www.gyan.dev
- libopus: yes
--------------------------------------------------
VoiceConnection {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  debug: null,
  rejoinAttempts: 0,
  onNetworkingClose: [Function: bound onNetworkingClose],
  onNetworkingStateChange: [Function: bound onNetworkingStateChange],
  onNetworkingError: [Function: bound onNetworkingError],
  onNetworkingDebug: [Function: bound onNetworkingDebug],
  _state: {
    status: 'signalling',
    adapter: {
      sendPayload: [Function: sendPayload],
      destroy: [Function: destroy]
    }
  },
  packets: { server: undefined, state: undefined },
  joinConfig: {
    selfDeaf: true,
    selfMute: false,
    group: 'default',
    channelID: '869188941591490603',
    guildID: '869188940924588043',
    adapterCreator: [Function (anonymous)]
  },
  [Symbol(kCapture)]: false
}
[WS => Shard 0] [CLOSE]
    Event Code: 4001
    Clean     : true
    Reason    : Unknown opcode.
[WS => Shard 0] Clearing the heartbeat interval.
[WS => Shard 0] Session id is present, attempting an immediate reconnect...
[WS => Shard 0] A connection object was found. Cleaning up before continuing.
    State: CLOSED
[WS => Shard 0] [DESTROY]
    Close Code    : 1000
    Reset         : false
    Emit DESTROYED: false
[WS => Shard 0] WS State: CLOSED
[WS => Shard 0] [CONNECT]
    Gateway    : wss://gateway.discord.gg/
    Version    : 9
    Encoding   : json
    Compression: none
[WS => Shard 0] Setting a HELLO timeout for 20s.
[WS => Shard 0] [CONNECTED] Took 240ms
[WS => Shard 0] Clearing the HELLO timeout.
[WS => Shard 0] Setting a heartbeat interval for 41250ms.
[WS => Shard 0] [RESUME] Session 68361649e0712f1dc0148aca7e0db43a, sequence 3
[WS => Shard 0] [INVALID SESSION] Resumable: false.
[WS => Shard 0] Failed to connect to the gateway, requeueing...
[WS => Manager] Shard Queue Size: 1; continuing in 5 seconds...
[WS => Shard 0] An open connection was found, attempting an immediate identify.
[WS => Shard 0] [IDENTIFY] Shard 0/1 with intents: 641
[WS => Shard 0] [READY] Session 5408435bd02192883f43d2feb7257a18.
[WS => Shard 0] [ReadyHeartbeat] Sending a heartbeat.
[WS => Shard 0] Shard received all its guilds. Marking as fully ready.
[WS => Shard 0] Heartbeat acknowledged, latency of 59ms.
Error: Did not enter state ready within 10000ms
calm steeple

do you have "GUILD_VOICE_STATES" in your client intents?

meager river

yes

carmine timber
meager river
const { Client, Collection, Intents } = require('discord.js');

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

Can you send the full thing (minus tokens)?

@meager river Like this one :

meager river

ok

carmine timber
meager river
{
  op: 4,
  d: {
    guild_id: undefined,
    channel_id: undefined,
    self_deaf: true,
    self_mute: false
  }
}
{
  op: 6,
  d: {
    token: '*********************',
    session_id: '90477da46f2e6a2de589bdfeabdc4d1e',
    seq: 3
  }
}
{
  op: 2,
  d: {
    large_threshold: 50,
    compress: false,
    properties: {
      '$os': 'win32',
      '$browser': 'discord.js',
      '$device': 'discord.js'
    },
    version: 9,
    presence: { activities: [], afk: false, since: null, status: 'online' },
    intents: 641,
    token: '*************************',
    shard: [ 0, 1 ]
  }
}
{ op: 1, d: -1 }

This?

carmine timber

So channel ID and guild ID are both undefined which causes error.

carmine timber
meager river

do you want me to send my whole play command? it's badly written but you might be able to see the issue.

meager river

discord messed up the indentation

knotty socket

@carmine timber Hi. How to 'destroy' or 'Stop' a entersState without connection argument?

meager river
wispy junco

VOICE STATE UPDATE event is looping how to solve

fervent estuary

Dont let it loop?

carmine timber
robust knot

var voiceChannel = message.guild.channels.cache.get("842859974324518913");
if(voiceChannel.members.size > 0){
voiceChannel.join().then(connection =>{
const dispatcher = connection.play('audios/private.mp3');
dispatcher.on("end", end => {
voiceChannel.leave();
});
}).catch(err => console.log(err));
}else{
message.channel.send("Nessuno è presente nel canale");
}
In this piece of code the bot should leave the channel at the end of the mp3, but it doesn't and I don't understand why

carmine timber
flat vector

Hi,
I'm having trouble updating my bot to v13. I'm trying to play a sound in a voice channel in reaction to a slash command.
The player goes from Idle to Buffering, then from buffering to Playing state, but instantly goes back to idle state. No sound is played in the voice channel.
Does anybody have a hint on what I'm doing wrong ?

meager river

Anyone else having trouble with ytdl-core crashing bot? The stream seems to error.

flat vector

My play command handler

edgy beacon

What is aborted error? I was playing audio with ytdl-core-discord and the bot suddenly stopped with aborted error.

knotty socket
rare gale

(node:17412) UnhandledPromiseRejectionWarning: TypeError: interaction.member.voice.channel.join is not a function

spare wave
edgy beacon
spare wave

Then try this js Ytdl(link, { filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1048576 * 32 });

highWatermark there is 32mb

edgy beacon

Is that ytdl-core or ytdl-core-discord?

spare wave

Both can use it because both still use ytdl-core

edgy beacon

Ok, I will try it

rare cosmos

bruh i cant even get my bot to join a channel XD

exotic valley
rare cosmos

how do i get my bot to join a vc? :P

exotic valley

check the pins for guide

rare cosmos

ive already done that bruv

exotic valley

then just ask it and provide all the resources so that we can help you

rare cosmos

-_-

how do i get my bot to join a vc there isnt any resources to provide

its a question

solar crypt

so for example,


vc.joinVoiceChannel({channelId: vcid, guildId: guildId})```
Or something like that, u need to specify client somewhere XD
rare cosmos

wdym specify client

i have

const connection = joinVoiceChannel({
    channelID: channel.id,
    guildID: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
});
solar crypt
rare cosmos

:C

solar crypt
rare cosmos

nope

solar crypt
rare cosmos nope

Have u installed all required packages? (from @discordjs/voice dependencies tab in readme)

rare cosmos

let me check

yes

solar crypt
rare cosmos

error: Did not enter state ready within 10000ms

solar crypt
rare cosmos

i have 32767

solar crypt

But what 32767? XD

rare cosmos

xD

{ intents: 32767 }

solar crypt

Oh, this way xD

rare cosmos

xdddd

solar crypt
rare cosmos

just all? xd

solar crypt

Yes, that will give your bot the best functionality XD
intents: "GUILD", "GUILD_MEMBERS", etc, etc

rare cosmos

nothing new

:/

I could not join the voice channel: Did not enter state ready within 10000ms

solar crypt

Whats your channel variable?
Textchannel or voicechannel?
@rare cosmos

rare cosmos

voicechannel

message.member.voice

meager river
rare cosmos
solar crypt

That's a problem!
Use message.member.voice.channel (add .channel after voice) @rare cosmos

rare cosmos

ok

solar crypt

Working? xD

rare cosmos

so basically message.member.voice.channel.id

@solar crypt

solar crypt

const channel = message.member.voice.channel

And then connection
channelId: channel.id
guildId: channel.guild.id
adapterCreator: channel.guild.voiceAdapterCreator

Or message.guild instead of channel.guild, your choice xD

rare cosmos

ok

I could not join the voice channel: Did not enter state ready within 10000ms

solar crypt

Uhm

Try console.log(channel)
And send result

rare cosmos
<ref *2> VoiceChannel {
  type: 'GUILD_VOICE',
  deleted: false,
  guild: <ref *1> Guild {
    id: '810560593491656784',
    name: '឵឵',
    icon: 'a_fbe3319a6e6704e3bebb683f665e65b2',
    features: [
      'THREADS_ENABLED',
      'PRIVATE_THREADS',
      'THREE_DAY_THREAD_ARCHIVE',
      'VANITY_URL',
      'BANNER',
      'SEVEN_DAY_THREAD_ARCHIVE',
      'NEWS',
      'COMMUNITY',
      'INVITE_SPLASH',
      'ANIMATED_ICON'
    ],
    commands: GuildApplicationCommandManager {
      permissions: [ApplicationCommandPermissionsManager],
      guild: [Circular *1]
    },
    members: GuildMemberManager { guild: [Circular *1] },
    channels: GuildChannelManager { guild: [Circular *1] },
    bans: GuildBanManager { guild: [Circular *1] },
    roles: RoleManager { guild: [Circular *1] },
    presences: PresenceManager {},
    voiceStates: VoiceStateManager { guild: [Circular *1] },
    stageInstances: StageInstanceManager { guild: [Circular *1] },
    invites: GuildInviteManager { guild: [Circular *1] },
    deleted: false,
    available: true,
    shardId: 0,
    splash: '180d9a3aa1de304528258981b913ebe7',
    banner: 'a7a729b29e19c93c1e0253c9b2f95724',
    description: null,
    verificationLevel: 'LOW',
    vanityURLCode: 'kim',
    nsfwLevel: 'DEFAULT',
    discoverySplash: null,
    memberCount: 143,
    large: true,
    applicationId: null,
    afkTimeout: 900,
    afkChannelId: null,
    systemChannelId: '810567542757785621',
    premiumTier: 'TIER_3',
    premiumSubscriptionCount: 30,
    explicitContentFilter: 'ALL_MEMBERS',
    mfaLevel: 'NONE',
    joinedTimestamp: 1613323160969,
    defaultMessageNotifications: 'ONLY_MENTIONS',
    systemChannelFlags: SystemChannelFlags { bitfield: 1 },
    maximumMembers: 100000,
    maximumPresences: null,
    approximateMemberCount: null,
    approximatePresenceCount: null,
    vanityURLUses: null,
    rulesChannelId: '835538707058130964',
    publicUpdatesChannelId: '810567190612410368',
    preferredLocale: 'en-US',
    ownerId: '293022381021069312',
    emojis: GuildEmojiManager { guild: [Circular *1] },
    stickers: GuildStickerManager { guild: [Circular *1] }
  },
  guildId: '810560593491656784',
  parentId: '810560593694031876',
  permissionOverwrites: PermissionOverwriteManager { channel: [Circular *2] },
  id: '848233629939400705',
  name: 'public ²',
  rawPosition: 3,
  rtcRegion: null,
  bitrate: 64000,
  userLimit: 99
}

:P

solar crypt
rare cosmos

ig so xd

whole flare

How do I change the volume of my resource? When I try ```js
myresource.volume.setVolumeLogarithmic(3 / 10);

TypeError: Cannot read property 'setVolumeLogarithmic' of undefined

solar crypt
rare cosmos

wut :d

solar crypt

channelID => channelId
guildID => guildId

solar crypt
rare cosmos

ok basically it works now but it doesnt play music :P

and its taking really long to join the channel

solar crypt
rare cosmos
            const stream = ytdl(song.url, {filter: 'audioonly'});
            const player = createAudioPlayer();
            let resource = createAudioResource(stream, { inputType: StreamType.Opus });
            player.play(resource);
            queue.connection.subscribe(player);
solar crypt
rare cosmos

i dont have any errors

solar crypt

Uhm

rare cosmos
solar crypt

Oh okay... But have u got aby queue.set in code?

rare cosmos

wut?

solar crypt

client.queue.set(something)
Have u got something like that?

rare cosmos

yes

client.queue = new Map(); is in index

solar crypt

Try changing inputType from StreamType.Opus to StreamType.Arbitrary

rare cosmos

it works :DDDDDDDDDDDDD

solar crypt

Nice :D

rare cosmos

ty so much

solar crypt

np 👍

neon ibex

When my bot with music function is running for about 48 hours, it seems that memory leaks occur due to numerous PipeWraps (about 100) as shown in the picture below. Is there a good solution or cause analysis?

spare wave

Using ytdl? You can diagnose memory with process.memoryUsage().heapUsed

neon ibex

I already restarted the bot so failed to measure the load. :(

spare wave

I'm not very sure how to handle memory with ytdl-core, I have use youtube-dl-exec and no memory leak etc so far

neon ibex

upper pic is after 48hours.
Big pupple area is JSArrayBufferData

neon ibex
spare wave

Mostly this when I use youtube-dl-exec, it goes up and down a bit, not just static 17mb

neon ibex

Thank you for your advice :)

Shoud I create a AudioResource as an example source of the voice module?

autumn pebble

can someone tell me why guildvoiceAdapterCreator is not assignable to voiceAdapterCreator in joinvoicechannel function

carmine timber
carmine timber
carmine timber
autumn pebble
carmine timber
autumn pebble
exotic valley
carmine timber

@vocal valley Free ?? Thought of alternatives ??

vocal valley

This weekend 👀

carmine timber

Okay 👍

subtle granite

If i want my bot to ONLY join/leave a voice channel and NOT talk/receive, do i still need @discordjs/voice?

because is the voice adapter just the audio or also the join/leave mechanism?

btw this is for mass vc move command

vocal valley

do you even need to join the vc at all if you're only moving other people @subtle granite?

subtle granite

How im implementing it yes i want to

merry parcel
   let connection = await joinVoiceChannel({
        channelId: interaction.member.voice.channelId,
        guildId: interaction.guild.id,
        adapterCreator: interaction.guild.guildvoiceAdapterCreator,
        selfDeaf: false
      });
(node:4974) UnhandledPromiseRejectionWarning: TypeError: adapterCreator is not a function
rare cosmos

TypeError: queue.connection.stop is not a function

why do i get this error?

fervent estuary

youre trying to stop a voice connection?

tough flame

is there a way to change voice channels without initiating another( destroying the old voiceConnection then creating a new one )

fervent estuary

unfortunately not

u will have to obtain a new voiceConnection and destroy the old one

tough flame

thanks

carmine timber
fervent estuary

id destroy it to be on the safe side

but it should switch automatically

tough flame

i was asking it for a implementation on the music-bot example and i implemented it like this its hacky but it works:

molten merlin

how can join to voice channel in v13

misty saddle

StageChannel.createStageInstance({ topic:"Something" , privacyLevel: "GUILD_ONLY" } ) isn't creating any instance , any solution ?

carmine timber
knotty socket
olive summit
subtle granite someone???

i don't think there's a way to join a voice channel without @discordjs/voice. though if you're not gonna play any audio you won't have to install an encoding library or ffmpeg probably

knotty socket
const process = ytdl(url, {
            o: '-',
            q: '',
            f: 'bestaudio[ext=webm+acodec=opus+asr=44100]/bestaudio',
            r: '64K',
          // ->Not work-> 'postprocessor-args': ['-af', 'bass=g=9,loudnorm=i=-16,aecho=0.8:0.9:1000|1800:0.3|0.25'],
        }, { stdio: ['ignore', 'pipe', 'ignore'], maxBuffer :  4e9 });

How to add ffmpeg filter options (['-af', 'bass=g=9,loudnorm=i=-16]) to youtube-dl-exec?

olive summit

i'm running into a weird error using a PassThrough stream as an AudioResource. it works and plays audio just fine unless I run connection.destroy() , then it throws Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close. it's not much of an issue since that's only run when i need the bot to leave the voice channel, which it does, but is there anything i'm doing wrong here?

subtle granite
TypeError: voiceChannel.join is not a function
    at run (D:\Nodejs_workspace\Soundy Studios\Events\message.js:66:53)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
D:\Nodejs_workspace\Soundy Studios\node_modules\discord.js\src\rest\RequestHandler.js:298
      throw new DiscordAPIError(data, res.status, request);
            ^

DiscordAPIError: Cannot send an empty message
    at RequestHandler.execute (D:\Nodejs_workspace\Soundy Studios\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (D:\Nodejs_workspace\Soundy Studios\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
    at async TextChannel.send (D:\Nodejs_workspace\Soundy Studios\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:171:15) {
  method: 'post',
  path: '/channels/861355381774221312/messages',
  code: 50006,
  httpStatus: 400,
  requestData: {
    json: {
      content: undefined,
      tts: false,
      nonce: undefined,
      embeds: undefined,
      components: undefined,
      username: undefined,
      avatar_url: undefined,
      allowed_mentions: undefined,
      flags: undefined,
      message_reference: undefined,
      attachments: undefined,
      sticker_ids: undefined
    },
    files: []
  }
}```Uhm, how would i join a voice channel then?
slender sparrow

pins

flat vector
flat vector My play command handler

Anybody has an idea of what I'm doing wrong ? I can't get my bot to play a sound. It joins the channel, the player goes to "Playing" state and the instantly goes back to "Idle" state.

subtle granite
slender sparrow
misty saddle
neon ibex
Error: Error: Cannot find module '/home/ubuntu/bot/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-x64-glibc-2.31/opus.node'

I got this error about voice module

whole flare
neon ibex

@discordjs/opus has already been installed. There was no problem when it was discord.js v13 when dev. But node version was raised to 16.6.1 and the stable v13 was installed, that error occured.

honest shuttle

Have the same problem

whole flare
deep dome

How can i receive output from a voice channel?

neon ibex
whole flare

@discordjs/opus and opusscript

spare wave

yeah, it become empty when updating to v13

do npm ls discordjs/opus

whole flare
deep dome
spare wave

and voice become empty too after updating, lol

whole flare
deep dome

here i can too

with this code the bot joins not muted or deafen'd

vc = joinVoiceChannel({
                channelId : newState.channelId as any,
                guildId : newState.guild.id,
                adapterCreator: newState.guild.voiceAdapterCreator,
                selfDeaf:false,
                selfMute:false
            })
whole flare

But there was an option to receive in Discord.js v12, I don't think you will be able to do that now because Discord.js v13 doesn't support voice in any way anymore

neon ibex
misty saddle

anyone's stage channel createInstance working ?

I am stuck with it

whole flare

My audio player sometimes gets randomly aborted

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)
Emitted 'error' event on AudioPlayer instance at:
    at Encoder.onStreamError (C:\Users\luukw\Desktop\DiscordBot\MusicBot\node_modules\@discordjs\voice\dist\audio\AudioPlayer.js:213:22)
    at Object.onceWrapper (node:events:514:26)
    at Encoder.emit (node:events:406:35)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
``` How do I fix this
spare wave
spare wave
neon ibex
spare wave

according to the documentation Stream#destroy(). I dont use it though

neon ibex

Is youtube-dl-exec better than ytdl-core ?

misty saddle
carmine timber
upper stump

hey, where do I get the voiceAdapterCreator from for the joinVoiceChannel function? :o

carmine timber
neon ibex At what point do I have to end it manually?

Just do this :

let player = createAudioPlayer()
let stream = Ytdl(link, { filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1048576 * 32 });
player.once(AudioPlayerStatus.Idle, () => {
    stream.destroy()
})

It will be suffucient.

brave blaze
        const Guild = client.guilds.cache.get(interaction.guild.id);
        const member = Guild.members.cache.get(interaction.member.id);
        let channel = member.voice.channel;
        console.log(channel)

        await ytdl('https://youtu.be/dQw4w9WgXcQ').pipe(fs.createWriteStream('../JetMusic/commands/music/video.ogg'));

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

        resource = createAudioResource(fs.createReadStream(join(__dirname, 'video.ogg'), {
            inputType: StreamType.OggOpus,
        }));

        console.log(resource)

        const player = createAudioPlayer();
        player.play(resource)

            interaction.reply({
                ephemeral: true,
                content: "bot joined"
            })

i have that, the file is creating but the bot isnt playing anything

carmine timber
brave blaze

oh ok

carmine timber

👍

upper stump

okay thanks, but also how can my bot be a speaker in a stagechannel?

fervent estuary

guildMember.voice.setSuppressed

gray ermine

Ahh help, it's giving me error here (djs-v13)

Type 'InternalDiscordGatewayAdapterCreator' cannot be mapped to type 'DiscordGatewayAdapterCreator'. The parameter types 'methods' and 'methods' are not supported.
spare wave

^ignore it for now, voice still use discord-api-types v0.19, while discordjs used v0.22, so that error occured

gray ermine

uhmm ok

scarlet thistle

is there any method can stop current playing resource?. Like connection.dispatcher.end()

scarlet thistle
subtle granite

TypeError: voiceChannel.join is not a function

const voiceChannel = msg.member.voice.channel;
//SOME CODE


var connection = await voiceChannel.join();
``` I know something has changed, but it happened when i changed to v13
placid canyon

Thats all I know so far, hope that helps 😄

subtle granite

It’s very complicated but when you know how to manage it then you make masterpieces

placid canyon
subtle granite

I try but I can’t yet

scarlet thistle

I can show you guys example code

Wait imma turn on my laptop

placid canyon

omg, that would be very helpful. Thanks

subtle granite
placid canyon
exotic valley
scarlet thistle
          const resource = createAudioResource(ytdl(serverQueue.songs[0].url, {
            filter: "audioonly",
            quality: "highestaudio",
            highWaterMark: 1 << 25,
          }))
          player.play(resource)
          player.on('error', error => {
            console.error(`Error: ${error.message}`);
            play(serverQueue.songs[0]);
          });
          serverQueue.voiceConnection.subscribe(player);
          player.on(AudioPlayerStatus.Idle, () => {
            serverQueue.songs.shift();
            play(serverQueue.songs[0])
          });
          serverQueue.textChannel.send(`Start playing: ${song.title}`)```
it will be something like that
placid canyon
solemn current

hi

scarlet thistle
carmine timber
subtle granite

How can bot join the stage channel?

placid canyon
fervent estuary
placid canyon
scarlet thistle
glad tulip

Help. I'm trying to get my bot to connect to a voice channel using the new 13.0 library and I'm getting this.

Type 'InternalDiscordGatewayAdapterCreator' is not assignable to type 'DiscordGatewayAdapterCreator'

Here's the code:

const voiceChannel = this.getVoiceChannel(msg);
            const conn = joinVoiceChannel({
                channelId: voiceChannel?.id!,
                guildId: voiceChannel?.guild.id!,
                adapterCreator: voiceChannel?.guild.voiceAdapterCreator!
            })
spare wave

For now you can ignore that error, voice still use discord-api-types v0.19 while djs uses 0.22. so only difference on that making it error out

glad tulip

Ah ok, thank you!

placid canyon
gloomy axle

btw there is no way of using opus and using v13 at the same time right?

 channel.join()
                .then((connection) => {
                this.emit(Constants_1.PlayerEvents.CONNECTION_CREATE, message, connection);
                queue.voiceConnection = connection;
                if (this.options.autoSelfDeaf)
                    connection.voice.setSelfDeaf(true);
                queue.tracks.push(track);
                this.emit(Constants_1.PlayerEvents.QUEUE_CREATE, message, queue);
                resolve(queue);
                this._playTrack(queue, true).catch((e) => {
                    this.emit(Constants_1.PlayerEvents.ERROR, e, queue.firstMessage, queue.playing);
                });
            })
subtle granite
async function play(guild, song, someId, videoId) {

    const member = await guild.members.fetch(someId)
    const serverQueue = queue.get(guild.id);

    const player = createAudioPlayer();

    const resource = createAudioResource(ytdl(serverQueue.songs[0].url, {
        filter: 'audioonly',
        quality: 'highestaudio',
        highWaterMark: 1 << 25,
    }))
    player.play(resource)
    player.on('error', error => {
        console.error(`Error: ${error.message}`)
        play(serverQueue.songs[0])
    })
    player.on(AudioPlayerStatus.Idle, () => {
        serverQueue.songs.shift();
        play(serverQueue.songs[0])
    })

    const playingEmbed = new Discord.MessageEmbed()
        .setTitle('NOW PLAYING')
        .setColor('#7A0090')
        .setThumbnail(`https://i.ytimg.com/vi/${videoId}/default.jpg`)
        .setDescription(`[${song.title}](${song.url}) [${member}]`)
        .setFooter('©️ Soundy Studios', pfp)
        .setTimestamp();
    serverQueue.textChannel.send({embeds: [playingEmbed]});
}``` Why is this not playing any sound?
gloomy axle

well the package i was using, uses v12 so 😩

scarlet thistle
subtle granite

Yes, and it sends the playingEmbed

gloomy axle
scarlet thistle
subtle granite

serverQueue.voiceConnection.subscribe(player);
TypeError: Cannot read property 'subscribe' of undefined
const serverQueue = queue.get(guild.id);

scarlet thistle

I'm kinda stupid at English so I don't know how to explain it

subtle granite

Try to explain...

scarlet thistle
sonic sky

So as v13 finally released now, where would I find the example of voiceReciever?

subtle granite
async function play(guild, someId, videoId, connection) {

    const member = await guild.members.fetch(someId)
    const serverQueue = queue.get(guild.id);

    const player = createAudioPlayer();
    const stream = ytdl(serverQueue.songs[0].url, { filter: 'audioonly'})
    const resource = createAudioResource(ytdl(serverQueue.songs[0].url, { inputType: DiscordVoice.StreamType.Arbitray }))

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

    player.on(AudioPlayerStatus.Idle, () => {
        if(!serverQueue.songs[0]){
            serverQueue.connection.destroy();
        }else{
            serverQueue.songs.shift();
            play(serverQueue.songs[0])
        }
    })

    const playingEmbed = new Discord.MessageEmbed()
        .setTitle('NOW PLAYING')
        .setColor('#7A0090')
        .setThumbnail(`https://i.ytimg.com/vi/${serverQueue.songs[0].videoId}/default.jpg`)
        .setDescription(`[${serverQueue.songs[0].title}](${serverQueue.songs[0].url}) [${member}]`)
        .setFooter('©️ Soundy Studios', pfp)
        .setTimestamp();
    serverQueue.textChannel.send({embeds: [playingEmbed]});
}``` Why do i get no audio?
glad tulip

When playing an audio file on connection, is there an on listener you can use for when the audio file is finished playing or did that get removed?

naive ingot

Under what circumstances would CommandInteraction#member result in an APIGuildMember and not a GuildMember?
I'm asking as this is not documented

glad tulip

In my old code I had this

conn
    .play(path)
    .on('finish', () => {
        voiceChannel.leave()
     })
     .on('error', err => console.error(err))

current code in typescript where it does not recognize 'finish' anymore

conn.on('finish', () => {
            player.stop()
            conn.disconnect()
        })
teal marten

How do I connect a bot to a channel?

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

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

Doesn't connect

keen plaza

Do you have the voice state intent?
If so, grab some debug logs from both discord.js and discordjs/voice.

glad tulip

Ignore me lol

teal marten

docs?

glad tulip

I was looking at playing audio on accident

subtle granite

I hate that i somehow get no audio

glad tulip
teal marten docs?
// Subscribe the connection to the audio player (will play audio on the voice connection)
const subscription = connection.subscribe(audioPlayer);

// subscription could be undefined if the connection is destroyed!
if (subscription) {
    // Unsubscribe after 5 seconds (stop playing audio on the voice connection)
    setTimeout(() => subscription.unsubscribe(), 5_000);
}

I was looking here but might have just misunderstood it

subtle granite

But i like how the bot defeans itself tho

solemn current

how to get the people in the vc

teal marten

I have ONLY slash commands in my bot
There is a command /join

const ct = require ('common-tags');
const {joinVoiceChannel} = require ('@ discordjs / voice');
module.exports = {
   name: 'join',
   description: 'Invite bot to voice channel',
   async execute (interaction) {
             const connection = joinVoiceChannel ({
                  channelId: channel.id,
                  guildId: channel.guild.id,
                  adapterCreator: channel.guild.voiceAdapterCreator,
              });
              await interaction.reply (ct.stripIndents`
                   Command: $ {interaction.commandName}
                   ID: $ {interaction.commandId}
             `);
   },
};

But the bot won't connect

solemn current

bruh

subtle granite
hollow flume

man this is different

and a lot harder to get it to function

subtle granite

How would i check if i'm already in a voice channel?

teal marten
solemn current

bruh

solemn current
placid canyon
spare wave
subtle granite

Like I'm starting to think they're bored so they do crap like this. Explain to me what good is it that they made 60 lines of code out of 10 lines of code?

placid canyon
spare wave
Ytdl(link, { filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1048576 * 32 });``` like this
hollow flume

was about to loose it ngl

spare wave

and ytdl doesnt end it stream automatically, you need to end it manually else got issue memory leak

subtle granite
async function play(guild, someId) {

    const member = await guild.members.fetch(someId)
    const serverQueue = queue.get(guild.id);

    const player = createAudioPlayer();
    const stream = ytdl(serverQueue.songs[0].url, { filter: 'audioonly'})
    const resource = createAudioResource(stream, { inputType: DiscordVoice.StreamType.Arbitray })

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

    player.on(AudioPlayerStatus.Idle, () => {
        if(!serverQueue.songs[0]){
            serverQueue.connection.destroy();
        }else{
            serverQueue.songs.shift();
            play(serverQueue.songs[0])
        }
    })

    const playingEmbed = new Discord.MessageEmbed()
        .setTitle('NOW PLAYING')
        .setColor('#7A0090')
        .setThumbnail(`https://i.ytimg.com/vi/${serverQueue.songs[0].id}/default.jpg`)
        .setDescription(`[${serverQueue.songs[0].title}](${serverQueue.songs[0].url}) [${serverQueue.songs[0].member}]`)
        .setFooter('©️ Soundy Studios', pfp)
        .setTimestamp();
    serverQueue.textChannel.send({embeds: [playingEmbed]});
}``` Why does this not play any sound?
hollow flume
subtle granite
hollow flume

it isnt, ive the same and works for me, pretty sure

subtle granite

I need to know what is wrong then

solemn current
async function play(guild, someId) {

    const member = await guild.members.fetch(someId)
    const serverQueue = queue.get(guild.id);

    const player = createAudioPlayer();
    const stream = ytdl(serverQueue.songs[0].url, { filter: 'audioonly'})
    const resource = createAudioResource(stream, { inputType: DiscordVoice.StreamType.Arbitray })

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

    player.on(AudioPlayerStatus.Idle, () => {
        if(!serverQueue.songs[0]){
            serverQueue.connection.destroy();
        }else{
            serverQueue.songs.shift();
            play(serverQueue.songs[0])
        }
    })

    const playingEmbed = new Discord.MessageEmbed()
        .setTitle('NOW PLAYING')
        .setColor('#7A0090')
        .setThumbnail(`https://i.ytimg.com/vi/${serverQueue.songs[0].id}/default.jpg`)
        .setDescription(`[${serverQueue.songs[0].title}](${serverQueue.songs[0].url}) [${serverQueue.songs[0].member}]`)
        .setFooter(':copyright: Soundy Studios', pfp)
        .setTimestamp();
    serverQueue.textChannel.send({embeds: [playingEmbed]});
}
placid canyon

Hey, does anybody know what my problem is? I get this overwhelming amout of debug info (im talking about the thing at the end, the connections state are activated by myself)

It goes to ready and then crashes

hollow flume
placid canyon
placid canyon It goes to ready and then crashes

That comes when I try to play an live stream: ```sh
PS D:\GitHub\BenniBot> node .

Core Dependencies

  • @discordjs/voice: 0.5.5
  • prism-media: 1.3.1

Opus Libraries

  • @discordjs/opus: 0.5.3
  • opusscript: not found

Encryption Libraries

  • sodium: not found
  • libsodium-wrappers: 0.7.9
  • tweetnacl: not found

FFmpeg

  • version: 4.4-essentials_build-www.gyan.dev
  • libopus: yes

BenniBot#8620 Version b4.0.0.0 started sucessfully!
Connection transitioned from signalling to connecting
Connection transitioned from connecting to connecting
Connection transitioned from connecting to connecting
Connection transitioned from connecting to connecting
Connection transitioned from connecting to ready
Audio player transitioned from idle to buffering
Connection transitioned from ready to ready
Audio player transitioned from buffering to playing
[06-08-2021 22:16:06] Server Name: playing - lofi hip hop radio - beats to relax/study to
Audio player transitioned from playing to idle
[06-08-2021 22:16:06] Server Name: Stopped playing Music and left the Voice Channel
Connection transitioned from ready to destroyed

little berry

How do I get the voice channel ID of the bot?

placid canyon
placid canyon
little berry

The current voice channel that the bot is in, the ID of it

subtle granite
subtle granite

Now i get an error ```js
D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\util\Secretbox.js:27
throw new Error(`Cannot play audio as no valid encryption package is installed.
^

Error: Cannot play audio as no valid encryption package is installed.

  • Install sodium, libsodium-wrappers, or tweetnacl.

  • Use the generateDependencyReport() function for more information.

    at Object.fallbackError (D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\util\Secretbox.js:27:11)
    at Networking.encryptOpusPacket (D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\networking\Networking.js:413:35)
    at Networking.createAudioPacket (D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\networking\Networking.js:397:53)
    at Networking.prepareAudioPacket (D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\networking\Networking.js:321:37)
    at VoiceConnection.prepareAudioPacket (D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\VoiceConnection.js:286:33)
    at D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\audio\AudioPlayer.js:426:54
    at Array.forEach (<anonymous>)
    at AudioPlayer._preparePacket (D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\audio\AudioPlayer.js:426:19)
    at AudioPlayer._stepPrepare (D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\audio\AudioPlayer.js:398:22)
    at prepareNextAudioFrame (D:\Nodejs_workspace\Soundy Studios\node_modules@discordjs\voice\dist\DataStore.js:106:31)```

async function play(guild, someId) {

    const member = await guild.members.fetch(someId)
    const serverQueue = queue.get(guild.id);

    const player = createAudioPlayer();
    const stream = ytdl(serverQueue.songs[0].url, { filter: 'audioonly'})
    const resource = createAudioResource(stream, { inputType: DiscordVoice.StreamType.Arbitray })

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

    player.on(AudioPlayerStatus.Idle, () => {
        if(!serverQueue.songs[0]){
            serverQueue.connection.destroy();
        }else{
            serverQueue.songs.shift();
            play(serverQueue.songs[0])
        }
    })

    const playingEmbed = new Discord.MessageEmbed()
        .setTitle('NOW PLAYING')
        .setColor('#7A0090')
        .setThumbnail(`https://i.ytimg.com/vi/${serverQueue.songs[0].id}/default.jpg`)
        .setDescription(`[${serverQueue.songs[0].title}](${serverQueue.songs[0].url}) [${serverQueue.songs[0].member}]`)
        .setFooter('©️ Soundy Studios', pfp)
        .setTimestamp();
    serverQueue.textChannel.send({embeds: [playingEmbed]});
}```
little berry

you need an encryption library, npm install sodium

subtle granite
little berry you need an encryption library, `npm install sodium`
PS D:\Nodejs_workspace\Soundy Studios> npm i sodium
npm ERR! code 1
npm ERR! path D:\Nodejs_workspace\Soundy Studios\node_modules\sodium
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node install.js --preinstall
npm ERR! Please set your Microsoft Visual Studio version before you run npm install
npm ERR! Example for Visual Studio 2015:
npm ERR! 
npm ERR!     For you user only:
npm ERR! 
npm ERR!         npm config set msvs_version 2015
npm ERR!
npm ERR!     Global:
npm ERR!
npm ERR!         npm config set msvs_version 2015 --global
npm ERR!
npm ERR! Supported values are 2010, 2012, 2013, 2015

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\julia\AppData\Local\npm-cache\_logs\2021-08-06T20_37_59_034Z-debug.log```
keen plaza

You probably want one of the others on windows.

little berry

Then try npm i tweetnacl

Seems to be a problem with vs as well, maybe you should npm config set msvs_version 2015 --global

subtle granite

Finally

if (cmd === 'stop') {
        if (!msg.member.voice.channel)
            return msg.reply('You need to be in a voice channel to perform this command!');
        if (!serverQueue)
            return msg.reply('No song is playing!!');
        serverQueue.songs = [];
        serverQueue.connection.destroy();
    }``` Now i have problem with it not clearing the queue
scarlet thistle
subtle granite

TypeError: Cannot read property 'members' of undefined
const member = await guild.members.fetch(someId)
How do i get that error when i pass msg.guild

subtle granite
buoyant ledge

~~hi 😄
can I change the volume of a resource while playing?
I tried this, but it doesn't change anything
https://afink.eu/kicom5~~
I'm to dumb, sorry 😄

autumn robin

receive from voice

icy maple

The guide in the pins explains how to use the new voice package

fleet aspen

Whenever I try to play things, I get the error of
if (resource.ended) { TypeError: Cannot read property 'ended' of undefined

How can I resolve that one?

-- Fixed by adding const resource thing --

calm steeple
AudioPlayerError: aborted``` i really dont know about this error anyone help?
neon ibex
neon ibex
Error: 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)

I got this error in AudioPlayer. Once I find out that the situation is playing a long song, that error occurs along the way.

spare wave
neon ibex

oh I see Thanks!

hasty shuttle

Why would I get Error TypeError: channel.join is not a function
Code:

    const { channel } = message.member.voice;
    const queueConstruct = {
      textChannel: message.channel,
      channel,
      connection: null,
      songs: [],
      loop: false,
      volume: 100,
      playing: true
    };
    queueConstruct.songs.push(song);
    message.client.queue.set(message.guild.id, queueConstruct);
    try {
      queueConstruct.connection = await channel.join();
      await queueConstruct.connection.voice.setSelfDeaf(true);
      play(queueConstruct.songs[0], message);
    } catch (error) {
      console.error(error);
      message.client.queue.delete(message.guild.id);
      await channel.leave();
      return message.channel.send(`無法加入語音頻道: ${error}`).catch(console.error);
    }
river oxide

Can someone give me a tip for making the bot the voice call in discord.js v13?

neon ibex
hasty shuttle
neon ibex
const { joinVoiceChannel } = require('@discordjs/voice');

joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator
})
neon ibex
spare wave

Yeah, can lower it or later I will publish some example using youtube-dl-exec

scarlet thistle

Is there any methods like .on("end") to check whether a resource is completely playing?

bold cairn

I'm using it with idle, but that's not recommended

scarlet thistle

It says that i should set something like setMaxListenner

spare wave

Proof of concept for skip is make a playlist, and using audioplayer.stopwhere, when it stop, it will idle and make it to seek next track by using shift() I'm on phone so pardon if the spelling is incorrect etc.

scarlet thistle
          const connection = joinVoiceChannel({
            channelId: channel.id,
            guildId: channel.guild.id,
            adapterCreator: channel.guild.voiceAdapterCreator
          });
          // connection.setMaxListeners(1000);
          serverQueue.voiceConnection = connection;
          serverQueue.loopSong = false;
          serverQueue.songPlayer = player;
          play(queueConstruct.songs[0]);

I did that, then I called serverQueue.songPlayer.stop() from skip command

neon ibex

I'm testing the youtube-dl-exec.

severe frost

I am unable to install sodium even after running

npm install --global --production --vs2015 --add-python-to-path windows-build-tools

pls help

scarlet thistle

install libsodium instead

severe frost

ohkay

neon ibex

Which one is better between tweetnacl and libsodium-wrappers?

neon ibex

Is there any difference?

spare wave

Not very sure on the difference, since I did not measure any quality/quantity

neon ibex

thanks

severe frost
module.exports = {
    name: 'muteall',
    description: 'A command that allows admins to mute everyone in current VC.',
    usage: 'Just the command with no arguments.',
    permissions: "MUTE_MEMBERS",
    execute(message) {
        console.log(message.member.voice.channelId)
        if (message.member.voice.channelId) {
            let channel = message.guild.channels.cache.get(message.member.voice.channel.id);
            for (const [, member] of channel.members) {

                member.voice.setMute(true);
            }

            message.reply({ content: 'I have muted everyone in your VC.' })

        } else {
            message.reply({ content: 'You need to join a voice channel first!' });
        }

    }
}

It is saying 'you need to join a vc' even after I have joined a vc, worked fine in v12

PS- It simply mutes everyone in author's vc

wispy trout

oh i see

in my eval it works

severe frost

.channel or .channelId both worked in v12 and in v13 it only remembers my voice state when the client was ready, and never updates the voice state

proud spindle
misty saddle

Stage Channel.createStageInstance() isn't working , but it was working on deprecreted versions , it just suddenly not working from yesterday

sly bear

how do we join a voice channel? im getting so confused

dusky hatch

is the voice module already included in v13 and i can uninstall @discordjs/voice ?

dusky hatch
misty saddle

two seperate package

dusky hatch

just to be sure, "@discordjs/voice": "^0.5.5", is the latest version correct?

misty saddle

yeah