at MessagePayload.resolveData (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\structures\MessagePayload.js:184:36)
at TextChannel.send (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:167:61)
at Object.execute (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\events\messageEvent.js:27:23)
at Client.<anonymous> (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\index.js:42:46)
at Client.emit (node:events:394:28)
at MessageCreateAction.handle (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:18)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:345:31)
at WebSocketShard.onPacket (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
at WebSocketShard.onMessage (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
PS C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot> ```
#archive-voice
30636 messages · Page 20 of 31
.setTitle('You may not run this command at the time.')
.setDescription(`You may run this command in ${ms(a - Date.now(), { long: true })}`)
.setColor('RANDOM')
message.channel.send({embeds:embed})```
pls help
nvm fixred
hey guys, id like to add a play music feature to my bot, where do i start?
You can read the discord guide on how to do it. Just follow this link and read up on Voice Connections, Audio Player, and Audio Resources. That's all you should need. https://discordjs.guide/voice/voice-connections.html
Hi, I've been trying to make a music bot. Right now I'm just trying to make it so that it plays the next song in the queue, it'll play the next song in the queue once but after that it stops playing.
https://sourceb.in/PL8vs2jJpe
You shouldn't make a new AudioPlayer for each song, you can reuse the same one and just call .play() on it again. The reason it only plays the next song once is because you create the idle listener on your original player and then replace it with another one, so effectively the listener doesn't exist anymore.
ohh ok
So uh, im trying to play from an .ogg file, and the audio just isnt playing. The code is basically this:
const resource = createAudioResource('./data/cache/current-audio.ogg')
player.play(resource);
connection.subscribe(player);
And the music works fine with a direct stream, so i'm not sure why its not working with a file path. The file itself is present and i can play it with other software locally, so that isn't an issue either. The player isnt erroring either, since i have it log errors in console, and nothing shows up.
its not working with any file in general, not a .ogg specific issue im having, tried mp4 and webm too
This is relative path, convert it to absolute path
does it not take relative paths at all?
No it don't take relative paths
nope its not working with the absolute path either, same issue, nothing is playing and no errors either
Do you have GUILD_VOICE_STATES intent ??
as i said, everything works fine if i use a direct audio stream, so its not a permission issue
Show me final code with absolute path
its... literally the same code with the absolute path... how would you verify my absolute path anyway?
existsSync works fine
i use it to check before trying to play the audio, and it passes the check
again if the path was wrong it would error because it wouldnt be able to find the file
its able to create the resource, i log it and it shows the file im trying to play
debug your dependencies
Ok so the issue seems to be that the audio player cant switch between playing from an Internal.Readable resource to a file resource? Unless im mistaken.
If i try to play from a stream and then play a new resource from a file, it doesnt play, but if i play from a file first its fine
@vague remnant It would be great if you debug your dependencies. Since ffmpeg-static has some issues while playing from a file.
im not using ffmpeg-static
i have ffmpeg installed on the os
How to understand that a bot has finished playing a track to start a new one?
have a callback on the AudioPlayerStatus.Idle event for your audio player
hi, I wanted to write a code in the event we know as "voiceStateUpdate" in v12, but this situation has changed in v13. What should I do in v13? (I just started using v13e. I don't know anything)
What's the problem you're having in v13?
There is no "voiceStateUpdate" in v13. i want to know what i can use instead @edgy burrow
voiceStateUpdate exists in v13
oh🤧
what can i use instead?
It exists.
voiceStateUpdate exists
I understand what you want to say. Is there anything else in his mission?
like any other event
voiceStateUpdate is the only voice event
so I can't do in v13 what I can do in v12?
Yes you can, you can use voiceStateUpdate
but im using v13
Yes, it's also a thing in v13
It did not get removed in v13
(event) Client#voiceStateUpdate
Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
Do you have the GUILD_VOICE_STATES intent?
let me see
oh no. thank u <3
If I created a player how would I be able to pause it in a different file
player.pause() pauses the player
player.unpause() unpauses it
Yea but how would you access the player
I defined it in a different file
Could someone please explain to me the reason for the following error - i.e. what it means/what causes it?
Error: Cannot perform IP discovery - socket closed
at Socket.<anonymous> (/app/node_modules/@discordjs/voice/dist/networking/VoiceUDPSocket.js:120:52)
at Object.onceWrapper (node:events:509:28)
at Socket.emit (node:events:402:35)
at socketCloseNT (node:dgram:755:8)
at processTicksAndRejections (node:internal/process/task_queues:82:21)
export a function that can access it, and then use the function in the other file, or just export the player
wtf
Does anyone know how to trigger a function when an audio player finishes playing an audio resource? I want to run several lines of code as soon as an audio player finishes playing a song.
listen for the player idle event
doesn't output "ok", why?
Thanks!
pls help 🙂 doesn't showning the "ok man"
:/
import exports
Yea but how would you call the player
I recommend you learning some js mate
I recommend reading docs mate.
From connection,
Just get connection using this [ https://discordjs.github.io/voice/modules.html#getvoiceconnection ]
and then get player by connection.state.subscription.player // Works only if you ran connection.subscribe(player)
Rule 2, this is for discordjs help. Not just js help.
Umm it was for discord.js/voice I think you misunderstood my question?
Error: Cannot find module 'node:events'
Require stack:
- /home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/client/BaseClient.js
- /home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/index.js
- /home/runner/QuerulousSandybrownExams/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
at Function.Module._load (internal/modules/cjs/loader.js:667:27)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/client/BaseClient.js:3:22)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/client/BaseClient.js',
'/home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/index.js',
'/home/runner/QuerulousSandybrownExams/index.js'
]
}
Please update node.js to version 16.6.0 or newer!
• Download
• Linux (nodesource)
discordjs.guide results:
• Interactions: Buttons
• Interactions: Building and sending buttons
@lost creek Use docs command in #app-commands , not here.
Umm
Sometimes a strange situation happens:
I turn on the track and I have a check if there is a queue or not. If not, then the specified track is included. If there is a queue, then the track is recorded in the database for the next playback.
Also I have a check for PLAYER IDLE STATE.
The problem is that sometimes after the end of the track I wait about 2-5 minutes and turn on the song again, then he skips it and clears the queue as it becomes empty. Can you help with this, please?
Code where you have listener for player idle state ??
I tried to include a track without a queue and without a listener. The result is the same...
I believe this issue is related to connection.subscribe(). Now I will try to solve it...
No, that's not the problem
Show code without queue system
and also skip code
const connection = voice.joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const audioplayer = voice.createAudioPlayer();
if (!audioplayer.subscribers[0]) {
connection.subscribe(audioplayer);
}
const resourceFirst = await voice.createAudioResource(`{HERE PATH TO TRACK}`);
console.log(audioplayer);
audioplayer.play(resourceFirst);
@carmine timber Here
And SKIP
const connection = voice.getVoiceConnection(message.guild.id);
connection.state.subscription.player.stop(true);
Does this code runs whenever you run play command ??
This code is very wrong approach for playing music.
You are creating a new Player everytime you run play command.
This is main issue you are facing.
Oh, snx!
How to get a text channel from event?
which event ??
audioplayer.on(AudioPlayerStatus.Playing
So i'm still having the issue i was having before, essentially, if i play an Internal.Readable resource from a stream, then i play from a file, nothing plays, and the player doesn't error either.
I have all the dependencies installed i think? heres the debug for it:
Core Dependencies
- @discordjs/voice: 0.6.0
- prism-media: 1.3.2
Opus Libraries
- @discordjs/opus: 0.5.3
- opusscript: not found
Encryption Libraries
- sodium: 3.0.2
- libsodium-wrappers: not found
- tweetnacl: not found
FFmpeg
- version: 4.2.4-1ubuntu0.1
- libopus: yes
Also @discordjs/opus gives me npm warnings when i install it
I can't seem to find in the code where the VolumeTransformer pipes data through ffmpeg
Hello everyone sorry to disturb but i just followed a tutorial to create a music bot but the bot won't join the channel ... 🙃
An i have no error
Is it just me or is just simply playing a simple audio file far harder in v13 than v12?
not really I really like the new player thing
kinda upset that v13 requires a non LTS version of Node
Will be LTS soon
i wont ever be able to go to anything higher than v14 LTS on my hardware (older homelab) sadly
I'm writing double the code to achieve the same thing, and just making sure I am not going wrong somewhere haha
is there a way I can await an audio resource becoming playable ? like wait 10secs to see if it will become playable otherwise destroy it
you can setup a timeout urself
How can i listen to the 'stateChange' event on a second .js file aside from the main.js file?
instead of having the player.on('stateChange' , ...) code on the main.js have it on the musicplayer.js file where i have the play skip queue and other commands
you can put the player into that file?
if main.js has nothing to do with the music aspect why have the player be there
the player is on the second file
but when i use player.on('stateChange' , ...) on this file the event is never detected
You are registering the stateChange event in reproductor.js?
no
that should be done with the player.addEventListener method?
no you can use player.on()
the main issue is if the player isnt the same instance that is actually playing the music
if they are different players events from one of them wont trigger for the other
there's only one player across all files, which is created there in reproductor.js
will we have a seek option with djs voice in the future?
If you are attaching this in message event, just pass the message directly. [ same for interaction ]
How can I make my bot join vc?
const channel = interaction.member.voice.channel;
channel.join()```
Not working
K
How can I make my bot join vc?
const channel = interaction.member.voice.channel;
channel.join().then(connection => {
console.log("Successfully connected.");
}).catch(e => {
console.error(e);
});```
getting channel.join() is not a function
Not working ;-;
not working because you havent try it yet
See
const { joinVoiceChannel } = require('@discordjs/voice'); const connection = joinVoiceChannel({ channelId: channel.id, guildId: channel.guild.id, adapterCreator: channel.guild.voiceAdapterCreator, });```
Aftee that what to do im confused ;-;
you didnt define the channel id, guild id, adapter properly
Working Tysm 😅
I'm trying to make a music bot and it isn't reading my messages from discord plus I'm new to js as well. Can anyone please take a look
const { version } = require('os');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const ytdl = require("ytdl-core");
const PREFIX = '!';
var servers = {};
client.on('ready', () => {
console.log(`The bot is online!`);
});
client.on('message', message => {
console.log("Before switch");
let args = message.content.substring(PREFIX.length).split(" ");
switch(args[0]){
case 'play':
console.log("play reached");
function play(connection, message){
var server = servers[message.guild.id];
server.dispatcher = connection.playStream(ytdl(server.queue[0], {filter: "audioonly"}));
server.queue.shift();
server.dispatcher.on("end", function(){
if(server.queue[0]){
play(connection, message);
} else {
connection.disconnect();
}
});
}
if(!args[1]){
message.channel.send("You need to provide a link!");
return;
}
if(!message.member.voiceChannel){
message.channel.send("You must be in a voice channel to play this bot!");
return;
}
if(!servers[message.guild.id]) servers[message.guild.id] = {
queue:[]
}
var server = servers[message.guild.id];
server.queue.push(args[1]);
if(!message.guild.voiceConnection) message.member.voiceChannel.join().then(function(connection){
console.log("lol dewd");
play(connection, message);
});
break;
}
});```
It should be playing the songs just by this code but my guess is it's not reading the messages
This is v13 voice help, ask this in #archive-djs-v12-voice-deprecated
okay thanks 😃
hello why this can't working fix ${client.voice.connections.size}
@carmine timber
This has been removed
hu now what we do to see status of connection?
client.voice.adapters.size
oh okay thanks
Do I have to have discordjs/voice installed in order for voiceStateUpdate to work?
no, you need intent
Ahhhhhhhh
Gotcha. Thanks.
is there any way to get the connection and destroy it other than creating the variable connection = joinVoiceChannel() ?
i have a question, what is group ?
ty
Is there a way to trigger an event when audio player finishes playing resource?
when the audioPlayer state changes from playing to idle
how can I know if the bot actually disconnected or if it just switched voice channels?
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
``` how do i get the channel?
you can use client#VoiceStateUpdate for that
i mean when i use this code this code, it sais that channel is undefined
u will have to define channel as an instance of voiceChannel
either by getting it from cache or from a member that executed a command
const channel = bot.channels.cache.get('channel-id');
```?
but I use the connection.on("disconnect")
u dont really need to do that. As you can just pass the channel and guildeId directly
kk
u will still need an instance of guild tho in order to get the adapter
wdym
im confused, how do i do that?
which event are you calling the joinVoiceChannel in?
in the main file
event
not file
any xd
in cron
it repeats every minute
do u wish the bot to join the channel when u send a command or automatically on login?
im making it so it joins the channel at 21:37
alright
i want to at least
in that case you can just get the guild with client.guilds.cache.get(guildID)
how then
mistyped it as cant. Thats how you can get it. My bad
const connection = joinVoiceChannel({
channelId: "channel id",
guildId: "guild id",
adapterCreator: guild.voiceAdapterCreator,
});
```so you can just do this. Where `guild` is `const guild = client.guilds.cache.get("id")`
TypeError: Cannot read property 'voiceAdapterCreator' of undefined
did you define guild?
yep
send me the code around that part now
Youtube-dl is not workin when it joins the voice channel it plays the Silence_frame
Help me pls
what is this error guys ?
show the whole error message
only 3 line
show the whole console
only that one

its not a error message, its a warning that your using experimental features that may soon be removed i think
just read
i think the issue is from node.js ver 16.11.0
not djs related btw
My bot joins the channel but doesnt play anything.
It can parse the link/search and gets the video without any errors but doesnt play
It isnt lighting up green its just sitting there
try with another song
or try with file
Do you have the GUILD_VOICE_STATES intent?
Yep
Can you show your join and play music code?
You need to call connection.subscribe(player) to tell you connection to stream whatever the player is playing
I assume after the player.play no?
At any point when both are initialized, doesn't matter.
Nice it works now thank you! 😄
Hello
Is any way we do some eval command bot automatically least all vc there it playing songs
I notice sometimes when it buffers or lags it plays it rapidly to get back to where it should be. Is there any solution to this or is this a downside that isnt solvable?
How i can check if my bot is the only user in a voice channel?
my bot plays music, but i will that he leaves when the channel is empty (regardless if he play music or not)
discordjs.guide results:
• Library: Handling disconnects
• Popular Topics: Missing permissions
player.on(djsvoice.AudioPlayerStatus.Idle, () => {
player.stop();
})
You need to have that after the play part
ah
idk, but dont work...
can i get a number of the users they in the same voice?
You can use channel.members to get all guild members in that channel > https://discord.js.org/#/docs/main/stable/class/VoiceChannel?scrollTo=members
yes! Thats it! But how i get the voice channel id?
channel.id
and how i can check if my bot is in this channel?
yeah, thats simple stuff xD
You can use getVoiceConnection(<guildId>) to get the output of a VoiceConnection object or undefined depending on if your bot is in a channel on that guild.
That's a function from @discordjs/voice
and from this object i need only the channel id. But i cant find it
sorry im dump
i found it haha
BUT THANKS!
I said read the pin in this channel ._.
oops
My bot won't play audio when there's 6 people in the voice channel at once
He can join, and he'll play about 1 second or so of audio before just stopping, if I go to a VC with it alone it works fine
I feel like this might be a type bug 🤔
guildId: interaction.guildId,
channelId: voiceChannel.id,
adapterCreator: interaction.guild?.voiceAdapterCreator
});```
If I assert the type as DiscordGatewayAdapterCreator it works and the bot joins the channel with no errors.
Unless I am missing something.
const { createAudioPlayer, NoSubscriberBehavior, joinVoiceChannel, createAudioResource } = require('@discordjs/voice')
module.exports={
description:'',
execute(bot,interaction){
try{
const channel = bot.channels.cache.get('895765320034291736');
const guild = bot.guilds.cache.get(`895765319560331337`)
const connection = joinVoiceChannel({
channelId: `895765320034291735`,
guildId: `895765319560331337`,
adapterCreator: guild.voiceAdapterCreator,
});
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
connection.on("stateChange",(oldState,newState)=>{
console.log(oldState,newState)
})
const resource = createAudioResource('./data/barka.mp3');
interaction.reply('t')
player.play(resource);
}catch(e){console.log(e)}
}
}
hey guys, why doesnt the bot join the vc?
channel.join is not a function
if you use Discord v13, that way of joining a voice channel is no longer a thing
You need to use @discordjs/voice package
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});```
const player = createAudioPlayer();
const resource = createAudioResource('link or path to file');
player.play(resource);
thats how u play music
I got the paste from https://discordjs.guide/voice/voice-connections.html#cheat-sheet
Are you sure you have the right guild and channel id?
yep
You issue is that is just doesn't join? No error?
@subtle granite thats how u play sound
Can you change it to this:
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
});
and try again?
works, why is the bot deafened tho?
That's the standard. You can add selfDeaf: false, in your joinVoiceChannel() to disable it.
❤️ love u xd
You need FFmpeg to play audio. You can use @discordjs/voice's generateDependencyReport() to see what dependecies you will need to play audio. > https://discordjs.guide/voice/#debugging-dependencies
now the music playing doesnt work
Ah right, I saw this in the first code shot you saw but forgot to mention it. You also need to call connection.subscribe(player) to tell your connection to stream whatever the player is playing.
no
npm install ffmpeg-static
Read the page I linked, it explains it.
connection.subscribe(player)
Error: Cannot play audio as no valid encryption package is installed.
- Install sodium, libsodium-wrappers, or tweetnacl.
- Use the generateDependencyReport() function for more information.
whitch do i install?
That's not why it didn't join voice chat, but you're right that was missing xD.
Sodium is only linux, other two doesn't matter take your pick.
Try doing this instead?
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator
});
your a genious, thx
Yeah, we already fixed it by doing something similar to that, thanks for trying to help though.
Haha, don't mention it.
My bot doesn't want to play audio when there's too many people in the VC and I can't figure out why. No error or anything, it just doesn't want to play
There are no events on player.play()
A few things. Change line 62 to player.on('idle', () -> { Also, channel.leave() is not a function.
Yes as thats not a thing
nvm
Playing songs with the AudioPlayer and joining voice channels are two separate things. You have to do both.
Are you using v12 or v13?
I see code for both
In your joinVoiceChannel() the ids should be strings, not ints.
how to disconnect a bot from a channel
connection.destroy()
That's usually better, yeah.
ok
You still have to subscribe the connection to the player: connection.subscribe(player)
Just put it after your .play() it doesn't really matter.
No, you can't call .play() on a connection, and that .on will also make you crash.
- create player
const player = createAudioPlayer() - create a connection
const connection = joinVoiceChannel({...options}); - subscribe the player to the connection
connection.subscribe(player);
Does that help?
You just sent a screenshot when you had player.play(...)
At any point where both the player and connection exist. It doesn't matter where.
Legit this @subtle granite
apzrn, have you recently upgraded your Discord.js version to v13 under a v12 codebase?
Ahhhh
v13 is a whole different ball game
Everything to do with voice has changed basically
Matte told you the .on part was a problem. Not the .play(). What he said was because you need to call .on(...) on something and the way you did it, it would've been on the output of some other function which doesn't work. That's why I said change it to player.on('idle', () => { connection.destroy() }
If it helps azprn, I have started developing my new v13 bot I will send you a file that has a basic implementation
https://github.com/jack3898/discord-youtube-bot-2/blob/2d9548c8f723a7fb85dfb06a34c358738acd2fb8/src/commands/modules/play.ts
It is TS, but it shouldn't be hard to filter that out hopefully it helps you
For simplicity before you start implementing @discordjs/voice just remove everything that has to do with v12 voice in ur code. Otherwise youll end up with a mess
Yeah Matte, there was so much in my old youtube bot that would need refactoring that I just started a new project entirely 😂
npm i tweetnacl
This, still.
Not the FFmpeg part, but the debug dependecy part @subtle granite
wym?
Can you send a screenshot?
What was it before? Do you use a transparent profile picture or something? I am not sure but maybe discord has a background colour set in the profile pic for a transparent picture?
I doubt it is anything serious though :)
Does the bot play music or no?
Huh maybe it's a Discord quirk I am not aware of 
Do you have the GUILD_VOICE_STATES intent?
Yes
Yeah, that's fine.
yeah you only specify once you init the client
have you hard-coded the resource for the version of the code you are testing?
or should I say not coded in
Yeah, was just about to mention that haha.
well in the code you provided, the createAudioResource method does not have a valid audio bitstream as an argument
Most tutorials are still from v12, since v13 is still only a few months old.
Yeah also like Touche says, v13 is wayyyyyy different
Make sure when you watch video guides, you watch for discord v13. It's vastly different in almost every aspect
You can input that stream object into the createAudioResource(stream), but the rest of the if-statement in this iswrong. I'm actually surprised this hasn't crashed you yet. Just remove all of that and use the stream object.
well, my old youtube bot I made that has quite a few features became wayyy too much hassle to refactor to v13 because v13 is so different. I just started a new project instead, I think that would be the best way to go or at the very least archive big chunks of v12 code and rewrite with v13.
Ayyyy 😂
Don't get rick rolled too easily 👀
One thing I do notice in the code you sent is that you're passing in an instance of Message into your function but my code uses the new CommandInteraction instance (the variable called "interaction")
So you may need to swap out the "interaction" variables for "message". I can't guarantee that will give no errors though!
Ah yes, you're using commonjs. My codebase uses the new ES6 module syntax. It should be safe to swap it to const.
Ok one glaring obvious thing I forgot to mention is that globals is my own creation so it will not exist in your project.
In my code globals contains a variable called "audioPlayer" which is simply the result of createAudioPlayer()
So delete the whole globals import and just create a variable called player which is created with createAudioPlayer()
By the way, the reason I did that is because you do not need to create an audio player for every command. You can do it once and reuse it
If by other one you mean old project then maybe. My project file is written for my environment so you would need to understand what to swap out.
I think at this rate, you should create an empty sandbox project and in one JS file get the bot to join and play audio as a way to grasp how the new adio system works. Then, you should know enough to be able to translate that to your current project. I am running out of suggestions, so I think from now on the best thing to do is the above with a mix of reading documentation.
https://discordjs.guide/voice/voice-connections.html#playing-audio
https://discordjs.github.io/voice/index.html
In that case my above response applies!
maybe this still const resource = createAudioResource('link or path to file')
as mentioned before there is a hard coded invalid value in there
as a test get any mp3 and put the path to the mp3 in there.
How can I test for the bot and a certain user being in a voice channel together with no other users?
I want the user to be able to disconnect the bot if they are the only one in the vc listening to the bot, even if they don't have the right permissions.
In other words, how do I access the channel of a current connection? I can use the .members property on the channel
i just tried
const voiceConnection = joinVoiceChannel({
channelId: member.voice.channel.id,
guildId: member.guild.id,
adapterCreator: member.guild.voiceAdapterCreator
})
and it gives me this error
TypeError: Cannot read property 'set' of undefined
at D:\tecno\Documents\code\node\Oneki-bot\node_modules\discord.js\src\structures\Guild.js:1342:34
at new VoiceConnection (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\VoiceConnection.js:76:25)
at Object.createVoiceConnection (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\VoiceConnection.js:515:29)
at joinVoiceChannel (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\joinVoiceChannel.js:18:30)
at D:\tecno\Documents\code\node\Oneki-bot\js\scripts\util.js:80:53
at new Promise (<anonymous>)
at Object.joinVoice (D:\tecno\Documents\code\node\Oneki-bot\js\scripts\util.js:64:16)
at D:\tecno\Documents\code\node\Oneki-bot\js\commands\play.js:26:93
at processTicksAndRejections (node:internal/process/task_queues:96:5)
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Ty
peError: Cannot read property 'set' of undefined".] {
code: 'ERR_UNHANDLED_REJECTION'
}
any solution?
number 1 set is undefined so define it number 2 set is not in that code so so actual code.
the set is code from discord.js, so i can't define
ion knoe den
???
Current node-opus package is deprecated?
yes
Hey, I'm attempting a simple script to record, and then play back voice data from a specific user in a voice channel. The following script records opus packets into the "bufferData" array, however it fails to play it back: ```js
const opusStream = receiver.subscribe("472158867183108118", {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
const bufferData = [];
opusStream.on("data", chunk => {
bufferData.push(chunk);
})
opusStream.on("end", async () => {
var player = createAudioPlayer()
var resource = createAudioResource(bufferData, {type: "opus"})
connection.subscribe(player)
player.play(resource)
})```
When I installed @discordjs/opus it logged "Found 1 vulnerabilities, 1 severity" what does this mean
discordjs/opus has some dependencies which have fixed some vulnerabilities in their latest releases, but discordjs/opus has not updated its dependencies.
Hi. Question. I'm using @discordjs/voice and I used joinVoiceChannel for joining the channel. What can I do for leaving the channel? It's my first time using it.
const connection = getVoiceConnection('guild id') // get this function from discordjs/voice module.
connection.destroy() // Destroys the connection and now it can be used again [ Leaves vc and destroys connection ]
// OR
connection.disconnect() // [ Leaves vc only ] This can be useful if you want to rejoin your bot
Hey why this error occurs and my bot leaves the voice channel or stop playing the song without leaving the voice channel.
And this happens multiple times
It occurs if that port is already in use by system. Either socket is not closed completely or some other issues. Restart your system and you are good to go
It joins the voice channel and start to play the song but at the middle it suddenly stops playing and when i see console i receive this error
Hmm i did that multiple times but still i receive the same error. Sometimes it works properly and sometimes it doesn't
Windows or Linux ??
Linux
Which VPS ??
Hmm it's aws i guess so but don't know properly as i use a pterodactyl based host not my own vps
So it is aws, then you need to allow all outgoing connections in your port forwarding settings
Is there a way to play a mp4 in a video o screen sharing by the bot?
Hmm then i guess i will ask the host owner to do that
Not possible
Rip
👍
Why this thing happened
Music stopped in stage but bot is still in stage
you get ratelimit
You are getting ratelimited by youtube

how to know for how long I'll stay rate limited?
in your case, miniget will get a header named as Retry-After that contains info about how long you will stay rate limited.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
anyone know what would cause AudioPlayerError: connect ETIMEDOUT ?
How can I smoothly transition between audio resources like transitions instead of just cutting between them?
is the only way to leave voice channel destroying connection?
you can also use connection.disconnect
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
if(video){
const stream = ytdl(video.url, {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', ()=>{
voiceChannel.leave();
});
await message.reply(`:youGotThis: Puszczam: ***${video.title}***`);
}
```Why .play() is not a funcion?
Because the play method does not belong to connection. play() exists on the result of createAudioPlayer()
connection.play() was a thing in V12 but v13 changes it.
Code
const fs = require("fs")
module.exports.run = async (client, message, args) => {
const channel = message.member.voice.channel;
if(!channel) return message.channel.send({ content: '>>> You need to be in a voice channel!' })
const vc = joinVoiceChannel({
channelId: channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
if(!args.length) return message.channel.send({ content: ">>> Arguments required!" })
const connection = getVoiceConnection(message.guild.id)
files_ = [];
var files = fs.readdirSync("./songs");
for (var i in files){
var name = "./songs" + '/' + files[i];
if (fs.statSync(name).isDirectory()){
getFiles(name, files_);
} else {
files_.push(name);
}
}
console.log(files)
for(var i = 0; i < files.length; i++)
if(files[i] == args[0])
var song = files[i]
const subscription = connection.subscribe(song)
if(subscription)
setTimeout(() => subscription.unsubscribe(), 5_000)
}
module.exports.help = {
name: "play"
}```
Error
``` const subscription = player['subscribe'](this);
^
TypeError: player.subscribe is not a function```
What does this error mean and how do i fix it?
You need to pass the player into your connection.subscribe() function, not a song. And from the looks of things you'll first need to create an AudioPlayer and AudioResource. The guide in pins explains these things.
ok
ill do that then
Hello!
Can anyone tell me (or redirect me to a doc that explains it to me) how to know the play-time duration of the currently playing track (for a nowplaying command). Cause I found nothing on discord.guide or discordjs.github.io...
Thx a lot 🙂
||Edit:
Found it: player["_state"].playbackDuration
||
is there any package to play spotify tracks (not like play-dl) in a voice channel??
you cant play songs from spotify directly
you can get metadata tho and use that to search the same song on youtube and play that
Does anyone recommend any packages for making a musicbot? (Not ytdl since it has alot of issues abborting music)
play-dl is a good alternative to ytdl-core.
thanks ill have a look at play-dl
I cant start my bot, because discordjs/voice returns this error. and idk what to do
pls help, because i was waiting the hole day
try running npm install in the commandline that seems to sometimes work
Hey, I'm attempting a simple script to record, and then play back voice data from a specific user in a voice channel. The following script records opus packets into the "bufferData" array, however it fails to play it back: ```js
const opusStream = receiver.subscribe("472158867183108118", {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
const bufferData = [];
opusStream.on("data", chunk => {
bufferData.push(chunk);
})
opusStream.on("end", async () => {
var player = createAudioPlayer()
var resource = createAudioResource(bufferData, {type: "opus"})
connection.subscribe(player)
player.play(resource)
})```
You can try storing it in a file too see if it actually recorded or if the data got lost.
my bot doesn't play the audio resource, why?
After trying to install @discordjs/opus
Im using node v16 discord.jsv13 btw
when i say $play likeag6 it comes up with you are not connected to a voice channel but i am connected in a vc
I got it playing stuff, but I don't know how I can save the audio into a PCM buffer
And the bot has every permission
const opusStream = receiver.subscribe("472158867183108118", {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
var resource = createAudioResource(opusStream, {inputType: "opus"})
var player = createAudioPlayer()
connection.subscribe(player)
player.play(resource, {seek:0, volume: 1})```
I am planning on making a PA system for Mumble using Discord, however Mumble only accepts raw 16 bit PCM chunks
Not really sure how I can extract the pcm buffer from the opusStream type
Since my error deals with discordjs/opus, is there a way to play using an alternative?
I did require('ytdl') but it can't find the module
And I installed the package
Doing this works great: js const opusStream = receiver.subscribe("472158867183108118", { end: { behavior: EndBehaviorType.AfterSilence, duration: 100, }, }); var resource = createAudioResource(opusStream, {inputType: "opus"}) var player = createAudioPlayer() connection.subscribe(player) player.play(resource, {seek:0, volume: 1})
However doing this does not work
const opusStream = receiver.subscribe("472158867183108118", {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
var writable = fs.createWriteStream('test.pcm');
opusStream.pipe(writable)
opusStream.on("end", async () => {
var readable = fs.createReadStream('test.pcm');
var resource = createAudioResource(readable, {inputType: "opus"})
var player = createAudioPlayer()
connection.subscribe(player)
player.play(resource, {seek:0, volume: 1})
})```
its saying voiceChannel.join is not a function but i defined it as const voiceChannel = message.member.voice.channel;
my bot doesn't connecting in the voice channel ( ready ), why?
fuck me, i don't insert the intent
Guild#me
The client user as a GuildMember of this guild
npm init -y
Do it and you are good to go.
i fixxed it but thanks
👍
Can you try playing back the test.pcm file in some other app to listen if it has not gone corrupted
use the voiceStateUpdate event and look if the newState has no channel but the oldState has one.
Then check oldState.channel.members
(event) Client#voiceStateUpdate
Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
VoiceState#channel
The channel that the member is connected to
VoiceChannel#members
The members in this voice-based channel
do you have the proper intents enabled?
also oldstate.channel.members.size will never be null
at least 0
please send the code, I can't see shit with that gif xD
please send the whole event
PS C:\Users\Timsl\Documents\FarCryDiscordBot> npm i @discordjs/opus
npm ERR! code ENOENT
npm ERR! syscall spawn bash
npm ERR! path C:\Users\Timsl\Documents\FarCryDiscordBot\node_modules\@discordjs\opus
npm ERR! errno -4058
npm ERR! enoent spawn bash ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
``` Anyone know how to fix this error? Im just trying to install discord.js/opus
PS C:\Users\Timsl\Documents\FarCryDiscordBot> npm i @discordjs/opus@latest
npm WARN ERESOLVE overriding peer dependency
npm WARN While resolving: prism-media@1.3.2
npm WARN Found: @discordjs/opus@0.6.0
npm WARN node_modules/@discordjs/opus
npm WARN @discordjs/opus@"0.6.0" from the root project
npm WARN
npm WARN Could not resolve dependency:
npm WARN peerOptional @discordjs/opus@"^0.5.0" from prism-media@1.3.2
npm WARN node_modules/prism-media
npm WARN prism-media@"^1.3.1" from @discordjs/voice@0.6.0
npm WARN node_modules/@discordjs/voice
npm WARN
npm WARN Conflicting peer dependency: @discordjs/opus@0.5.3
npm WARN node_modules/@discordjs/opus
npm WARN peerOptional @discordjs/opus@"^0.5.0" from prism-media@1.3.2
npm WARN node_modules/prism-media
npm WARN prism-media@"^1.3.1" from @discordjs/voice@0.6.0
npm WARN node_modules/@discordjs/voice
npm ERR! code ENOENT
npm ERR! syscall spawn bash
npm ERR! path C:\Users\Timsl\Documents\FarCryDiscordBot\node_modules\@discordjs\opus
npm ERR! errno -4058
npm ERR! enoent spawn bash ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Timsl\AppData\Local\npm-cache\_logs\2021-10-15T11_37_44_895Z-debug.log
PS C:\Users\Timsl\Documents\FarCryDiscordBot>
Is it possible, to call someone private?
No
Thx
const stream = ytdl(song.url, {filter: "audioonly"});
const resource = createAudioResource(stream);
player.play(resource);
song_queue.connection.subscribe(player)
.on('finish', () => {
song_queue.songs.shift;
video_player(guild, song_queue.songs[0]);
});
player.play(resource).on('finish', () => {
^
TypeError: Cannot read properties of undefined (reading 'on')
Where am I supposed to place .on function to make it work?
What's event for player finishing song
How can I play a mp3 on my pc using @discordjs/voice? Now I'm using a url.
You can just define the path in the audioresource
Anybody?
you defined resource, not player. Or what is player?
const { joinVoiceChannel, createAudioPlayer, createAudioResource} = require('@discordjs/voice') //npm i @discordjs/voice
const player = createAudioPlayer();
Hello! I want to make my music bot to play audio form youtube (worked on v12). I managed to make the bot join let connection = joinVoiceChannel({channelId: interaction.member.voice.channel.id, guildId: interaction.member.voice.channel.guild.id, adapterCreator: interaction.member.voice.channel.guild.voiceAdapterCreator}); connection.on(VoiceConnectionStatus.Ready, () => { playMusic(interaction.guild, guildObj, connection); });but I do not understand what is wrong with my playMusic function. I get TypeError: connection.subsribe is not a function.
The playMusic is
const resource = createAudioResource(ytdl(guildObj.music.queue[0], {filter: "audioonly", "quality": "highestaudio"}));
player.play(resource);
connection.subsribe(player);```What am I doing wrong?
you misspelled subscribe
🤦♂️ Have been looking for a mistake for 10 minutes already. Thanks a lot
sometimes 4 eyes are better than 2 eyes 
I believe you need to attach the event to the player and not the subscribe function
Worked ❤️
const stream = ytdl(song.url, {filter: "audioonly", "quality": "highestaudio"});
const resource = createAudioResource(stream);
player.play(resource);
song_queue.connection.subscribe(player);
player.on('finish', () => {
console.log('Song finished');
song_queue.songs.shift;
video_player(guild, song_queue.songs[0]);
});
It seems that 'finish' event doesn't happen even tho a song is finished, why?
Use AudioPlayerStatus.Idle instead
Dont forget to import the type properly
How? I'm supposed to make event 'idle' instead of 'finish'?
Would be new to me that there is an event called finish
Hello again! I play music like that:
{
let player = createAudioPlayer();
let resource = createAudioResource(ytdl(guildObj.music.queue[0], {filter: "audioonly", "quality": "highestaudio"}));
player.play(resource);
connection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () =>
{
playMusic(guildObj, connection);
});
}```1) After a few minutes of a song playing I get `AudioPlayerError: aborted` and the playback stops. What is it caused by?
2) How do I get the `player` from `connection`. I have separate functions for `pause`, `stop` and so on which need to access the `player`. I can get `connection` with `getVoiceConnection(<guild>.id)`. But how do I get `player` from that `connection`?
That's an error caused by ytdl-core. You can switch to play-dl to avoid it.
ah... that's weird. It worked well on djsv12. But ok, thanks. I will look into something else. What about the second?
I would recommend keeping track of the player if that is possible within your architecture it is pretty safe to do so
Guess I will have to do so. But I wondered whether there is something like message.guild.voice.connection.dispatcher.pause(true); in v13
Is there a way to detect an afk user in VC or at least if they're talking / muted?
I dont think any apps play raw PCM data
You are not providing a OPUS head to data that you received. See
How do I check if an AudioPlayer object is playing?
player.state.status == 'playing'
thanks
Why is this an issue
What the f**k is this error and WHY It appears?
MinigetError: Status code: 403
at ClientRequest.<anonymous> (/mnt/c/Users/olegl/GitHub Desktop/ZeroBot-Discord/node_modules/miniget/dist/index.js:210:27)
at Object.onceWrapper (node:events:514:26)
at ClientRequest.emit (node:events:394:28)
at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:621:27)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
at TLSSocket.socketOnData (node:_http_client:487:22)
at TLSSocket.emit (node:events:394:28)
at addChunk (node:internal/streams/readable:312:12)
at readableAddChunk (node:internal/streams/readable:287:9)
at TLSSocket.Readable.push (node:internal/streams/readable:226:10) {
statusCode: 403
}
That thing is annoying! I getting it randomly and I can't debug it!
i feel you but for me it's to even connect to the voice channel lol
this is confusing me so much
I'm pretty sure that's ratelimit.
channelId: message.member.voice.channel.id,
guildId: message.member.voice.channel.guild.id,
adapterCreator: message.member.voice.channel.guild.voiceAdapterCreator,
});``` this is in the docs
Just TS complaining, type //@tts-ignore or something like that above the line.
If I am using multiple files, how do I create an AudioPlayer in the main one, and use it in a command.js
Oh, nice! Thanks discord! All I'm thinking about is putting your servers down with my bot!
Anyway, how can I fix it?
Running servers costs money, you can use them for free, but rate limit just prevents abuse and overload.
You can check your code if you're accidentally making tons of requests or maybe you try looping over every message in a chat or something like that. That's the sort of stuff that would probably limit you.
how to get youtube cookie
That's the problem, there's nothing in my code that could send a ton of requests.
I'm not an expert on the subject though @elder sorrel , I'm sure someone else actually knows what they're talking about when it comes to rate limits.
Not to mention that I could be completely wrong about the whole rate limit thing.
Ok, thank you. Seems like that problem disappeared after restarting the whole server (lol)
Had the same question an hour before today. Ended up using Map <guild.id> -> <player>
That's Forbidden code
429 = Rate Limit
Ah right, that's where I went wrong. Thanks for correcting me.
how to set music volume
Pass inLineVolume to true while creating audio resource and then do this at any point of time.
<AudioResource>.volume.setVolume(0.1)
thx
Error: Cannot find module 'node:events'
Require stack:
- /home/runner/I-FUCK/node_modules/discord.js/src/client/BaseClient.js
- /home/runner/I-FUCK/node_modules/discord.js/src/index.js
- /home/runner/I-FUCK/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
at Function.Module._load (internal/modules/cjs/loader.js:746:27)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (/home/runner/I-FUCK/node_modules/discord.js/src/client/BaseClient.js:3:22)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Module.require (internal/modules/cjs/loader.js:974:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/home/runner/I-FUCK/node_modules/discord.js/src/client/BaseClient.js',
'/home/runner/I-FUCK/node_modules/discord.js/src/index.js',
'/home/runner/I-FUCK/index.js'
]
}
i need help with this error
Do node -v and show me the version
v14.17.1
how exactly?
update your node version to 16
cmd pls
Tag suggestion for @eager crag:
Please update node.js to version 16.6.0 or newer!
• Download
• Linux (nodesource)
global.music_subscriptions = new Map();, global.music_subscriptions.set(guildObj.id, subscription);, global.music_subscriptions.get(guildObj.id);.
Leave that method,
Just get connection by getVoiceConnection through discordjs/voice function
and get player by
const player = connection.state.subscription.player
Why do you need to store if it is readily available ??
Someone has answered me it is not possible.
Have seen your answer now, will try) thanks
It is possible only if you had done connection.subscribe(player)
it says, that TypeError: Cannot read properties of undefined (reading 'player')
how to set a volume with the player? ( external command )
Player variable: queue.player
Connection variable: queue.connection
Volume variable: queue.volume
if (connection.subscription) {return}
why does this line not work?
It's connection.state.subscription.
Thanks
Hii. I need help. How can I know if the bot is playing something? Thanks.
const resource = createAudioResource(<link_to_audio>, {
inputType: StreamType.Arbitrary
});
``` that's from the example code given. do i switch `Arbitrary` to `Opus` if im using `@discordjs/opus`? Actually what does `inputType` even mean in this case?
If you have your AudioPlayer you can create the condition player.state.status == 'playing'.
Did you run connection.subscribe(player) ??
Yes, it works now
queue.player.state.resource.volume.setVolume(0.1)
:1:
yall know what the autopaused status is?
ty 😄 i didnt find that last part about autopaused XD
TypeScript only allows me to do player.state.status
resource doesn't exist according to TypeScript
How can I get a list of all active voice connections?
I used for the adapterCreator in joinVoiceChannel the guild.voiceAdapterCreator now my TS yells at me. What do I need to insert there now?
Hello bretheren. Anyone here familiar with the play-dl package? And how I manage the soundcloud authorization
how do i make my bot join a vc?
I've googled and came up with nothing
Is there any update on prism-media's opus encoder memory leak being fixed?
// @ts-expect-error or // @ts-ingore
@vocal valley I do apologize if you dislike pings, but;
#archive-voice message
Afaik, nothing has been said about this ever since the gh issue emerged on the voice repo regarding inlineVolume. I'm curious if this is something that will not be fixed or if there's any ETA or perhaps just even confirmation that this is known about as it is quite detrimental at scale.
is it possible to save a channel permissions in a data base?
Been trying with the https://github.com/discordjs/voice/blob/main/examples/recorder
my code
if (
interaction.member instanceof GuildMember &&
interaction.member.voice.channel
) {
const channel = interaction.member.voice.channel;
let connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
selfDeaf: false,
selfMute: true,
adapterCreator: channel.guild.voiceAdapterCreator,
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 20e3);
const receiver = connection.receiver;
receiver.speaking.on('start', (userId) => {
console.log('r');
});
} catch (error) {
console.warn(error);
await interaction.followUp('Failed to join voice channel within 20 seconds, please try again later!');
}
await interaction.followUp('Ready!');
}
``` With this I get an error `AbortError: The operation was aborted
` and timeout. Any ideas?
AbortSignals are used in djs when doing anything http related. Either your connection wasn't good enough and took too long to send a request or Discord's servers took too long to respond which sometimes happens considering today was an outage for a good number of large guilds.
Sorry, and thanks for the answer. I was just missing an Intents
hi! I'm using typescript in my bot. it times out on entersState(subscription.voiceConnection, VoiceConnectionStatus.Ready, 20e3);
here's the code
if (!subscription) {
if (interaction.member instanceof GuildMember && interaction.member.voice.channel) {
const channel = interaction.member.voice.channel;
subscription = new MusicSubscription(
joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator as DiscordGatewayAdapterCreator,
}),
);
subscription.voiceConnection.on('error', console.warn);
subscriptions.set(interaction.guildId, subscription);
}
}
// If there is no subscription, tell the user they need to join a channel.
if (!subscription) {
await interaction.followUp('Join a voice channel and then try that again!');
return;
}
// Make sure the connection is ready before processing the user's request
try {
await entersState(subscription.voiceConnection, VoiceConnectionStatus.Ready, 20e3);
} catch (error) {
console.warn(error);
await interaction.followUp('Failed to join voice channel within 20 seconds, please try again later!');
return;
}
adapterCreator has the cast because tsc complained about it being an InternalDiscordGatewayAdapterCreator, I'm not quite sure what I need to do here
Intents.FLAGS.GUILD_VOICE_STATES
did the trick, thanks man
So over time my bot AudioPlayer gets stuck in the autopaused state is there a way to get it out of that status?
(player.state as AudioPlayerPlayingState).resource.volume.setVolume
how do I connect to a voice channel?
this used to be simple, just <VoiceChannel>.join()
this is urgent, please, I need to make a video about my other bot working but I have no friends to help so im using all my other bots but I cant get them to join the channel to demonstrate (the video is for the bot verification process)
How to define guild voice region
what's the proper way to check if the playback has ended?
player.on(AudioPlayerStatus.Idle, () => {})
is it better to do that or listen to stateChange event? cuz thats what im doing and checking if the newstate is idle
if you don't need other states, then use the one i provided
how can i make my bot leave the channel in v13?
ok thanks
im pretty sure u just destroy the connection
how to do that in v13 with the new voice lib?
since in v12 we could just do <channel>.leave()
VoiceConnection.destroy()
alright thanks
ig i would probably use it like this
const channel = <member>.voice.channel
channel.destroy()```
You can store connection when joining the channel
oh.
Why do you need to store connection ??
You can get it very easily.
You don't need to, but you can...
bump
Documentation suggestion for @mental totem:
(event) Client#voiceStateUpdate
Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
Documentation suggestion for @mental totem:
VoiceState#mute
Whether this member is either self-muted or server-muted
So you can't detect an AFK user?
Is there a way to get the player so I can pause the audio using @discordjs/voice?
how to make bot join vc?
const DiscordVoice = require('@discordjs/voice')
DiscordVoice.joinVoiceChannel({
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});```
This should help
Oh you need the library @discordjs/voice
Having a issue. Bot plays first song all good, but when I call a new player.play(RESOURCE) where resource gets made from next song in queue, no sounds comes from the bot. Someone had similar problems? I have tried using player.stop() then in Idle start next song, or just play next song with a skip command (not going into Idle state).
yeah ik that..but i was using a recording modulke and it doesnt work with voice
and to use voice to record idk wher to start
Yah we can, just use voiceStateUpdate and check if user is muted or not. If yes, that user is afk
Can you somehow check whether user that used a command is in a voice channel on the server said command was used on?
Get connection by https://discordjs.github.io/voice/modules.html#getvoiceconnection
And then get player by [ works only if you had done connection.subscribe(player) ]:
const player = connection.state.subscription.player
Use player.stop(true)
player = connection.state.subscription.player
^
TypeError: Cannot read property 'player' of undefined
As told before also, you need to do connection.subscribe(player)
Done
Still nothing..
Can you console.log(connection.state.subscription) ??
Alr one sec
Not having a problem with stopping. Problem is with starting the new song. Runs all the way clean without errors, just no sound.
Can you play first song easily ??
Yes, no problem at all.
You call a new player and plays resource in that player not in the player subscribed to connection. That's main issue
connection: <ref *1> VoiceConnection {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
debug: null,
rejoinAttempts: 0,
receiver: VoiceReceiver {
voiceConnection: [Circular *1],
ssrcMap: [SSRCMap],
speaking: [SpeakingMap],
subscriptions: Map(0) {},
connectionData: {},
onWsPacket: [Function: bound onWsPacket],
onUdpMessage: [Function: bound onUdpMessage]
},
onNetworkingClose: [Function: bound onNetworkingClose],
onNetworkingStateChange: [Function: bound onNetworkingStateChange],
onNetworkingError: [Function: bound onNetworkingError],
onNetworkingDebug: [Function: bound onNetworkingDebug],
_state: {
status: 'signalling',
adapter: [Object],
subscription: [Circular *2]
},
packets: { server: undefined, state: undefined },
joinConfig: {
selfDeaf: true,
selfMute: false,
group: 'default',
channelId: '888827503777566814',
guildId: '888827503777566810',
adapterCreator: [Function (anonymous)]
},
[Symbol(kCapture)]: false
},
player: AudioPlayer {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
subscribers: [ [Circular *2] ],
_state: {
status: 'buffering',
resource: [AudioResource],
onReadableCallback: [Function: onReadableCallback],
onFailureCallback: [Function: onFailureCallback],
onStreamError: [Function: onStreamError]
},
behaviors: { noSubscriber: 'pause', maxMissedFrames: 5 },
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
}
}```
See player is there, so what's issue now ??
Basically
The first time is ok, when I run again the command it says:
TypeError: Cannot read property 'status' of undefined```
I only create a new AudioPlayer if non exists. If I had multiple, Idle would have been called twice as well when stopping no?
if (!serverQueue.player) {
console.log("Lager AudioPlayer");
const player = createAudioPlayer();
//Connection Ready
serverQueue.connection.on(VoiceConnectionStatus.Ready, () => {
console.log(
"Kobling er satt til 'Ready' - klar for å spille musikk!"
);
const subscription = serverQueue.connection.subscribe(
player
);
player.play(resource);
serverQueue.player = player;
});
What is player defined earlier ??
They can be afk without being muted if the server doesn't have an afk channel and they can be muted without being afk
What is the code if player is there ??
else {
await serverQueue.player.play(resource);
}
https://github.com/discordjs/voice/discussions/176
Use this then
What kind of resource you are playing ??
Nvm fixed
What's the issue ??
Using discord-ytdl-core if thats what you thinking about?
const stream = ytdl(song.url, {
filter: "audioonly",
opusEncoded: true,
encoderArgs: encoderArgstoset,
bitrate: 320,
quality: "highestaudio",
liveBuffer: 40000,
highWaterMark: 1 << 32,
inlineVolume: true
});
const resource = createAudioResource(stream);
No I was thinking about something else.
I can't help with discord-ytdl-core.
I accidentally deleted an important part of the code. Ik im so dumb.
Oh okay no issues 👍
Sorry for bothering
Well, dont see why resource should have anything to do with it as first song entered plays fine 😦
thanks
Hi, I have a voice recorder set up to end on silence. When it ends, I process the recording and all that and start listening again. If a certain word is said, I listen for commands. However, there’s a problem.
Imagine this scenario:
A user says the bots wake word, and is then silent.
The bot is listening for commands now.
The users mic activates for a second due to background noise
My bot tries to process that as a command, gets nothing, let’s the user know and the user is confused.
Is there any way to combat this? Set a minimum audio time before listening for the silence timeout?
Can you show me player-idle event code ??
player.on(AudioPlayerStatus.Idle, () => {
if (serverQueue.connection) {
if (serverQueue.songs.length > 0) {
if (serverQueue.loop) {
let lastSong = serverQueue.songs.shift();
serverQueue.songs.push(lastSong);
player.play(getResource(serverQueue.songs[0], serverQueue, serverQueue.filter));
} else if (serverQueue.songloop) {
player.play(getResource(serverQueue.songs[0], serverQueue, serverQueue.filter));
} else {
console.log("LOOOOP") //Where i get to when using player.stop().
serverQueue.songs.shift();
player.play(getResource(serverQueue.songs[0], serverQueue, serverQueue.filter));
}
}
} else {
try {
serverQueue.connection.destroy();
} catch (e) {
console.log(String(e).grey);
}
serverQueue.connection.disconnect();
client.queue.delete(message.guild.id);
return serverQueue.textChannel.send(`**Køen er tom!**`);
}
});
yup as code says you will get LOOOOP if serverQueue.loop and serverQueue.songloop is not undefined.
Yes I want to go there. Problem is still that when player.play(getResource(...)) get executed, no sound comes 😦 (in Idle event).
So it means it is an issue of discord-ytdl-core, so I can't help
But if it was a wrong resource (ie ytdl returns something it shouldnt) would audioplayer say so?
Use this error handler
https://discordjs.guide/voice/audio-player.html#taking-action-within-the-error-handler
player.on("error", (error) => {
console.error(`Error: ${error.message} with resource ${error}`);
serverQueue.songs.shift();
if(!serverQueue.songs[0]){
try {
serverQueue.connection.destroy();
} catch (e) {
console.log(String(e).grey);
}
return client.queue.delete(message.guild.id);
}
player.play(getResource(serverQueue.songs[0], serverQueue, serverQueue.filter));
});
Already do 😦
I have not added any code and it works now. I give up. Not gonna touch anything 
what's the problem here?
is there a way to seek the audioPlayer? 🔵
can someone help me myb?
idk why it happens but it does
It's not play(): it's player.subscribe(<resource>)
||If I remember well||
WTF, that is not even a thing.
https://discordjs.github.io/voice/classes/audioplayer.html#play
What is player here ??
Do npm init -y and you are good to go
@carmine timber
(it's just a private method but it exists)
In your package.json file, add the item "main" and gives it the path to your main file 👍
"slayer_bosses":{"spider":{"claimed_levels":{"level_1":true,"level_2":true,"level_3":true},"boss_kills_tier_0":1,"xp":1130,"boss_kills_tier_1":1,"boss_kills_tier_2":9},"wolf":{"claimed_levels":{"level_1":true,"level_2":true},"boss_kills_tier_0":1,"xp":630,"boss_kills_tier_1":1,"boss_kills_tier_2":1,"boss_kills_tier_3":1},"zombie":{"claimed_levels":{"level_1":true,"level_2":true,"level_3":true,"level_4":true}
what would be the best way to check what level is the last true?
is the only way checking every single level to see if its true?
Quick question: say I want to create a skip song command in a separate file than where I have my current player functionality. Is it possible to access the player from a different file with some kind of function (like getVoiceConnection)?
not playing, help me
TypeError: player.subscribe is not a function
how come this is happening? im tryingto subscribe to a connection
my bot voice connection gets destroyed after playing for like an hour or two is that expected?
i'm pretty much just using the voiceconnection event handler used in
i think its been pretty consistent at the 2 hour mark
How can I put this radio on my bot?
https://usa9.fastcast4u.com/proxy/jamz?mp=/1
I have searched but I don't find why I have AbortError: The operation was aborted
Oh I probably find I will try
I doubt it, but is it possible to call someone in a dm?
no
is there a way to play multiple streams to an audio player?
switching back to v12, this sucks
Ah ok thx djoh
how do u make it so if a song has finished it does something like remove the song out of the queue / list
You can use a listener on the player for the idle state like so: player.on('idle', () => {}). When the player finishes a resource it will become idle.
ok thx
You probably using entersState, It has some issues.
Any solution?
anyone knows this error
throw er; // Unhandled 'error' event
^
AudioPlayerError: aborted```
Getting this error whenever I try to play music... does anyone know a fix?
can somebody help me make a music bot with replit or autocode
This code doesn't work properly but there's any error messages
(btw, this.song(music).file is a .mp3 file in the same folder)
Hey can anyone give me lyrics.Js code for v 13….pls
I think you are returning before the player is finished playing because you don't wait for it. Thus the connection is getting destroyed stops the playing immediately.
How do i wait until everyone leaves the voice channel to delete it? Because it only deletes if the last person leaving is the person who created the voice channel
const { Collection } = require("discord.js");
const voiceCollection = new Collection();
module.exports = async (Discord, client, oldState, newState) => {
const user = await client.users.fetch(newState.id);
const member = newState.guild.member(user);
// JOIN
if (!oldState.channel && newState.channelID === "899361398654640179") {
const channel = await newState.guild.channels.create(user.tag, {
type: "voice",
parent: newState.channel.parent,
});
member.voice.setChannel(channel);
voiceCollection.set(user.id, channel.id);
await channel.overwritePermissions([
{
id: user.id,
allow: ["MANAGE_CHANNELS", "CONNECT"],
},
{
id: member.guild.id,
deny: ["CONNECT"],
},
]);
} else if (!newState.channel) {
if (oldState.channelID === voiceCollection.get(newState.id)) {
if (oldState.channel.members.size < 1) {
return oldState.channel.delete();
}
}
}```
Hello. So my bot can play youtube audios, but after 40 seconds it stops with an error. The error is:
throw er; // Unhandled 'error' event
AudioPlayerError: aborted
Emitted 'error' event on AudioPlayer instance at:
at OggDemuxer.onStreamError ```
What can I do? Thanks.
If you are using ytdl people have been experiencing issues with it in that case I recommend looking into a different packages with that functionality. You could also run a test with a local file to see if there is no other issue.
Yes I'm using ytdl. What do you think I should use?
I have seen play-dl being recommended in here I have no experience with it though
hi, how can I just destroy the audioplayer that it wont emit any event enymore?
Ok! Tomorrow I’ll try it. I’ll go to sleep now. Thank you for the help! Goodbye
TypeError: stream.once is not a function ??
const stream = process.stdio;
const process = raw(
this.url,
{
o: '-',
q: '',
f: 'bestaudio[ext=webm+acodec=opus+asr=48000]/bestaudio',
r: '100K',
},
{ stdio: ['ignore', 'pipe', 'ignore'] },
);
How to kick people from voice channel?
i just tried
const voiceConnection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
and it gives me this error
D:\tecno\Documents\code\node\Oneki-bot\node_modules\discord.js\src\structures\Guild.js:1342
this.client.voice.adapters.set(this.id, methods);
^
TypeError: Cannot read property 'set' of undefined
at D:\tecno\Documents\code\node\Oneki-bot\node_modules\discord.js\src\structures\Guild.js:1342:34
at new VoiceConnection (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\VoiceConnection.js:76:25)
at Object.createVoiceConnection (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\VoiceConnection.js:515:29)
at joinVoiceChannel (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\joinVoiceChannel.js:18:30)
at Join.run (D:\tecno\Documents\code\node\Oneki-bot\js\commands\join.js:20:33)
at D:\tecno\Documents\code\node\Oneki-bot\js\events\command.js:10:25
at processTicksAndRejections (node:internal/process/task_queues:96:5)
any solution?
I used @discordjs/voice v0.6.0 & discord.js v13.2.0
Error:
Error: Cannot play audio as no valid encryption package is installed.
- Install sodium, libsodium-wrappers, or tweetnacl.
- Use the generateDependencyReport() function for more information.
And if use generateDependencyReport()
Return:
--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.6.0
- prism-media: 1.3.2
Opus Libraries
- @discordjs/opus: 0.5.3
- opusscript: not found
Encryption Libraries
- sodium: 3.0.2
- libsodium-wrappers: not found
- tweetnacl: not found
FFmpeg
- version: 4.3.1-full_build-www.gyan.dev
- libopus: yes
--------------------------------------------------
How would a bot set itself as a speaker in a stage channel?
oh nvm
discord.js version ??
Documentation suggestion for @serene meadow:
VoiceState#setChannel()
Moves the member to a different channel, or disconnects them from the one they're in.
13.2.0
Can you do npm ls discord.js and show me the version ??
Let me...
You code is wrong.
const stream = process.stdout
I think you need to re install discord.js.
Documentation suggestion for @sonic bay:
VoiceChannel#members
The members in this voice-based channel
Get size of above for checking no of users in that channel
I tried but it show me same error
discordjs/voice version ??
0.6.0
are you overwriting client.voice
No
show ur code
@ripe orchid ^^
the whole file not just that
can i see ur index
create a new folder and then run these commands :
npm init -y
npm install discord.js
npm install @discordjs/voice
And copy your codes to that folder.

client.voice = new Collection(); youre overwriting client.voice
Remove client.voice code
I work as a team, i had not noticed that change
Jeje tnx for the help, i had been programming for hours
I've got a raspberry pi 4 and i am trying to make a bot that has downloaded songs (non copyright ofc). and its not playing music. did i do something wrong?
that is the part that needs to play music but it doesn't work
Do you have the GUILD_VOICE_STATES intent?
i now get this error
Error: Cannot play audio as no valid encryption package is installed.
You need an encryption package. Checkout debugging dependencies (https://discordjs.guide/voice/#debugging-dependencies) to see what you need.
thx now the bot is playing music :)
hey anybody knows this error i was using genius api for my lyrics cmd
This is for discordjs questions. I'd recommend asking in a genius community.
This was the code playig music in djs v12
what shall i do to make it djs 13?
my code: https://srcb.in/S6G1T18lst
hi, how can I just destroy the audioplayer that it wont emit any event enymore?
are voiceconnections suppose to get destroyed after 2 hours?
mine keeps getting destroy on the 2 hour mark
Why sometimes audioPlayer.on('error') return Error: aborted
And if i try again with same video no return error ???
how can i use the @discordjs/voice package to disconnect the bot from a channel
Do you know how to add filter on the music ?
Is there any way to capture audio from a voice channel? I know there was a way in v12 and hopefully something like that was kept in v13.
Call connection.disconnect() or connection.destroy().
There is, but I don't know how it works.
That's what I thought, but there's nothing in the guide. I don't know where to look in the docs.
i already figured it out thabks anyways
Hey im having this problem that doesnt make any sense, can someone help me out ?
note above is my code for playing audio stream
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: message.member.guild.id,
adapterCreator: message.member.guild.voiceAdapterCreator,
});
const subscription = connection.subscribe(player);
const { createAudioResource, StreamType } = require('@discordjs/voice');
const resource = createAudioResource(`/sounds/happy/${happySoundsRandom}`);
player.play(resource);
}
What am I missing here? my bot wont connect to voice channel.
AudioPlayerError: aborted
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:407:19)
at TLSSocket.emit (node:events:402:35)
at node:net:672:12
at TCP.done (node:_tls_wrap:580:7) {
resource: AudioResource {
playbackDuration: 987720,
started: true,
silenceRemaining: -1,
edges: [ [Object], [Object] ],
playStream: OggDemuxer {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_remainder: null,
_head: null,
_bitstream: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: [Function: bound onwrite]
},
metadata: null,
silencePaddingFrames: 5,
audioPlayer: AudioPlayer {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
subscribers: [Array],
_state: [Object],
behaviors: [Object],
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
}
}
}
Fix??
uhhhh idk how to say this but how can you prevent your bot from playing musisc accross different servers ???
like it plays music for sure but same song in multiple servers in a row ???
how to fix that even
not sure if this is the right answer but see if you can create more players or sometin
like subscribe to that particular voice channel right ?
possibly
No fix, it's a ytdl-core issue. You can swap to another library like play-dl that doesn't have that issue.
this is actually quite irritating.
i have this simple if-statement set up like so:
if (!interaction.member.voice.channel) {
return interaction.followUp({ content: 'You need to be in a voice channel.' });
};
i am in a voice channel and the bot has full permissions so obviously the bot would know, but no matter if i am in a voice channel or not, it still sends this interaction message. i am quite lost.
I’m trying thanks
Do you have the GUILD_VOICE_STATES intent?
yes, i do.
In your joinVoiceChannel(...) the id properties have to be Strings, not integers.
What you put is fine, just make it Strings instead of ints.
Just put quotation marks around it.
Yeah, if I may give some unsolicited advise: Codecademy offers some great courses including on javascript that can get you acquainted with the language and programming before undertaking more complicated projects.
You don't have to use the connection object. Just creating it is enough to make the bot join. Are you sure you are providing the right ids?
I'd recommend changing it to this and trying again:
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
})
This does require you to be in the channel you want it to join.
No, a Guild is a discord server.
Also, make sure you have the GUILD_VOICE_STATES intent.
Looks like you still need to subscribe your connection to the player like so: connection.subscribe(player). This just tells your connection to output whatever your player is playing.
Yeah, at any point when both those variables exist.
No, since you create the player variable only after that so it doesn't know what player is yet. Just put it on like line 62 or something.
data.connection.play(stream, {
volume: 0.9
});
//this is in my code in one location, when ran it plays a stream, but no audio can be heard.
//this is in another location, it plays an audio file. this can be heard with ease.
dpat = connection.play(scat, {
volume: 0.9
});```
You need to actually input some audio resource into the createAudioResource(...) function. Right now you just have a placeholder String. Your code is a bit messy since it has a bunch of v12 stuff in there as well. I'd recommend you remove the entire if statement that is above the joinVoiceChannel() stuff and just replace it with this one line: const stream = ytdl(args[0], {filter: 'audioonly'});. Then you change the audio resource line to const resource = createAudioResource(stream).
what do you mean? I dont want to play the audio file. i want to play the stream
oh you thought i was helping you. That was an issue I was having.
That's v12, this channel is for v13. -> #archive-djs-v12-voice-deprecated
so its because its deprecated, thats why. im on 13 and in the process of updating some code i wrote years ago
then, mid-update discord went from 12-13
If you run that code in v13 you should get ... is not a function errors.
I did for a while, but not now
Could you elaborate on what you mean?
Surely data.connection is a VoiceConnection object, is it not?
im not sure, i could check but at this point im just going to rewrite everything from scratch in v13 and hope its stable for a month at least
You can put a path to an audio file that is on your computer in there or you can provide it with a stream like I did in my example.
That's probably a good idea xD.
Yeah, so just follow what I said here:
I'd recommend you remove the entire if statement that is above the joinVoiceChannel() stuff and just replace it with this one line: const stream = ytdl(args[0], {filter: 'audioonly'});. Then you change the audio resource line to const resource = createAudioResource(stream).
No, remove this part:
if(validURL(args[0])){
const connection = voiceChannel.join();
const stream = ytdl(args[0], {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
channel.leave();
message.channel.send('leaving channel');
});
await message.reply(`:thumbsup: Now Playing ***Your Link!***`)
return
}
And just leave this in it's place:
const stream = ytdl(args[0], {filter: 'audioonly'})
And then you change this:
const resource = createAudioResource('link or path to file')
to this:
const resource = createAudioResource(stream)
By the way, can you link the tutorial/guide that you used? I've seen this before and people had the same issues as you.
Can you show the full error? And what is args[0] I assumed that's just a url that you input?
Yeah, so the way it's set up now is it can only handle URL's. So you would have to say "!play <your url here>" instead. You can use something like youtube-search I think to search a youtube video based on search terms, but I'd recommend getting this to work with URLs first before moving on.
Yeah, the bot is just deafened by default to save resources, it doesn't need to hear anything to play.
Can you try changing this:
if(video){
const player = createAudioPlayer();
const resource = createAudioResource(stream)
player.on('idle', () => {
});
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
} else {
message.channel.send('No video results found');
}
To this:
const player = createAudioPlayer();
const resource = createAudioResource(stream)
player.on('idle', () => {
});
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
Oh, I'm dumb, didn't even see this. You never call the .play() method to start playing the resource haha. Just add this: player.play(resource)
directly after the const resource = createAudioResource(stream) line.
Oh did you remove the .subscribe() line at any point? I can't see it in there. I may have forgotten to add it into one of my code blocks. Just put that back in like you did before.
Big! To error handle that I'd probably just take it the simple route and change this:
const validURL = (str) =>{
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex.test(str)){
return false;
} else {
return true;
}
}
const stream = ytdl(args[0], {filter: 'audioonly'});
To this:
if(!args[0].startsWith("https://www.youtube.com/watch?v=")) {
return message.reply({content: "Not a valid youtube url", ephemeral: true})
}
const stream = ytdl(args[0], {filter: 'audioonly'})
if(!stream){
return message.reply({content: "Couldn't finde youtube video", ephemeral: true})
}
That just checks if the URL is a youtube video before trying to find it, and after searching for it with ytdl it just makes sure it has got it.
Great, glad it works. Imma head off to bed now haha. Good luck with the rest of your dev!
does djs/voice let you play any music file? can it play spotify urls?
youtube is not letting you use it will they let you if you keep your bot non-premium?
Is there any way to adjust the volume of the bot (before playing the resource) without using inlineVolume
not that ive found
Is there an event that fires when a stream ends?
<AudioPlayer>.on(AudioPlayerStatus.Idle, () => {
// Resource has ended.
})
thank you
is there a way to query the current state of the player?
(isPlaying or smth)
if(<AudioPlayer>.state.status === AudioPlayerStatus.Playing) {
// Audio Player is playing
}
Thank you again, where are you getting these? I cant find docs
amazing
thank you
I think it's voiceChannel.destroy()
At least in v13 it is
No it is Connection.destroy()
There is no property like VoiceChannel.destroy()
can someone help?
humm how fix this erro ? I can't play music ples help me
(node:1480) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1480) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time
that just a warning, please read clearly
what is channel defined as ??
in channelID
i already got it fixed... kinda
it wont play any audio tho :/
Ok tell me when you execute player.play, does this player is same as that of subscribed one ??
yeah
Show me full code
var happySoundsRandom = happySounds[Math.floor(Math.random()*happySounds.length)];
const player = discordVoice.createAudioPlayer();
const resource = discordVoice.createAudioResource(`/sounds/happy/${happySoundsRandom}`);
const connection = discordVoice.joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
player.play(resource);
connection.subscribe(player);
Your resource creation is wrong. Change that to absolute path
absolute?
eyyyy it works, thanks
Weird question but is it possible to "undeafen" the bot?
other than by possibly creating a recording thing of somesort
set selfDeaf to false when using joinVoiceChannel command
worked like a champ, thanks
.then(conn => {
const dispatcher = conn.play(__dirname + 'beep.mp3');
dispatcher.on('finish', () => { console.log(`Joined ${channel.name}!\n\nREADY TO RECORD\n`); });
const receiver = conn.receiver;
conn.on('speaking', (user, speaking) => {
if (speaking) {
const pathToFile =`${Date.now()}.pcm`;
const pathToFile2 =`${Date.now()}.mp3`;
console.log(`${user.username} started speaking`);
const audioStream = receiver.createStream(user, { mode: 'pcm' });
audioStream.pipe(createNewChunk(pathToFile));
audioStream.on('end', () => {
const cmd = 'ffmpeg -i ' + pathToFile + ' ' + pathToFile2;
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
console.log(`${channel.username} stopped speaking`); });
}
});
})``` i'm trying to record audio and then change the file to mp3, but im getting always correupt input packet in ffmpeg also the .pcm file isnt playing anything
is there a way to stream something via my bot?
also if i try to use the example code i get this error ```const opusStream = receiver.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
const oggStream = new opus.OggLogicalBitstream({
opusHead: new opus.OpusHead({
channelCount: 2,
sampleRate: 48000,
}),
pageSizeControl: {
maxPackets: 10,
},
});
const filename = `./recordings/${Date.now()}.ogg`;
const out = createWriteStream(filename);
console.log(`👂 Started recording ${filename}`);
pipeline(opusStream, oggStream, out, (err) => {
if (err) {
console.warn(`❌ Error recording file ${filename} - ${err.message}`);
} else {
console.log(`✅ Recorded ${filename}`);
}
});```
Unhandled promise rejection: Error: Cannot find module 'node-crc'
If you aren't getting any errors, try to place console.log checkpoints throughout your code to find out where execution stops.
• Once you do, log relevant values and if-conditions
• More sophisticated debugging methods are breakpoints and runtime inspections: learn more
after installing node-crc i get this error
Hello! When i write this:
let conn = await voice.joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false
})
await conn.play(....)
the bot join the voice channel, with no errors, but the it gives at conn.play() "play is not a function"
you need to make a player.
I'm having issues setting the volume of a resource.
I have inlineVolume set to true
DiscordjsVoice.createAudioResource(url, {
inputType: DiscordjsVoice.StreamType.Arbitrary,
inlineVolume: true,
metadata: { url }
});
Then in a different file - I access the resource by reading the resource property of the state of the audioplayer
console.log(volume, player.state.resource.volume);
player.state.resource.volume = volume;
console.log(volume, player.state.resource.volume);
volume = target volume
before, it logs 10 100 then 10 10 but I hear no difference.
Accessing the volume again shows it's set to 10, but no difference in the audio level can be heard.
So i have the audio player etc working perfectly
but id like to access player from another file basically, i get an error if i map it to a global variable. Can you give me some advice?
^
TypeError: leaveVoiceChannel is not a function```
is it something different than leave? my join one works
connection.destroy()
it wont let me then as its before ive initialized connection
Then how are you in a voice channel?
i got the play command working but i cant get the command to leave the voicechannel working
idk what it is youre doing
you need to join the voice channel (or else, you wont be in the voice channel) then destroy that connection.
Youre passing an invalid url to ytdl()
You should check for it before calling that
Hello! How can i leave a voice channel? I'm searching a lot but i cannot find anything. I tried with connection.destroy() but it doesn't work (for because i've commands in different files). How can i do? The bot after finishing playing sound does not leave alone the channel
Exactly
anyone know whats going on here? Every once in awhile it aborts.
try {
await entersState(subscription.voiceConnection, VoiceConnectionStatus.Ready, 20e3);
}
catch (error) {
console.warn(error);
await interaction.followUp('Failed to join voice channel within 20 seconds, please try again later!');
return;
}
AbortError: The operation was aborted
code: 'ABORT_ERR'
It happens with entersState function
everything in voice changed in 13.0, is there any guide about how to use that?
why discord/voice cant play full song it play only 15-30 secons song
It can. I’m able to play 3-5 min songs
yes bro i am playing spotify songs
it playing but not full
Then it’s most likely an issue with ur code or internet
yeah i checked the source code for entersState and see that but I wonder why. could it be something do with ubuntu 20 and aws ec2?
other links work but not sotify
Or ur only getting 15s of a song
any fix ?
Code will tell us more about your condition
No it occurs when some code run abort signal in node 16
oooh, that's unfortunate. so just something with have to deal with?
i catch it spotify give me preview url not full song
That would make sense
Yep but it is difficult to catch that signal
I can’t reliably get that error without letting my laptop go to sleep
but any way to get full song bcz link not support discord/voice
I’m not familiar with how Spotify links work
Spotify links are hard to play due to their DRM layer.
does discord/voice support links ?
discord/voice itself wont
i know it so hard
That’s what she said
you have to use a module
using any npm module ?
You can search that Spotify title on YouTube and play YouTube stream instead
but i want to make only spotify player i don't want to use youtube api
just use some sort of youtube module. forget about trying to stream from spotify
All the best 👍
thanks
i know how to make bot like hydra but i need only thing which play spotify tracks
no one can stream from spotify, they just resolve to other source
when i try to use the example code i get this error (the bot runs on Windows WSL - Ubuntu)
const opusStream = receiver.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
const oggStream = new opus.OggLogicalBitstream({
opusHead: new opus.OpusHead({
channelCount: 2,
sampleRate: 48000,
}),
pageSizeControl: {
maxPackets: 10,
},
});
const filename = `./recordings/${Date.now()}.ogg`;
const out = createWriteStream(filename);
console.log(`👂 Started recording ${filename}`);
pipeline(opusStream, oggStream, out, (err) => {
if (err) {
console.warn(`❌ Error recording file ${filename} - ${err.message}`);
} else {
console.log(`✅ Recorded ${filename}`);
}
});```
also if i try this ```ts
const connection = await channel.join()
const receiver = connection.receiver
const userStream = receiver.createStream(author, {mode:'pcm', end: 'silence'})
const writeStream = fs.createWriteStream('recording.pcm', {})
const buffer = []
userStream.on('data', (chunk) => {
buffer.push(chunk)
console.log(chunk)
userStream.pipe(writeStream)
});
writeStream.on('pipe', console.log)
userStream.on('finish', () => {
channel.leave()
const cmd = 'ffmpeg -i recording.pcm recording.wav';
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
});```
the output .pcm file cant be played and after using ffmpeg the wav file is 10x size and it only has white noise
Voice recording doesn't work on windows even if u use WSL... Consider using linux for that
oh i see, thank you
whoops wrong guild
Im in a voice channel and if i try interaction.member.voice.channelId it returns null, but if i restart the bot it returns the voice channel id, and if i leave it still returning the voice channel id, why???!!
nvm, missing intents
Setting player.state.resource.volume doesn't seem to change the volume.
I have inlineVolume set to true in createAudioResource
DiscordjsVoice.createAudioResource(url, {
inputType: DiscordjsVoice.StreamType.Arbitrary,
inlineVolume: true,
metadata: { url }
});
// ... (in another file) ...
player.state.resource.volume = volume;
I've set the volume to 100 and 10 and hear no differences.
I believe the audio level might be mapped between 0 and 1
I'm looking at the docs and it says that it's readonly.
I also don't see another method to set the volume.
I'll give mapping it between 0 and 1 a try.
the volume property is indeed readonly but it returns a volumetransform on which you can do setVolume(volume)
Oh! Didn't see the volumetransform. ty
idk how i managed to miss that
err stream destroyed isnt a valid case, anyone help?
I wanted to record 2-5 users in a voice chat, this lead me into two questions:
- One: Should I create a pipe when they start talking and destory it when they stop? Or should I start and keep the pipes active all the time?
- Two: What should I try to do to pass the data into an audio file? I can get the audio from
reciver.subscribeorreciver.speaking.on('data' () => {})so what would be best?
Hey so I'm using discord.js/voice and I created an audio resource to play a file and then I set an interval to print debugging information and the bot is able to join a channel, and the audio resource's status is playing but there's no green circle and it's not actually playing any audio. I tried multiple different audio formats. I have ffmpeg installed globally. Is there any way to get more information for debugging purposes? Any tips?
Ah, I needed to add Intents.FLAGS.GUILD_VOICE_STATES
Fixed!
Error: Cannot play a resource that has already ended.
How can I replay an audio that has been played?
You have to create a new resource
Are there any viable sources for popular music other than ytdl/youtube? Anyone had luck elsewhere?
I heard of play-dl, never actually used it tho
ok tnx
Ty:)
Would using createAudioResource#inlineVolume pretty much nullify the improvement in performance gained by specificying input type? (createAudioResource#inputType: StreamType.WebmOpus) - since the resource ends up piping through FFmpeg anyway?
Yes it does.
Cheers :)
Hey Guys
pause and resume commands aren't working for me is there anyway to fix it?
Is there an error? Relevant code?
no errors
Then it’s prob not running
it only works when i use pause again and then use resume
pause is working but resume doesn't work until i use pause again
Prob got some spaghetti code then
https://github.com/discordjs/discord.js/issues/5300 something related to this maybe
Bruh, that issue is for v12
i am using v12
The fix was stated in that issue tho
I doubt the native v12 voice is gonna get updated tho
If i update to v13 then i need to make some changes
Is v13 good ?
It’s depends on what you define as "good"
Most ppl who hate it are those who either don’t like to update code (even tho that’s what software development is), or prefer to stick to using bad practices bc it’s easier
What is the new version of discord.js now?
Latest rn is 13.2.0
Ok i will update my code then
Hello! Is there a way to handle the audioplayer finish event? For example when it ends the song/audio in order to run the next audio (for example stored in a map)?
The player will emit idle
but it emits idle also if the audio is stopped manually. Or Also if it's created and nothing is runned on it. It emits idle the same
The last one is false
It does not emit when created
It only emits it becomes idle (from a different state)
in the previous version (when there is not the voice package) ther is the .play(audio).on('finish',....). I'm searching something like that.
Well, ur not gonna find anything
ok. so i need to work with the idle event tho?
Yes
So if i detach a connection, it should not emit idle anymore right?
That’s not the case
The idle listener will still be attached to the player regardless of the connection
No, that’s that a different event
unsubscribe is a different event. But connections don’t affect player events
ok....but so how can i recognize if the audio is finished or stopped? I've to register also my commands?
(my intent is to make an audio map as queue, if i send a stop command, it stops playing, if i skip/or audio finish, it continues with the audios queue).
Wouldn’t that be the same thing?
If it finishes, it shifts the queue and continues. If you stop it. It does the same thing
If you want it kill it, clear the queue before stopping. If you don’t want to clear the queue, pause it
oh you right, it changes only that in 1 case it run the next audio, in the other it only shifts
Is there an other way to check the emit event? I've to check it into an asynchronous function and when it emits the idle i've to recursive call that function. But it works only 1 times. If it emits more then 1 time it doesn't work
Is anybody familiar with speech recognition stuff? I m trying to add feature to my bot which can join vcs and talk to people. Like siri and google assistant. Right now, I have figured out ai chat using swagger ui and it can speak out the output(response) in a vc but you have to type in a channel for a response. (I m using tts for that. The message is sent to a private channel and the tts will read the response)
In short, what I m trying say is: Is anybody familiar with speech recognition? Like, converting speech to text or something like that!
Anyone got the route from posting self deafening a bot?
Are there any current problems with playing sound in a voice channel? My bot joins the voice channel, lights green, but has no sound. Yesterday everything worked fine.
I have created a simple test bot and it is the same. He joins the voice channel, lights green, but has no sound.
const { Client, Intents } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
const { token, channelId, guildId } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_VOICE_STATES] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
const connection = joinVoiceChannel({
channelId: channelId,
guildId: guildId,
adapterCreator: interaction.member.guild.voiceAdapterCreator,
});
const audioPlayer = createAudioPlayer();
const resource = createAudioResource('sound.mp3');
audioPlayer.play(resource);
connection.subscribe(audioPlayer);
await interaction.reply('Pong!');
}
});
client.login(token);
try using const connection = getVoiceConnection()
ofc import is aswell
Unfortunately this has not solved the problem. The connection variable is still the VoiceConnection and it also shows in Discord that the bot is talking, but you can't hear anything.
You are passing in a string to createAudioResource(). What you need to pass in is a readable stream
In your case that would be something like createAudioResource(fs.createReadStream('sound.mp3'))
After ofc importing fs (no download required, it is integrated into node)
Does not work either. Same result. It shows in Discord that the bot is talking, but you can't hear anything.
My current test code:
const { Client, Intents } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, getVoiceConnection } = require('@discordjs/voice');
const { token, channelId, guildId } = require('./config.json');
const fs = require('fs')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_VOICE_STATES] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
joinVoiceChannel({
channelId: channelId,
guildId: guildId,
adapterCreator: interaction.member.guild.voiceAdapterCreator,
});
const connection = getVoiceConnection(guildId);
const audioPlayer = createAudioPlayer();
const resource = createAudioResource(fs.createReadStream('sound.mp3'));
audioPlayer.play(resource);
connection.subscribe(audioPlayer);
await interaction.reply('Pong!');
}
});
client.login(token);
Sorry guys. Everything works again. The standard input output devices did not work anymore. I just had to change the settings from default to some other device. There was nothing wrong with the code from the very beginning. Only the discord settings were the problem.
Hey! Is there a way to make a bot join a stage voice channel in discord.js? I’ve looked through the docs and havent found anything yet 😅
I don't think it supports stage channels right now, maybe later they may provide an update or something. Even I have been trying for the same
you would join it the same way you would a regular voice channel
its the same way as you would for a regular voice channel
hey, so i'm trying to make my bot join a vc and play a locally saved mp3 file, and i've looked through the docs n stuff, and turned for this to be my script:
vc.join().then(async (connection) => {
console.log("connection"); console.log(connection)
const { VoiceConnectionStatus, createAudioResource, createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice');
const player = await createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
})
console.log("player created")
const resource = await createAudioResource('./musicfiles/Bastille_Pompeii.mp3', {
metadata: {
title: 'A good song!',
},
})
console.log("recourse created")
player.play(resource)
connection.subscribe(player)
console.log(VoiceConnectionStatus)
player.on('error', error => {
// console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`)
// player.play(getNextResource())
})
})
But it complains that connection.subscribe isn't a function, is this an error on my side? and if so, how should i do it otherwise?
vc.join() is no longer used.
https://discordjs.guide/voice/voice-connections.html#creation
that part works though? It still joins the vc
discord.js version ??
v13
i'll assume that the connection param is just invalid from that method then
There is no method in v13.
@crimson crane
https://discord.js.org/#/docs/main/stable/class/VoiceChannel
See there is no function as join
yeah i'll assume that it just joins and gives wrong arg
it then returns this
vsc complaining about an error inside the discordjs/voice module
when i did the following:
const connection = joinVoiceChannel({
channelId: vc.id,
guildId: vc.guild.id,
adapterCreator: vc.guild.voiceAdapterCreator,
})
What is the complaint ??
Show me full joining code
ok
const { voice } = msg.member
if (voice.channelID) {
const vc = voice.channel
// console.log(channel)
const { joinVoiceChannel, VoiceConnectionStatus, createAudioResource, createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice');
const connection = joinVoiceChannel({
channelId: vc.id,
guildId: vc.guild.id,
adapterCreator: vc.guild.voiceAdapterCreator
})
Log the <Guild>.voiceAdapterCreator
ok
Sidenote, its <VoiceState>.channelId (small d)
Voicestate?
Yes
VoiceState = voice in your code
ah, it's undefined
Make sure ur running npm ls discord.js in ur project directory
yeah the complete bot works, just not the vc part
Do npm ls discord.js in the project directory
Do
npm init -y
npm i discord.js
Why init?
That's the User directory
oh wait the project directory
macci@ /Users/macci
You shouldn't have anything installed there in the first place
/Documents/Programming yeah
/Js/CBot
ok yeah apparently i've v13 globally but v12 in this directory
Use npm i discord.js@latest to install v13
You should always have ur terminal running in the project directory ur working in
Err, it says i'm missing intents "TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client."
const { Client, Intents, Permissions } = require('discord.js')
const client = new Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"], partials: ["CHANNEL"] })
Show the full error
/Users/macci/Documents/Programming/JS/CBbot/node_modules/discord.js/src/client/Client.js:544
throw new TypeError('CLIENT_MISSING_INTENTS');
^
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions (/Users/macci/Documents/Programming/JS/CBbot/node_modules/discord.js/src/client/Client.js:544:13)
at new Client (/Users/macci/Documents/Programming/JS/CBbot/node_modules/discord.js/src/client/Client.js:73:10)
at Object.<anonymous> (/Users/macci/Documents/Programming/JS/CBbot/server.js:6:16)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47 {
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
}
Also add the GUILD_VOICE_STATES intent
done, still does the same though
Is that the line 6 of server.js?
no line 6 is commented out..
Make sure the sever.js file is saved
the 'const client' is line 16
it is saved, yes
I don't think that part changes if it's unsaved?
if its unsaved it shows a white dot
Show server.js not helixserver.js
oh
forgot to change that after swap to v13
damn it works, thanks a lot!
for anyone wondering, i figured it out:
const {
NoSubscriberBehavior,
StreamType,
createAudioPlayer,
createAudioResource,
entersState,
AudioPlayerStatus,
VoiceConnectionStatus,
joinVoiceChannel,
} = require('@discordjs/voice');
let channel = await client.channels.cache.get('900857610717237258');
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
try {
connection.subscribe(player);
return connection;
} catch (error) {
connection.destroy();
throw error;
}
hey i'm tring to make music bot i didn't send any Errors but i don't play anything
this is my code
if (command == "노래") {
await interaction.reply("잠시 기다려주세요...");
if (!interaction.member.voice.channel) {
return interaction.editReply('먼저 음성 채널에 참여해주세요!');
}
var video = await youtube.searchVideo(option.getString('곡명'));
interaction.editReply('```' + video.videos[0].title + '을 재생하겠습니다```');
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
});
const stream = ytdl('http://youtu.be/'+video.videos[0].id, { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary, inlineVolume: true });
resource.volume.setVolume(1);
const player = createAudioPlayer();
player.play(resource);
connection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => connection.destroy());
}
Do you have the GUILD_VOICE_STATES intent?
