#archive-voice
30636 messages · Page 7 of 31
lol, it's literally .joinable
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!');
}
}
You have to use the new voice package. The guide is in the pins
Thanks
And make sure to enable the GUILD_VOICE_STATES intent
Yes
Discord js v13 like, Discord js v12 dislike )))
how to connect to the voice channel
joinVoiceChannel() dosen't work
<VoiceChannel>.join()?
Removed in v13
Show code
oh mb
Nothing happens
if (message.content == "jointest") {
const connection = joinVoiceChannel({
channelId: message.channel.id,
guildId: message.channel.guild.id,
adapterCreator: message.channel.guild.voiceAdapterCreator,
});
}
It’s prob not running then
What message are you sending?
jointest
Log message.content before the if statement, and a different log inside
from the pinned message in this channel, it is a little unclear how to make the bot connect to the voice channel
Did you add the logs and retest yet?
?
Log
message.contentbefore the if statement, and a different log inside
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
}
Should prob use await enterState(…) and wait for ready to make sure the bot actually connects
enterState?
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');
You can view the other sections of the guide using the hamburger menu in the top right
this happens when i follow the guide and i have NO CLUE on what this error means
^ Just ignore it for now, it a typing discrepancy between discord.js newest commit against voice module. @keen flume
ty
i still seem to get this issue though
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.
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
Cannot play audio as no valid encryption package is installed
You need to install one of these encryption library.
sodium, libsodium-wrappers, tweetnacl
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 :(
Guys, help, pls
Can we stream video? Or that is still imporssible?
Sorry, no
does anyone happen to know the new way of which to change the volume (when the audio is already playing)?
Getting <AudioResource> and change <AudioResource>.volume
P.S. Not worked.
You need to pass inLineVolume to true while creating audio resource and then use resource.volume.setVolume(amount).
yep that works ty 🙂
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
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?
how to stop bot from playing music and leave vc
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}`)
})
connection.destroy() or connection.disconnect() || Only if you want to reuse your voice connection once again
If it is giving Error Status 403 = Forbidden, So it means that the audio resource you are playing has entered to error status 403 from that site.
Hmm ok. Could that be due to me doing YTDL still? I've heard mixed things about that.
If so, what is (or are) the recommended alternatives? I forget which ones are suggested now
See youtube-dl examples best alternative to ytdl
if(connection.state.status !== 'destroyed') connection.destroy()
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?
Please send the full log and code generating the error.
Hi people, do you know how to get the id of the channel where the bot is connected on guild ?
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
How can I play audio in specific channel?
Hewwo. Since there's @discordjs/voice, do I need @discordjs/opus anymore?
Oh ok
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': {
//
}
}
}
I'll try, thanks for the help.
?stage
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
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
The problem actually lies with erlpack here
So just uninstall that
ok
thx, it works <3
is there an event like speaking on voiceConnection@djs12?
i meant that is there an event on the new djs voice like the speaking event on djs12
is audio receiver automatically get data from speaking users?
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 });
djs v12 or 13 ??
npm list @discordjs/voice ??
13
what has message.guild.me.voice.channel.leave
changed to?
Main question. <AudioPlayer> needs to be created separately for each server, yeah?
how do i make the bot join a voice channel and create a connection?
yes, but thats just the method, how do i use it? as in message.guild.me.voice.disconnect?
joinVoiceChannel will returns voice connection
then you could just call disconnect from it
ah ty, i was just trying to make if command === 'disconnect' then disconnect from vc
Does anyone know what the startime alternative is?
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
not quite sure what you mean but maybe this is what you're looking for: #archive-voice message
help?....
any one?
Hi how to make the music bot to join stage channel..
Sorry I wasn't on the computer, I'm looking for a resource, how long has ill stream been
Hi, has new voice module something like seek option?
not yet as far as I know. there's a work around: #archive-voice message
thx
How can i understand that the audio player has finished the song?
state changes to idle
there should be a section about this in the guide
i looked but i dont understand so am asking
audio players have states (while playing your resource it's playing) so once they don't play the resource anymore their state switches to idle. what you do is wait for this to happen...
hmm alright thankss
i found the problem is my audioplayer state doesnt switches to idle
subscribe new resource
and i restart vs code and fixed now
👍
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
how to join a voice channel?
interaction.member.voice.channel.join not working
How to make a nowplaying command?
@discordjs/voice removed streamTime and pauseTime
Oh bruh I saw it
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 });
Create audio resource like this : https://discordjs.guide/voice/audio-resources.html#creation
and then play in audio player like this : https://discordjs.guide/voice/audio-player.html#playing-audio
thanks
How to join stage Channel and play music 🤔
oh I get it
Can anyone tell me how to make a bot to play songs on stages?
What should i do so the bot instantly leaves VC after i restart/re-deploy the bot?
You need to loop through each guild and do something like this :
client.guilds.cache.forEach((guild) => {
guild.me?.voice.setChannel(null)
})
Same way as you do in voice channel but to make bot speaker you need to set this : https://discord.js.org/#/docs/main/master/class/VoiceState?scrollTo=setSuppressed
as false.
Let me try that
Try that and let me know the results
Give me a min
Okay
It’s works perfectly for voice channels. Thank you!
Though i have to find the way to end it properly in stageChannels
Does it not work on stage channels ??
It works. But the stageInstance doesn’t get deleted. Thus after restart, when i try to play again on a stage channel the bot just stays as a listener.
Whenever bot or somebody joins in stage, they are audience at first, they need to be made speaker by using : https://discord.js.org/#/docs/main/master/class/VoiceState?scrollTo=setSuppressed
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.
Ok 👍
But Make sure you have Move Members permission, otherwise bot will not be able to disconnect.
I made the client to have admin perms by default.
All done. Thank you very much for your help!
Btw, this is only available on interactions only. Right?
yes
These are slash commands see pins at #archive-interactions
Hmm. I hope they are available on message soon as i can’t get them if i’m doing interaction.send.
do interaction.reply()
I know, already have them in my bot.
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.
Interaction.deferUpdate()?
how can i make my bot join a vc?
deferUpdate only extends the token validity from 3 seconds to 15 minutes
If i use defer(), i get 15 minutes. If i do deferUpdate every 15 minutes using setInterval will that work?
Hmm
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
Im trying to get voice connections with this method
client.voice.connections.size```
its worked for me in v12 has the method been changed?
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.
What would be the best way to get a number of people that are in a VC with the bot globally?
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.
Show me code where you defined client in main file
Oh, was it Intents problem? It rings a bell when you said that
Yes
Ok, thanks
You need Guild_Voice_State Intent for bot to connect
ah, i will add it to the intents array, thanks again
👍
Yes it had been changed.
You are merging 2 things and this can't be done. You are creating a youtube-dl to send you audio packets to stream and side by side also creating FFMPEG to transcode it at same time. FFMPEG requires a url or a file for -ss function to work, you can't just stream into FFMPEG and tell FFMPEG to skip to this part of song just by using audio packets that I have sent.
let total_members = 0
client.guilds.cache.forEach((guild) => {
total_members += guild.me.voice.channel.members.length
})
legend, tysm
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?
if the bot isnt in a vc voice.channel will be null
Change that code to :
let total_members = 0
client.guilds.cache.forEach((guild) => {
total_members += (guild.me.voice?.channel) ? guild.me.voice.channel.members.length : 0
})
seems to just print out null now 
will keep looking
What is printing null ???
total_members
I have set the value to 0, so how can it print null ??
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
So let me check and tell you the results.
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
aha, got it with .size instead of .length
Yes
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
you my friend are an absolute legend, tysm ♥️
No problem
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!');
});```
The Debug Log says that the bot closed because of unknown opcode
@edgy beacon May be this thread will help you
And I don't know what to do
I did what the thread said and nothing has been changed
channelID를 channelId로 바꿔야해요
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
감사합니당!
한국분 맞으셨구나 ㅋㅋ
Can I see your code?
it was fixed, i had to add this property lol
adapterCreator: message.channel.guild.voiceAdapterCreator,
Is it just me or are the createAudioResourceOptions missing from the docs
good!
Me too I think?
There doesn't seem to be many, based on the examples. But still.
Which options do you need ??
i needed the input type
Found it in an example.
There is inputType in audio resource
Yeah i wanted to see the options but figured the types existed in the module.
how to undefine my bot plz help
What’s the new method?
What is undefine meaning?
in vc
pls don't cross post questions
how to make bot speaker when join stage channel
@brisk aspen You might get a rough idea from this
Ight
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
how to use filters pn my bot?
@eager lake
help?...
?r6
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.
oops sorry
connection.subscribe(player)
ty
You need FFMPEG instance for that
oldVoice.guild.me.voice.setSuppressed(false); }
``` why channel type is return null
oldVoice.channel.type
hmm...
how do i end the current song which is playing
before it was like connection.dispatcher.end();
please help
audioPlayer.stop();
oh, so it will end the whole current song and not all ?
yes maybe same behavior as dispatcher.end() (v12)
oh, okay, trying
good!
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
:)
can someone help me? My bot doesn't get all the members in one voice.Like 2 members but it only get 1
Weird, I ended up making it work. it was a problem with FFMPEG's -f option, and Discord's inputType
option.
what is djs new voice ?
if(oldVoice.channel.type === "GUILD_STAGE_VOICE"){
oldVoice.guild.me.voice.setSuppressed(false);
}
Can i access AudioPlayer properties and methods from a subscribed connection?
connection.player i think
The guide is using connection.pause(), but doesn't show the context, e.g. what does the connection variable represent
There doesn't exist anything like that in the docs
player.pause()
Can the player be tracked like the connection can?
I am looking at making a separate command for pausing and unpausing and would prefer avoiding having to export the player, or the subscription.
idk
Does type: 'voice', still work in v13?
When creating a channel? Idk if this is the right channel to ask
Does anyone know why joinVoiceChannel() isn't working? I am sending it the right Voice Channel/Guild ID and the voiceAdapterCreator.
It's GUILD_VOICE now
code?
I can send it in 20 minutes
hmm may i know what's this error Error: Did not enter state ready within 30000ms
Intents problem
huh
Connection.state.subscription.player = player subscribed to that connection
wdym
Show me code where you defined client in main file
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
Add one more intent : Intents.FLAGS.GUILD_VOICE_STATE
See above
ok
hmm but its bitfield invalid
Sorry it is Intents.FLAGS.GUILD_VOICE_STATES
idk why but still doesn't work
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)```
Channelid must be the id of voice channel not the channel itself. It should be vc.id
i know, and that's not the issue
Do the bot join voice channel ??
yes
How to get my bot join stage Channel
Why I’m getting this?
https://cdn.discordapp.com/attachments/824411059443204127/872710806133940284/image.png
So what's the issue ??
but cannot play audio
Show me playing code
Same way as voice channel join command
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");
^^^
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
Having 2 conditions like that will likely cause issues
Just use this condition only if(!message.member.voice.channel)
how?
I commented other side
You are missing connection.susbcribe(player)
Maybe then, restart the bot and try again
but it says connection.subscribe() is not a function
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");
Get connection like this : https://discordjs.guide/voice/voice-connections.html#creation
and then run the command in audio player
Make sure you are in right channel, since new voice api doesn't have joining command like this : message.member.voice.channel.join()
Hmmm should I change like this
@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
Thx @carmine timber I changed my code like this and it worked
Wait do you create a voice connection before getting the connection
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
You are running connect to channel twice.
Remove Connect to channel from here :
await connectToChannel(vc)
player.play(audio);
how to make bot speaker when join stage channel
I am getting eror
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.);
}
}
Documentation suggestion for @warm field:
VoiceState#setSuppressed()
Suppress/unsuppress the user. Only applicable for stage channels.
Does it play now ??
nope
Do you still get subscribe of undefined error ??
got the [Symbol(code)]: 'VOICE_NOT_STAGE_CHANNEL' and Error: Did not enter state ready within undefinedms error
nope but ☝️
Yup, you are calling bot in a voice channel so this code fails : msg.guild.me.voice.setSuppressed(false);
huh, no
Moreover, you didn't define ms to connect , see this :https://discordjs.github.io/voice/modules.html#entersstate
You need to provide a vaild time
can you give me an example please, i don't know how long to put
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.`);
}
}
alright thanks let me try
hmm it didn't play and i got this error ```TypeError: Cannot read property 'once' of undefined
@carmine timber
Where do you have once in your code ??
its a discordjs/voice error
Show me full error
node_modules/@discordjs/voice/dist/audio/AudioPlayer.js:221:29)
at AudioPlayer.play
Type npm list @discordjs/voice
So that means it is error with the audio resource you are playing
Not a djs error anymore
hmm but its working well on djsv12
Maybe try using this module : https://www.npmjs.com/package/ytdl-core-discord
their dependencies were out of date but nvm i'll give it a try
@carmine timber still getting the same error
Show me code at this location.
Is it related to error event ??
i used ytdl-core-discord and TypeError: Cannot read property 'once' of undefined at AudioPlayer.play (/home/runner/node_modules/@discordjs/voice/dist/audio/AudioPlayer.js:221:29) at play (/home/runner/commands.js:35:12) at processTicksAndRejections (node:internal/process/task_queues:96:5) that's the error
No just do to AudioPlayer.js file and show me code at 221 line
@carmine timber
Just for now comment that line and run code again
umm
Did that work ??
no lol
its downloading everything again idk why
XD
@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)
Change this line :
if(msg.guild.me.voice?.channel?.type === 'GUILD_STAGE_VOICE'){msg.guild.me.voice.setSuppressed(false);}
hmm weird no errors but no audio
Change this line of code :
player.play(stream);
still not working
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.`);
}
}
Change this line :
const stream = downloadYT(video.url, { filter: 'audioonly' });
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
@carmine timber from {"status":"idle","resource":false,"stepTimeout":false} to {"status":"buffering","resource":true,"stepTimeout":false}
and then ??
hmm nothing
After buffering, Nothing ??
ye
Interesting
any solution ?
Did you use ytdl-core-discord module ??
If yes, then show me code of play function with that
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.`);
}
}
What is downloadYT defined as ??
um ytdl-core-discord
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)
lol still not working
Did you change last code ??
yea i do
Player logs ??
same as justnow
If I am not wrong, you need to await downloadYT
So change @olive musk to this & try again :
const stream = await downloadYT(video.url);
@olive musk Worked ??
@carmine timber didn't work 😢
Errors ??? and player logs
no error, player log state change: from {"status":"idle","resource":false,"stepTimeout":false} to {"status":"buffering","resource":true,"stepTimeout":false}
so your audioPlayer just gets stuck at buffering?
idk man
everything seems to be working fine on djsv12 but when it comes to v13 i'm literately confused
Yes apparantly
can you try smth for me?
we've been doing this for hours
sure
in ur node_modules navigate to the discordjs/voice source
okay, then ?
so full path would be node_modules/@discordjs/voice/dist/audio/AudioResouce.js
open that file
alright, now ?
replace lines 40-42 with this.playStream.once('readable', () => (this.started = true));
see if that fixes ur problem
i personally ran into a similar issue until i did that small change.
I got an open pr about it: https://github.com/discordjs/voice/pull/162
hmm still didn't work
so the player still just stays buffering?
yeah pretty much the same state change: from {"status":"idle","resource":false,"stepTimeout":false} to {"status":"buffering","resource":true,"stepTimeout":false}
ic
try listening for AudioResouce.playStream readable event
see if that fires
He also got playstream as undefined here https://cdn.discordapp.com/attachments/852128888128929802/872736281388535808/unknown.png
use an once listener preferrably
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
resouce.playStream is undefined there?
Yes
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?
Something like this
yeah i just saw that. If possible id like to see the current one
@olive musk can you do this?
@olive musk play function code ??
huh
@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)
}
}
can you send your current play function?
yea we're going on with the same issue here
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
@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
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
- version: 4.4-static https://johnvansickle.com/ffmpeg/
- libopus: yes
--------------------------------------------------```
Do npm i libsodium-wrappers
i mean like i don't have python 3 installed, wait its an npm
You need to have one encryption library to be able to send data.
Try adding one of the packages
i'm just confused, why discordjs decided to separate voice with discordjs
It will be merged once v13 releases
actually it wont
Oh that's weird
you said one of them only ?
yes
uh still not working
What do console.log(stream) Show ??
an object
too long can't send, but its not a promise
Ok I understand
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
haha just now we commented those events cuz it causes trouble
this is for the stream you got from downloadYT()
not resouce.playStream
um so what should i do now
listen for those events on stream
ya but it will say .once is not a function
and just log something to console that tells u which events fired
on stream?
you mean client.stream ?
no
i mean the stream you have there
const stream = await downloadYT(video.url);
oh, it returns an object
isnt should newVoice instead oldVoice?
i don't think there's any event or stuff
what editor are you using?
also if theres no event stuff on that id guess thats the problem
google cloud shell
ok...
so what is downloadYT()?
can you show where that is defined
downloadYT is actually a node module ( ytdl-core-discord )
last time i was using ytdl-core and it works fine
Didn't see that in the docs, Thank you very much!
ytdl-core-discord returns an opus stream
so that has events on it
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] },
yeah thats an event emitter
so just log them all
sure
wait how do i listen to the events ? TypeError: stream._events is not a function
stream.on(...)
just like any other events
and inside the function ?
id assume you know how listening to evnets works at this point...
okay
hmm is this how i listen to events ? stream.on('finish', msg => console.log)
there are no parameters in the finish event
also u arent calling the console.log properly
uh but none of them works
i've been using this for months now to listen to 'debug' event on djs
stream.on("event name", () => console.log("event fired!"));
nope didn't work stream.on('prefinish', msg => { console.log(msg) })
msg is not a parameter there
its going to be undefined
oh wait then what am i suppose to log ?
a string that lets you know which event it was that fired
like the event didn't fire at all, basically all of them
yes they dont until the stream ends
i mean like i have all the events on and they're not firing
see if readable event fires
yep it does fires
Ok thats good
fun fact : it fires after the player's debug event
So if u do resource.playStream.one(...) does it work?
See if readable fires there
hmm where
Do it right after you create the resource
define nothing inside the function?
Do the same thing u did for the stream readable event
Just chnage what it logs so u know its from the resouce
Dont log exactly the same string as u did from the stream.on readable
oh like other events ?, they all aren't going to fire lol
idk man would you like to help me out with that, maybe its because of my ide just maybe you know like not sure
So does resource.playStream readable event fire?
how to join a vc through this package?
the channels.cache.get().join() won't work
nvm found
hmm i think its not a function TypeError: resource.playStream.one is not a function
should i do resource.playStream() only ?
Thats not a function
And its once not one
eh?
Try re-installing
oh, ok
same err
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'
}
this is right, right?
idk maybe you need guildId also
oh
U didnt pass a listener to the .once()
doesn't change anything, added guild id too
you mean like resource.on('EVENT', () => {...})?
resource.playStream.on(...
wait can i not use the module for js?
U can
Which npm and nodejs version are u on btw?
what's the event ?
16
And npm?
idk let me check
7.9.0
Seems alright
Try doing npm i @discordjs/voice, JoinVoiceChannel options are wrong
read this : https://deploy-preview-595--discordjs-guide.netlify.app/voice/voice-connections.html#creation
oh
how to make the bot joins vc
still erroring out, its some problem with the module if i am correct
yeah the index.js file is missing
yep does trigger
add json "main": "index.js" to your package.json code
my bot's?
yes and ig you need index.js
my bot's package.json is correct
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
You need GUILD_VOICE_STATES intent also for bot to connect
how to make the bot joins vc
I have that
my bot won't even join vc idk why
idk how to make the bot joins vc
hi
Is it possible to make a bot that has a voice chat recording feature?
That sounds similar to the problem i had
What api can you rely on
Do u still have the fix implemented i instructed about earlier?
so what's the solution now
U still got the fix i told about before implemented?
which one ?
The first one. Where u changed that listener within node_modules
yep i do
Hey
And the audioPlayer still just got stuck at buffering?
yeah
so how do i make my bot join a voice channel it is so confusing
you said that happen to you before but have you fixed it ?
Did the readable event fire after or before the state change from idle to buffering
dude at this point I would get farther smashing me head into my keyboard. I can't get my bot to join the vc.
I did fix it. With the change i gave u
sameeeeeeeeeee
after
@sly bear do you have the GUILD_VOICE_STATES intent?
damn look at how long i've spend on this
same
what do i even do to make my bot join the vc , in v12 it was so easy ffs
Read the documentation
i did]
So whats the problem?
yeah because it sucks
Can u send a screenshot of the debug logs u got from audioPlayer?
um which ? its very short state change: from {"status":"idle","resource":false,"stepTimeout":false} to {"status":"buffering","resource":true,"stepTimeout":false}
Is that all u got?
ye
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
me too, i'm so sick of this now LOL but thanks for helping
@carmine timber you too, thanks
will this work?
Is it possible to make a bot that has a voice chat recording feature?؟؟؟؟
Yes
VoiceReceiving docs are still a wip tho
How can I do this?
I havent experimented with it yet
Id just suggest u take a look at djs/voice code and trial and error from that
Ok
Can you send me this code?
Thank you
I am getting error 4001
Code please
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;
}
What is voice_channel defined as ??
const voice_channel = interaction.member.voice.channel;
my bot isn't joining the channel at all
Are you sure, you are having problem at this ?? This looks all good for me.
As per your code, you are sending a Unknown code to discord API somewhere.
This much code or there is something else also ??
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
do you have "GUILD_VOICE_STATES" in your client intents?
yes
Show me code where you defined client in main file
const { Client, Collection, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES] });
Okay do one thing, go to here
node_modules/discord.js/src/client/websocket/WebSocketShard.js line 659 (the _send method) and log data there?
Do console.log(data) above this.connection.send( .
https://cdn.discordapp.com/attachments/872056466796867584/872073407682998312/unknown.png
Can you send the full thing (minus tokens)?
@meager river Like this one :
ok
Can you send the full thing (minus tokens)?
{
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?
So you are sending joinchannel command in wrong way :
{
op: 4,
d: {
guild_id: undefined,
channel_id: undefined,
self_deaf: true,
self_mute: false
}
}
So channel ID and guild ID are both undefined which causes error.
Can you console.log(voice_channel.id) and guild.id also ??
already did and it returned the proper id for both
do you want me to send my whole play command? it's badly written but you might be able to see the issue.
yes
discord messed up the indentation
@carmine timber Hi. How to 'destroy' or 'Stop' a entersState without connection argument?
Hang on we are trying to solve a problem.
VOICE STATE UPDATE event is looping how to solve
Dont let it loop?
@meager river
Just don't execute it. If you don't want that.
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
First of all, this code is of old voice module so should be asked in #archive-djs-v12-voice-deprecated >
Secondly, there is no event named as end in dispatcher. It is finish event
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 ?
Anyone else having trouble with ytdl-core crashing bot? The stream seems to error.
My play command handler
What is aborted error? I was playing audio with ytdl-core-discord and the bot suddenly stopped with aborted error.
thanks 😄
(node:17412) UnhandledPromiseRejectionWarning: TypeError: interaction.member.voice.channel.join is not a function
See pins
Any opinions?
Your node version is v16?
Yes
Then try this js Ytdl(link, { filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1048576 * 32 });
highWatermark there is 32mb
Is that ytdl-core or ytdl-core-discord?
Both can use it because both still use ytdl-core
Ok, I will try it
bruh i cant even get my bot to join a channel XD
um who cares
if ur trying to ask for help
then just ask it and provide all the resources so that we can help you
how do i get my bot to join a vc? :P
check the pins for guide
ive already done that bruv
then just ask it and provide all the resources so that we can help you
-_-
how do i get my bot to join a vc there isnt any resources to provide
its a question
so for example,
vc.joinVoiceChannel({channelId: vcid, guildId: guildId})```
Or something like that, u need to specify client somewhere XD
wdym specify client
i have
const connection = joinVoiceChannel({
channelID: channel.id,
guildID: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
Somehow add this connection to base discord client, i dont remember how to do that :v
:C
And it doesnt work? For my bot its working
nope
Have u installed all required packages? (from @discordjs/voice dependencies tab in readme)
let me check
yes
And bot is not joining channel? And no errors in console?
error: Did not enter state ready within 10000ms
Try adding intent 'GUILD_VOICE_STATES' in base client, maybe that will help
i have 32767
But what 32767? XD
xD
{ intents: 32767 }
Oh, this way xD
xdddd
But what means that intent XD
Try changing it to https://discord.js.org/#/docs/main/master/class/Intents?scrollTo=s-FLAGS
All intents from here
just all? xd
Yes, that will give your bot the best functionality XD
intents: "GUILD", "GUILD_MEMBERS", etc, etc
nothing new
:/
I could not join the voice channel: Did not enter state ready within 10000ms
Whats your channel variable?
Textchannel or voicechannel?
@rare cosmos
voicechannel
message.member.voice
tysm, I was so annoyed by the bot disconnecting often.
@solar crypt
That's a problem!
Use message.member.voice.channel (add .channel after voice) @rare cosmos
ok
Working? xD
so basically message.member.voice.channel.id
@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
ok
I could not join the voice channel: Did not enter state ready within 10000ms
Uhm
Try console.log(channel)
And send result
<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
So basically bot see voice channel
ig so xd
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
I know whats wrong
Change channelID: channel.id to channelId
Same with guildid
wut :d
channelID => channelId
guildID => guildId
U have function createAudioResource somewhere, try adding { volume: 3/10 } inside ()
ok basically it works now but it doesnt play music :P
and its taking really long to join the channel
U need to create player, link it to connection, then create resource and play it XD
const stream = ytdl(song.url, {filter: 'audioonly'});
const player = createAudioPlayer();
let resource = createAudioResource(stream, { inputType: StreamType.Opus });
player.play(resource);
queue.connection.subscribe(player);
What is queue variable, and what error do u have in console
i dont have any errors
Uhm
const queue = message.client.queue.get(message.guild.id);
Oh okay... But have u got aby queue.set in code?
wut?
client.queue.set(something)
Have u got something like that?
yes
client.queue = new Map(); is in index
Try changing inputType from StreamType.Opus to StreamType.Arbitrary
it works :DDDDDDDDDDDDD
Nice :D
ty so much
np 👍
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?
Using ytdl? You can diagnose memory with process.memoryUsage().heapUsed
I use ytdl-core.
I already restarted the bot so failed to measure the load. :(
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
upper pic is after 48hours.
Big pupple area is JSArrayBufferData
oh I see. I'll find about youtube-dl-exec
Mostly this when I use youtube-dl-exec, it goes up and down a bit, not just static 17mb
Thank you for your advice :)
Shoud I create a AudioResource as an example source of the voice module?
can someone tell me why guildvoiceAdapterCreator is not assignable to voiceAdapterCreator in joinvoicechannel function
Hey, do you know that you need to manually terminate stream of ytdl-core, player.stop() doesn't destroy it completely.
YTDL core explicitly tells everyone to destroy stream created by it.
//@ts-ignore on top of it might help to solve it.
i aready tried it, after running it gives an error
So try my solution that I gave to you
yes it worked
Thanks
(guildvoiceAdapterCreator as voiceAdapterCreator)
@vocal valley Free ?? Thought of alternatives ??
This weekend 👀
Okay 👍
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
do you even need to join the vc at all if you're only moving other people @subtle granite?
How im implementing it yes i want to
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
TypeError: queue.connection.stop is not a function
why do i get this error?
youre trying to stop a voice connection?
is there a way to change voice channels without initiating another( destroying the old voiceConnection then creating a new one )
unfortunately not
u will have to obtain a new voiceConnection and destroy the old one
thanks
Do you need to destroy the old one ??
It automatically switches the connection right .
As written here after the code : https://deploy-preview-595--discordjs-guide.netlify.app/voice/voice-connections.html#creation
id destroy it to be on the safe side
but it should switch automatically
i was asking it for a implementation on the music-bot example and i implemented it like this its hacky but it works:
how can join to voice channel in v13
StageChannel.createStageInstance({ topic:"Something" , privacyLevel: "GUILD_ONLY" } ) isn't creating any instance , any solution ?
That is a asynchronous, so maybe await this code.
someone???
right
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
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?
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?
okay
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?
pins
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.
That isn't really helpful
there guide, https://discordjs.guide/voice/
nope not working , it was working fine in previous commits !
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
You need to install the package @discordjs/opus
@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.
Have the same problem
I had this problem too but after I reïnstalled it it worked for me again
How can i receive output from a voice channel?
What module did you reinstall?
@discordjs/opus and opusscript
yeah, it become empty when updating to v13
do npm ls discordjs/opus
I think it's not possible with Discord.js as the bot by default has already been deafen
You used to be able to do it with discord.js v12
i don't see why they would disallow it
and voice become empty too after updating, lol
Yeah, but there you were able to deaf yourself and undeaf yourself
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
})
Ohw I never saw that option 😅
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
Delete node_modules and package-lock.json and npm install, then it works well.
anyone's stage channel createInstance working ?
I am stuck with it
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
Assuming you using ytdl-core
Ytdl(link, { filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1048576 * 32 });```
highWatermark there is 32mb
Thanks it's working 🙂
Do mind that you need to terminate the stream manually. https://github.com/fent/node-ytdl-core#streamdestroy Else you going to have memory leak issue
At what point do I have to end it manually?
according to the documentation Stream#destroy(). I dont use it though
Is youtube-dl-exec better than ytdl-core ?
yeah
youtube-dl takes more time to launch on other side, it supports playback though many sites
ytdl-core only supports playback of youtube only on other side, it takes less time to play song.
Now it is personal decision.
hey, where do I get the voiceAdapterCreator from for the joinVoiceChannel function? :o
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.
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
and i have no errors
You forgot to do :
connection.subscribe(player)
oh ok
Thanks for your advice!
👍
okay thanks, but also how can my bot be a speaker in a stagechannel?
guildMember.voice.setSuppressed
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.
^ignore it for now, voice still use discord-api-types v0.19, while discordjs used v0.22, so that error occured
uhmm ok
is there any method can stop current playing resource?. Like connection.dispatcher.end()
player.stop(); 🤔
Ok i'll try it later, thanks for your answer
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
As far as I know and as far im trying to implement the new .join functions is all that I know that , that you have to use @discord.js/voice to join, play and manage you Voice Activities. I found out that the function to play is now player.play(); player is an DiscordVoice.createAudioPlayer();
Thats all I know so far, hope that helps 😄
It’s very complicated but when you know how to manage it then you make masterpieces
do you know how to mange the new voice?
I try but I can’t yet
I can show you guys example code
Wait imma turn on my laptop
omg, that would be very helpful. Thanks
But i only want it to join the channel
DiscordVoice.joinVoiceChannel({
channelId: message.channelID,
guildId: message.channel.guild.id,
adapterCreator: message.channel.guild.voiceAdapterCreator,
});
you have to use @discordjs/voice for that
check the pins
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
Thank you so much, is createAudioResource a DiscordJSVoice Function?
hi
yes, you can declare it here
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice');
thanks
I guess channelID has been changed to channelId
How can bot join the stage channel?
Yeah, that's true thx
Just like u would with a voice channel
lmfao wish i had found that guide earlier
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!
})
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
Ah ok, thank you!
thats how I feel now after I tried for 5 hours xD
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);
});
})
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?
well the package i was using, uses v12 so 😩
did the bot connect to your voice channel?
Yes, and it sends the playingEmbed
this will be helpful
anyways i can change th function to JoinVoiceChannel?
which one, you can go search for iCrawl discord music bot on Github, and base on that to update your code to v13
serverQueue.voiceConnection.subscribe(player);
TypeError: Cannot read property 'subscribe' of undefined
const serverQueue = queue.get(guild.id);
I'm kinda stupid at English so I don't know how to explain it
Try to explain...
@subtle granite your code is missing so many things
So as v13 finally released now, where would I find the example of voiceReciever?
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?
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?
Under what circumstances would CommandInteraction#member result in an APIGuildMember and not a GuildMember?
I'm asking as this is not documented
same question
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()
})
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
Do you have the voice state intent?
If so, grab some debug logs from both discord.js and discordjs/voice.
Ignore me lol
docs?
I was looking at playing audio on accident
I hate that i somehow get no audio
// 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
But i like how the bot defeans itself tho
how to get the people in the vc
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
bruh
What have you defined channel as?
man this is different
and a lot harder to get it to function
How would i check if i'm already in a voice channel?
interaction.channel ?
bruh
@celest basalt do you know?
yes yes
very simple
"simple", it would work for me i guess but sodium just doesnt wont to install
libsodium is enough, sodium is hard to install, also for nodejs v16 above, you need to put in property highWaterMark if not it will error abort frequently
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?
libsodium is enough?, nice im trying sodium to get to work but it doesnt xD
Ytdl(link, { filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1048576 * 32 });``` like this
actually saved my sanity ty
was about to loose it ngl
and ytdl doesnt end it stream automatically, you need to end it manually else got issue memory leak
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?
invalid resource type ig
got the GUILD_VOICE_STATES intent?
How is it an invalid resource type?
it isnt, ive the same and works for me, pretty sure
I need to know what is wrong then
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]});
}
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
@subtle granite got this?
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
How do I get the voice channel ID of the bot?
never mind fixed it by not using ytdl discord
what do you mean?
The current voice channel that the bot is in, the ID of it
No :(

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]});
}```
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```
You probably want one of the others on windows.
Then try npm i tweetnacl
Seems to be a problem with vs as well, maybe you should npm config set msvs_version 2015 --global
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
Put queue in your queueConstruct and do something like serverQueue.queue.delete(<id>)
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
All my songs is serverQueue.songs, and serverQueue.songs.delete() is not a function
~~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 😄
receive from voice
The guide in the pins explains how to use the new voice package
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 --
AudioPlayerError: aborted``` i really dont know about this error anyone help?
I got same error but I don't know the reason
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.
That error is from ytdl and nodejs v16. You need to put in highWatermark like this #archive-voice message
oh I see Thanks!
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);
}
Can someone give me a tip for making the bot the voice call in discord.js v13?
in v13, there isn't join method and leave method in VoiceChannel
then how can i join a channel??
const { joinVoiceChannel } = require('@discordjs/voice');
joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator
})
The abort error does not occur, but the highwatermark is too high, so there is a disadvantage that memory usage is too large during song playback. 😦
Yeah, can lower it or later I will publish some example using youtube-dl-exec
Is there any methods like .on("end") to check whether a resource is completely playing?
player.on(AudioPlayerStatus.Idle, () => {
connection.disconnect();
})
I'm using it with idle, but that's not recommended
I'm using idle too, but when i use skip command it skips so many songs
It says that i should set something like setMaxListenner
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.
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
I'm testing the youtube-dl-exec.
I am unable to install sodium even after running
npm install --global --production --vs2015 --add-python-to-path windows-build-tools
pls help
install libsodium instead
ohkay
Which one is better between tweetnacl and libsodium-wrappers?
libsodium
Is there any difference?
Not very sure on the difference, since I did not measure any quality/quantity
thanks
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
.channelId? 
oh i see
in my eval it works
.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
do you have the GUILD_VOICE_STATES intent?
Stage Channel.createStageInstance() isn't working , but it was working on deprecreted versions , it just suddenly not working from yesterday
how do we join a voice channel? im getting so confused
https://github.com/discordjs/voice/tree/main/examples/music-bot/src have you take a look at this ?
is the voice module already included in v13 and i can uninstall @discordjs/voice ?
nope
i see, thanks!
two seperate package
just to be sure, "@discordjs/voice": "^0.5.5", is the latest version correct?
yeah