#archive-voice
30636 messages · Page 22 of 31
The error will occur if I try to use the joinVoiceChannel method that I importec from the d.js voice module; The resource is available, I've confirmed that too
I tried it on my Windows 10 machine, and my CentOS 8 Stream VM, both on Node 16.6.1; Same error on both
I'm 95% sure this is an issue with the library itself
I'm not sure about the specific error that you're getting, but it seems like it's getting some bad inputs from misc errors in your code of which I can see a few.
First of all, you don't create an AudioPlayer like so new AudioPlayer(), use the method createAudioPlayer() from the @discordjs/voice package.
Additionally, your joinVoiceChannel() method parameter must include an adapterCreator property like so:
const connection = joinVoiceChannel({
channelId: channelId,
guildId: guildId,
adapterCreator: <Guild>.voiceAdapterCreator,
selfDeaf: true,
})
The next problem your code probably doesn't even reach yet, but you'll run into it. You cannot parse a link as a resource to play into the <AudioPlayer>.play() method. You must first create an AudioResource using the createAudioResource() method once again from the @discordjs/voice package. This method doesn't take a URL either so you will have to find a way to turn the resource into a readable stream first using potentially another package, but I can't help you much on that front since I've only used packages that do it for youtube.
@winged plover
It could be the adapterCreator I am missing, I did not realise that was required 🤦♂️
As for the audioplayer, I don't see why I couldn't just create the player (see here https://discord.js.org/#/docs/voice/stable/class/AudioPlayer)
I was taking a look at the AudioResource docs and it mentioned streams, It's been ages since I had used D.js and before it accepted a URL that was outputting an audio stream, so I figured it would do the same now - thanks! I'll try a few things here with that info
It could be that you can just create one yourself. I'm not quite sure what createAudioPlayer() does in the background other than just making an AudioPlayer, but I've never seen anyone do it another way so I just kinda stick with what I know haha. Feel free to experiment with that though, I have been wrong before (many many times ;) ).
You're all good! I appreciate the help
No problem, good luck!
Ended up figuring it out - for anyone who searches for this, you'll need the adapterCreator- easy as pie - without it, there's that bizzare error; It isn't very well documented, so personally I just passed in the voiceAdapterCreator function from the message.member.voice object
Thanks again!
Guys I want to do that if the member's voice channel id is not the bot's voice channel id it just returns,
I already tried to do it, but the problem is that when the bot is not in a voice channel it obviously fails and crashes because it can't read the voice channel id, how can I make that if the bot is not in a voice channel it just executes the play command but if the bot is in a voice channel it checks if the bot's voice channel id is the user's voice channel id?
check <Guild>.me.voice in the docs, it returns <VoiceState>
Add this condition
if (message.guild.me.voice?.channel) return;
Same goes for interaction
is there any way to see who is watching the stream? have been trying to see if i can find any function to check for it
it worked :D
👍
why? I don't want to stop the code if the bot is in the voice channel
I just don't want that people can control the bot's player in another voice channel (obviously different from the bot's voice channel)
Guys, how do I mute all the members in the same voice channel as the message author? Tried doing this:
let channel = message.guild.channels.cache.get(message.member.voice.channel.id);
for (const [memberID, member] of channel.members) {
member.voice.setMute(true);
}
But i'm getting an error:
let channel = message.guild.channels.cache.get(message.member.voice.channel.id);
^
TypeError: Cannot read properties of null (reading 'id')
You need to make sure that your audio resource is a playable audio resource. For example you wouldn't be able to play a YouTube video with the default url, in this case you would need the url of the resource of the audio
Do you have the voice intent enabled?
Also there is no need to get the channel from cache when you can just do const channel = message.member.voice.channel
const Discord = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice');
module.exports = {
name : 'play',
args: true,
/**
*
* @param {Discord.Message} message
* @param {Array<string>} args
*/
async execute(message, args) {
const channel = message.member.voice.channel;
if (!channel) return message.reply(`Vous devez tout d'abord de rejoindre un salon vocal !`)
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const ressource = createAudioResource(args[0]);
player.play(ressource);
connection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => connection.destroy());
player.on('error', error => {
console.error(error);
});
},
};
my bot joins the vc and immediatly leave it ._.
args[0] is not a valid audioresource
yt videos links don't work?
thanks
how can I make an audio player play a youtube video url?
See the link pluto just sent.
thanks for helping
I'm pretty new here with this version of djs, so can you guys guide me how to integrate my lavacord to the bot? it says that it's playing music in the variables but it's not actually playing it on discord
How can I find the total duration on an Audio Resource in discord.js/voice?
anyone?
Does somebody know how to make a playlist? I have more audio files and I want to play them when I type the play command
capital letter.
no
hi, i need i little help
my bot plays youtube videos on chat but there is one specific video that always crashes at 1:52 with aborted error
does anyone knows how to solve this?
how can I lower the volume of my audio player
whenever my bot is playing audio it sometimes just randomly disconnects
nvm, it doesn't disconnect, sometimes it just stops playing due to some "unhandled error"
I made music bot, but I have some errors.
First, I have reject Promise Error.
reject Promise {
[
{
status: 'connecting',
adapter: [Object],
networking: [Networking]
},
{ status: 'ready', adapter: [Object], networking: [Networking] }
]
} AbortError: The operation was aborted
at abortListener (node:events:838:14)
at EventTarget.<anonymous> (node:events:874:47)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
at EventTarget.dispatchEvent (node:internal/event_target:504:26)
at abortSignal (node:internal/abort_controller:97:10)
at AbortController.abort (node:internal/abort_controller:122:5)
at Object.entersState (C:\Users\middl\Desktop\Litium\node_modules\@discordjs\voice\dist\util\entersState.js:20:56)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}
And Next, Reject Promise Again.
reject Promise { { ip: '121.###.##.###', port: 63202 } } Error: Cannot perform IP discovery - socket closed
at Socket.<anonymous> (C:\Users\middl\Desktop\Litium\node_modules\@discordjs\voice\dist\networking\VoiceUDPSocket.js:120:52)
at Object.onceWrapper (node:events:509:28)
at Socket.emit (node:events:402:35)
at socketCloseNT (node:dgram:755:8)
at processTicksAndRejections (node:internal/process/task_queues:82:21)
How can I fix it?
I can give source code if needed
my bot joins the voice channel, but it doesn't plays nothing and no error is logged in the console. what's happening?
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channelId,
guildId: interaction.guildId,
adapterCreator: interaction.guild.voiceAdapterCreator
});
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause
}
});
const resource = createAudioResource('./audio.mp3');
player.play(resource);
connection.subscribe(player);
interaction.reply('playing :thumbsup:');```
new here but how do you make the bot join vc?
what's the createAudioPlayer() fn code here?
hm
help please? ^_^
ahh i see it's a library in discordJs/Voice
const { createAudioPlayer } = require('@discordjs/voice');```
const { joinVoiceChannel, createAudioPlayer, createAudioResource, NoSubscriberBehavior } = require('@discordjs/voice');
thanks
ok, but what's the problem in there?
i've been following some old tutorials to make a simple yt-search and player bot
but the tutorial (this one https://www.youtube.com/watch?v=3wJJDM7jUsk) used the old method of connecting to vc's.
gimme a second
well first help would be to just have the bot join the vc
it can detect voice_state_updates in logs and even the channels the user is in.
the old method still works?
i thought it was removed in v13
no idea, i was getting type errors all over the place.
i have a bot. but how do i make it join vc in the latest version?
discordjs.guide results:
• Getting Started: Introduction
Voice got a complete rewrite
yeah indeed
There’s more sections in the guide that covers the rest of voice
channelId: <VoiceChannel>.id,
guildId: <Guild>.id,
adapterCreator: <Guild>.voiceAdapterCreator
});```
look i have the ytd-search working fine. like i can ask the bot to search a song on yt and it'll return with a url
just need to have him join vc and stream it
The voice guide covers that
and i still didn't learn it lol
It’s not a simple find and replace fix
what to do after this?
can i put my code here?
What for?
const connection = joinVoiceChannel({
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const player = createAudioPlayer({
noSubscriber: NoSubscriberBehavior.Pause,
});
connection.subscribe(player);
but he still doesn't join the vc
Did you enable the guide voice states intent in the client?
// Create a new client instance
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
Intents.FLAGS.DIRECT_MESSAGE_TYPING,
],
});
do you mean this?
okay i'll try with that. what's the intent for vc?
GUILD_VOICE_STATES
I made music bot, but I have some errors.
First, I have reject Promise Error.
reject Promise {
[
{
status: 'connecting',
adapter: [Object],
networking: [Networking]
},
{ status: 'ready', adapter: [Object], networking: [Networking] }
]
} AbortError: The operation was aborted
at abortListener (node:events:838:14)
at EventTarget.<anonymous> (node:events:874:47)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
at EventTarget.dispatchEvent (node:internal/event_target:504:26)
at abortSignal (node:internal/abort_controller:97:10)
at AbortController.abort (node:internal/abort_controller:122:5)
at Object.entersState (C:\Users\middl\Desktop\Litium\node_modules\@discordjs\voice\dist\util\entersState.js:20:56)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}
And Next, Reject Promise Again.
reject Promise { { ip: '121.###.##.###', port: 63202 } } Error: Cannot perform IP discovery - socket closed
at Socket.<anonymous> (C:\Users\middl\Desktop\Litium\node_modules\@discordjs\voice\dist\networking\VoiceUDPSocket.js:120:52)
at Object.onceWrapper (node:events:509:28)
at Socket.emit (node:events:402:35)
at socketCloseNT (node:dgram:755:8)
at processTicksAndRejections (node:internal/process/task_queues:82:21)
How can I fix it?
uhh my bot still isn't joining vc, i'm passing these values joinVoiceChannel();
channelID: [#903034211757940757](/guild/222078108977594368/channel/903034211757940757/) // changed a bit here and there
guildID 909094138240172043
adapterCreator methods => {
this.client.voice.adapters.set(this.id, methods);
return {
sendPayload: data => {
if (this.shard.status !== Status.READY) return false;
this.shard.send(data);
return true;
},
destroy: () => {
this.client.voice.adapters.delete(this.id);
},
};
}
okay yes now it's joining.
the error --> pass 903034211..57 instead of <#903034211..57>
315 // 3.15 I want to get output like this how do I do it
the sound from the url does not play, how to fix it?
Are you sure your play() function is being reached? And do you have the GUILD_VOICE_STATES intent?
uh, i'm understood my error
thanks
Can you elaborate what "function being reached" Means?
I mean the line that calls play() in their code is within a listener and an if-statement. It is possible that the program never reaches the line because, for example, the condition for the if-statement may be false in their testing environment or whatever.
Ahh I see thanks!
Has anyone here tried converting YouTube urls to stream data and playing that as a resource file before?
const voice = require('@discordjs/voice');
//...
const member_channel = message.member.voice.channel;
//...
if (!member_channel) {
return message.channel.send('**You have to be in a voice channel to use this command**');
};
//...
const connection = voice.joinVoiceChannel({
channelId: member_channel.id,
guildId: member_channel.guild.id,
adapterCreator: member_channel.guild.voiceAdapterCreator,
});
//...
connection.once(voice.VoiceConnectionStatus.Ready, () => {
message.channel.send(`**Joined** \`${member_channel.name}\``);
queue(connection);
return;
});
Yesterday, joining worked perfectly. Today for some reason, the connection status of the bot is stuck on SIGNALLING indefinitely
note: I'm using GUILD_VOICE_STATES, so that shouldn't be the problem
(I've been printing the connection each second in the image below)
Yeah, there's plenty of packages you can use for that. I recommend play-dl.
Have you tried printing member_channel and checking its contents?
ah yes,
"never waste time doing what people smarter than you have already done"
thanks!
np
Alright, so I'm getting slightly annoyed with the lack of documentation for the voice lib- but I'll ask anyway; Is there a way to not use FFmpeg to play audio? I'd like to just pass in a readable stream and be done with it
But for some ungodly reason, no matter if I set the type in the options, it runs ffmpeg and reprocesses the data
And yes, it is already in an Opus encoded format
yes, it's a GUILD_VOICE type, and it has the correct channel ID
(also I forgot to include the code where I check if member_channel even is a thing in my previous post, so I apologize for that)
line for making the bot leave a vc?
connection.unsubscribe(player); // something like this?
connection.disconnect(); for disconnecting entirely from the voice channel
connection.unsubscribe(player); is for unsubscribing from an audio player (stop playing the music from that audio player on this connection)
ahh i see
I'm guessing you don't have inline volume enabled, right?
I wasn't planning on using it no
Is there even a way to disable it?
The docs are setup in like, the most confusing way, it's legitimately infuriating
It's disabled by default.
Amazing, good
Can you send your code?
Sure thing
Lemme give you the snippet that actually outputs the audio, 1 sec
Sure
should also mention this.streamable is a Node PassThrough stream (readable & writable)
Hmm, I can't quite see what's going wrong, but this area isn't really my forte either. It could be that your streamable type is messing with it, but I'm just stabbing in the dark at that. Someone else is gonna have to help you unfortunately.
You're good! I appreciate you taking a look
np
I have a feeling it may be the PassThrough not being recognised as a readable stream, even though it is
how would you ask the bot to pause the currently playing music?
i'm thinking player.pause(resource) but do i have to re create the player and resource objects for this?
player.pause(); (player has to be playing a resource of course)
yes but i still need to declare the player object right? if i do player.pause() say in a separate function. will it still pause? (are they the same objects i meant) and is it same for unpause? i.e player.unpause();
it won't pause if you don't have a reference to the player you want to pause (how exactly you bring the reference to your function is something I can't help you with)
it will error since it doesn't know what player is
player.unpause(); is indeed the way to unpause/resume the player
if the playing and pausing/resuming functions are in the same file you could just simply use a variable
right now i have a playCommand(title) function which makes the bot join a vc and start playing the music with that title (which it gets from youtube).
Now i want to create a separate function pauseCommand() which should pause the music that's playing inside playCommand() but of course since it's different from playCommand() i'll have to create the player objects for both separately correct?
no, don't create 2 audio players
just declare a variable like var audioPlayer = null at the start, then in playCommand(title) when you start playing assign your player to the variable audioPlayer = (player here), then in pauseCommand() you have to check if audioPlayer even exists if (audioPlayer !== null) {} and then if it exists just pause audioPlayer.pause();
though this is basic javascript and doesn't really have much to do with discord.js so I would just look online on how to do stuff in javascript
oh wait can i do it like this? I.e have them both share a common player declared at the top of the file? 👀
const player = createAudioPlayer({
noSubscriber: NoSubscriberBehavior.Pause,
});
async function playCommand() {};
function pauseCommand() {
player.pause()
};
yes that is simpler than my suggestion (I usually think too overcomplicated for these things, sorry)
nah that's alright man thanks for replying! :>>>
but I don't know if it will error if the player isn't currently playing any resource and you pause it
you should check what happens then
yup although i have to close and sleep in like 5 mins ;-;
uni tom
yo @crisp tangle MY MAN IT WORKS LIKE A CHARM!
nice
EXACTLY LIKE HOW YOU'D THINK
thanks again bruh @crisp tangle
no probs, done this before so I would be confused it didn't work for u
.
Do you have the GUILD_VOICE_STATES intent?
uhh... no
you need that intent for voice channel/state (music) related stuff
do you mean this?
const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILD_VOICE_STATES] });
Yeah
well, this intent is not in documentation, but ok
Yeah, it's a bit obscure.
bump
but it's necessary to get members' voice states? because i don't have that and i got a voice state from a member
so, what it does is getting the bot's voice state?
No, the gateway intents are used to tell your bot what updates it needs to get. This one makes sure you get updates on the voice states of users and itself. Without it, the bot will not be able to tell that you've entered, switched, or left a voice channel.
ok, let me try it
Yeah, it needs it's own connection state because otherwise it will always be 'signalling' even though it looks like it has joined.
Additionally, I don't think createAudioResource() takes relative paths. I'd make that absolute just in case.
it worked, thanks 👍
but why the functions aren't in the documentation? like joinVoiceChannel(), createAudioResource(), etc.
the documentation only shows how to do it with the constructors
That's because the documentation you're reading is likely the discordjs one. Since v13, @discordjs/voice is a separate package. You can find its documentation on its npm page.
^ what Touché said
you have to switch from Main Library to Voice on the documentation site
the link on npm redirects it to the discordjs one
but i am talking about this one
Ah sorry, it's in their github instead. Here you go https://discordjs.github.io/voice/
Oh shit, I didn't even know that. Now I don't have to have two tabs open haha.
I found out when I had Voice and was searching for text channels but it didn't come up
thank u
but how do i use AudioResource constructor?
I've never used it, but you can make AudioResources with the createAudioResource() function instead.
yea i know, but i prefer using constructors
I suppose that the memory leak with inLineVolule hasn't be fixed yet and will never be fixed
They'll probably get 'round to it, but bug-fixing and development take time and I don't think it's a big group working on djs either.
Yes I know but the bug has been reported 3 months ago. And other updates have been made on this package in 3 month 😕
In v12 I used a StreamDispatcher to play music and I could use StreamDispatcher.streamTime/StreamDispatcher.totalStreamTime to get the time the dispatcher has been playing audio for
Is there a way to do this in v13? (I've been searching for a way, haven't found one though)
It be how it be sometimes.
Sure. I Hope it will be fixed soon
I think <AudioResource>.playbackDuration gives how long a specific resource has been playing for in miliseconds. That may be of use to you.
Thank you very much! It seems that I skipped that while looking at the docs for audioResource
Oh and you can also do it for the entire player with <AudioPlayer>.state.playbackDuration I'm now reading.
hmm, if the state of the audioPlayer has such useful things, maybe I should look more into it
They're usually very usefull, yeah.
Hello,
Can someone help me with my code for music bot.
I have TypeError: voiceChannel.join is not a function
And this is my code
@azure pollen
You're using voiceChannel.join() and connection.play(...) in your code. That is for playing music in discord.js v12.
If you're currently using discord.js v13 and you somewhat know what you're doing you can read this guide for upgrading from v12 to v13: https://discordjs.guide/additional-info/changes-in-v13.html
If you only want to know how the new voice/music stuff works then read this: https://discordjs.guide/voice
Thank you, I'm trying but can't do it
You can see my code here, if you know what to do that could help me.
https://stackoverflow.com/questions/69966684/im-doing-a-discord-bot-and-having-trouble-connecting-bot-to-voice-channel-any
I've never used import before, since the one time I did, it errored
try require instead (I'm also pretty new to javascript)
const { joinVoiceChannel } = require("@discordjs/voice");
Now I have different error
(node:13348) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)
node:internal/modules/cjs/loader:960
const err = new Error(`Cannot find module '${request}'`);
^
Error: Cannot find module 'C:\Users\mgali\Desktop\Projects\DiscordBot\node_modules\@discordjs\voice\dist\index.js'
at createEsmNotFoundErr (node:internal/modules/cjs/loader:960:15)
at finalizeEsmResolution (node:internal/modules/cjs/loader:953:15)
at resolveExports (node:internal/modules/cjs/loader:482:14)
at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.execute (C:\Users\mgali\Desktop\Projects\DiscordBot\commands\play.cjs:11:38)
at Client.<anonymous> (file:///C:/Users/mgali/Desktop/Projects/DiscordBot/main.js:41:37) {
code: 'MODULE_NOT_FOUND',
path: 'C:\\Users\\mgali\\Desktop\\Projects\\DiscordBot\\node_modules\\@discordjs\\voice\\package.json'
}
You can get rid of the deprecation warning by replacing message with messageCreate
- client.on('message', message => {...} (This is from discord.js v12)
+ client.on('messageCreate', message => {...}
(^ This should be in your index file)
For the actual error it seems that it cannot find the voice module, have you installed it? (you have to install it separately than discord.js)
npm install @discordjs/voice
yarn add @discordjs/voice
pnpm add @discordjs/voice
The first error is fixec.
Yes, I've installed @discordjs/voice
does it say the same thing now?
Yeah..
node:internal/modules/cjs/loader:960
const err = new Error(`Cannot find module '${request}'`);
^
Error: Cannot find module 'C:\Users\mgali\Desktop\Projects\DiscordBot\node_modules\@discordjs\voice\dist\index.js'
can you send your code again (of the play file)?
Are you on the latest node version?
Here it is
Yes, I have the latest.
There shouldn't be a problem with your code (up until line 37 at least)
and since the error says that it cannot find the module voice\dist\index.js, I would try reinstalling the @discordjs/voice module, just to be sure.
Okey, now it's better,
now I have new error...
TypeError: joinVoiceChannel.join is not a function
This line is the problem
const connection = await joinVoiceChannel.join();
yeah joinVoiceChannel.join is not a thing
If you want to connect to a voice channel you'll have to do
joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
and if you want to have the connection as a reference for other stuff just put that in a constant variable
const connection = voice.joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
channel is the channel you will be joining. In your code that would be voiceChannel
Okeeeey now it's connecting.....
Do you know how to fix it to play, whats the name of other function?
connection.play is not a function
The error is on this line
connection.play(stream, { seek: 0, volume: 1 })
https://discordjs.guide/voice Have you read through this yet? It would take too long for me to explain how everything works and also just providing you with the functions would not help you long-term
const Discord = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus, StreamType } = require('@discordjs/voice');
const ytdl = require('ytdl-core');
const config = require('../../config.json');
module.exports = {
name : 'play',
/**
*
* @param {Discord.Message} message
* @param {Array<string>} args
*/
async execute(message, args) {
if (!args.length) return message.reply(`Exécutez la commande en insérant le lien d'une vidéo YouTube.`)
const channel = message.member.voice.channel;
if (!channel) return message.reply(`Vous devez tout d'abord de rejoindre un salon vocal !`);
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const stream = ytdl(args[0], { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
player.play(resource);
connection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => connection.destroy());
player.on('error', error => {
console.error(error);
});
},
};
I don't hear my bot in VC
I would first check if the player even starts playing
player.on(AudioPlayerStatus.Playing, () => {
console.log('Playing audio')
});
can you also use a console.log('Idle') here?
just to check if it starts playing and then maybe instantly goes back to idle
it log Idle first
ah yes, that's because the player is always idle when it's not currently playing anything, so basically before and after playing
oh I see
I see, I need to install FFmpeg, so that I can gather resources for playing music.
Ant there is no direct function for playing music....
Yeah, in short: to play music you'd have to create an audio player (also don't create a new audio player each time someone uses your play function/command, only have one)
const audioPlayer = createAudioPlayer(); //you'll have to import {createAudioPlayer} from @discordjs/voice as well, don't forget
and then subscribe your connection to that audio player.
connection.subscribe(audioPlayer);
You can then create an audio resource with your ytdl stream like so
const stream = ytdl(args[0], {filter: 'audioonly'});
const resource = createAudioResource(stream); //you'll have to import {createAudioResource} from @discordjs/voice as well, don't forget
then you can play that resource with your created audio player
audioPlayer.play(resource);
and FFmpeg has to convert your stream to an opus stream, if it isn't one
you dunno?
you want to fix it? (continued in DMs)
yes?
Thank you so much, you've been very helpful 😊
👍 I've been updating my bot to v13 for the past 2 days, so I have some experience with @discord.js/voice
please can someone answer
Hello I am updating my bot to v13 and I cannot figure out how to get the audio working. My bot joins the audio channel, but does not play any audio and get stuck in the playing state. Any advice would be appreciated.
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false
});
//check to see if connection is valid
if(connection)
{
//playing here NOT WORKING
connection.subscribe(player);
player.play(resource);
}```
what does your "resource" declaration look like? reply with a console log of the resource object. It should have valid length (>0) along with other stuff.
Also does anyone know how to setup music queue's using play-dl?
i know i already asked this earlier, but nobody knows how to use AudioResource constructor?
It looks like this thanks for the help
//sound file to play
var resource = createAudioResource(createReadStream("../files/sounds/soundFile.ogg"), {
inputType: StreamType.OggOpus,
});
Also for some reason you are right the log is outputting length 0. I check the sound file and it works on my when I play it locally
i'm having trouble in general connecting to a voice channel and playing an audio clip. is there a quick script someone could make as a base so i could use that?
// imports
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
NoSubscriberBehavior,
StreamType,
} = require("@discordjs/voice");
// joining a vc from a message
const channelID = message.member.voice.channel
.toString()
.replaceAll("<", "")
.replaceAll(">", "")
.replaceAll("#", "");
console.log(`VoiceChannel ID: ${channelID}`);
const connection = joinVoiceChannel({
channelId: channelID,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const player = createAudioPlayer({
noSubscriber: NoSubscriberBehavior.Pause,
});
connection.subscribe(player);
I did the string manipulation because the channel id returned always contained <,>,# which made it invalid you can also just do a string.match() instead.
NOTE: YOU NEED TO HAVE THIS IN YOUR INTENT
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
Intents.FLAGS.DIRECT_MESSAGE_TYPING,
Intents.FLAGS.GUILD_VOICE_STATES, //<-- important for vc
],
});
I don't know how to play resource from your local library right now though I'm just streaming stuff from youtube.
I'm trying to play internet radio urls and using the code javascript const res = await fetch(fileId); if (!res.ok) console.log("Had a problem fetching!"); return res.body;
works perfectly for something like an mp3 hosted on a webserver, but the moment I try to play something from an icecast server i get the error attached. I assume this is because the bot isn't able to load the whole stream so it times out. Any way I can get around this?
Anyone know a good hosting service for a music bot?
i used https://repl.it
is there a way to get an mp3 file playback duration which is on discord cdn?
the reason it is on cdn is because we used to put mp3 files straight into discord for Groovy to play (what used to be -p f command)
After moving a member to another voice channel, getting their voice channel id logs the previous channel id, is there like a time that I need to wait for it to update?
I do fetch member before loggin to be sure
Do I need the voice library orrrr?
Figured it out, was missing GUILD_VOICE_STATES intent

Instead of the string manipulation for channel ID you can also just get the ID property from the channel message.member.voice.channel.id.
ahh yes. Thanks!
please.
Sure I can help. Are you files local or on a webserver or on YouTube or what
local files
How confident are you with discordjs/voice already. When I get home tonight I can send some code to do that
Do you want to queue up a whole playlist or do you just generally want a queue?
You said you wanted to play multiple songs
meh, but I can do it by watching the guide/docs
Do you need help making a queue, playing a local file, or both
making a queue
that doesn't have much to do with @discord.js/voice itself, you can use some kind of array for the queue
I use a linked list for the queue
True. That is more so just standard js stuff
oh
Dm and I'll send basic queue code over
So for today and yesterday now, I've been trying to figure out why my bot's connection is always stuck on signalling, when I run my joinVoiceChannel() function. This is what I get when I print the connection itself
<ref *1> K {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
rejoinAttempts: 0,
_state: {
status: 'signalling',
adapter: {
sendPayload: [Function: sendPayload],
destroy: [Function: destroy]
}
},
joinConfig: {
selfDeaf: true,
selfMute: false,
group: 'default',
channelId: '694105448822997022',
guildId: '432175548169584642',
adapterCreator: [Function (anonymous)]
},
packets: { server: undefined, state: undefined },
receiver: q {
voiceConnection: [Circular *1],
ssrcMap: L {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
map: Map(0) {},
[Symbol(kCapture)]: false
},
subscriptions: Map(0) {},
connectionData: {},
speaking: se {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
users: Map(0) {},
speakingTimeouts: Map(0) {},
[Symbol(kCapture)]: false
},
onWsPacket: [Function: bound onWsPacket],
onUdpMessage: [Function: bound onUdpMessage]
},
debug: null,
onNetworkingClose: [Function: bound onNetworkingClose],
onNetworkingStateChange: [Function: bound onNetworkingStateChange],
onNetworkingError: [Function: bound onNetworkingError],
onNetworkingDebug: [Function: bound onNetworkingDebug],
[Symbol(kCapture)]: false
}
Nothing seems wrong with it, so I'm confused.
I've also been printing connection.state every 3 seconds. And it always outputs status: signalling, like I said before
{
status: 'signalling',
adapter: {
sendPayload: [Function: sendPayload],
destroy: [Function: destroy]
}
}
The voice channel that I want to connect to exists, its ID string exists, the @discordjs/voice package is up-to-date (also reinstalled it) and I have the GUILD_VOICE_STATES intent.
I have absolutely no idea what the problem is, and this worked perfectly 2 days ago. Any ideas?
This might seem pretty obvious but does your bot have permissions to join the requested voice channel?
yes, he has ADMINISTRATOR permissions
also when I do my play command, the bot itself joins my VC on discord physically, but the actual connection is still in the signalling state
thanks for trying to help though, that is appreciated
Hm have you tried playing some audio?
I have 2 listeners, one for when the connection has been disconnected and one for when it's ready and connected
(below is my ready listener)
connection.once(voice.VoiceConnectionStatus.Ready, () => {
if (first_state !== 'none') {
//console.log(`First state isn't none! First state: ${first_state}`);
return;
};
first_state = 'ready';
message.channel.send(`**Joined** \`${member_channel.name}\``);
queue(connection);
return;
});
It would have played the music with queue(connection), if it ever went to ready, though it hasn't had any state changes at all
But I will try to forcefully play music, and I'll report back.
(edit/report: my audio player starts playing, though the connection doesn't channel the audio)
If you use ```js
const connection = getVoiceConnection(guildId)
//console.log the state of that connection
yes, it's still at signalling continuously
Ok that's a weird one... I really have no idea right now sorry
it's okay 👍
@crisp tangle which package.json dependencies do you have?
const { joinVoiceChannel } = require('@discordjs/voice');
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
const stream = ytdl(video.url, {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
});``` why do i get this error ```js
connection.play is not a function
{
"name": "discord-bot",
"version": "1.2.0",
"description": "Bot from scratch",
"main": "index.js",
"scripts": {
"test": "echo yes"
},
"author": "TheKiller101555",
"license": "ISC",
"dependencies": {
"@discordjs/opus": "^0.7.0",
"@discordjs/voice": "^0.7.5",
"axios": "^0.24.0",
"cheerio": "^1.0.0-rc.10",
"discord.js": "^13.3.1",
"discord.js-musicbot-addon": "^13.9.1",
"eslint": "^8.2.0",
"ffmpeg": "0.0.4",
"ffmpeg-static": "^4.4.0",
"install": "^0.13.0",
"jquery": "^3.6.0",
"jsdom": "^18.1.0",
"libsodium-wrappers": "^0.7.9",
"opus": "0.0.0",
"opusscript": "0.0.8",
"request": "^2.88.2",
"updated-youtube-info": "^1.4.7",
"ytdl": "^1.4.1",
"ytdl-core": "^4.9.1",
"ytdl-core-discord": "^1.3.1"
}
}
I took the code you send above and created a small bot which joins the voice channel perfectly fine
const voice = require('@discordjs/voice');
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_VOICE_STATES
]});
console.log(process.version)
client.login(process.env.TOKEN);
client.on('messageCreate', async(message) => {
//...
const member_channel = message.member.voice.channel;
//...
if (message.author.bot) return;
if (!member_channel) {
return message.channel.send('**You have to be in a voice channel to use this command**');
};
//...
const connection = voice.joinVoiceChannel({
channelId: member_channel.id,
guildId: member_channel.guild.id,
adapterCreator: member_channel.guild.voiceAdapterCreator,
});
//...
console.log(connection.state)
connection.on('ready', () => {
console.log(connection.state)
message.channel.send(`**Joined** \`${member_channel.name}\``);
//queue(connection)
return;
});
});
using the following dependecies
"@discordjs/opus": "^0.7.0",
"@discordjs/voice": "^0.7.5",
"discord.js": "^13.3.1",
"ffmpeg-static": "^4.4.0",
"libsodium-wrappers": "^0.7.9"
seems like it's the same
anyone know?
yeah I think it doesn't anything to do with the code itself, since it worked perfectly before
I'll maybe try reinstalling all packages later (but right now am busy doing something)
read the guide in the pins on how to play audioresources
also seek doesn't exist in v13 anymore
I have a question about inline audio. The docs says "Enabling it will allow you to modify the volume of your stream in realtime.". Is there a way to modify the volume once when you create the resource without a performance decrease?
// Will use FFmpeg with volume control enabled
resource = createAudioResource(join(__dirname, 'file.mp3'), { inlineVolume: true });
resource.volume.setVolume(0.5);```
that's what the guide says so I assume no (not with djs)
Ok, the speciation of "in realtime" made me think it was possible
hmm let
Error: Error: Cannot find module '/home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm-glibc-2.28/opus.node'
Require stack:
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/@discordjs/opus/lib/index.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/prism-media/src/util/loader.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/prism-media/src/opus/Opus.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/prism-media/src/opus/index.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/node_modules/prism-media/src/index.js
- /home/pi/NodeBot/node_modules/@discordjs/voice/dist/index.js
- /home/pi/NodeBot/commands/music/play.js
- /home/pi/NodeBot/handlers/command_handler.js
- /home/pi/NodeBot/bot.js
anyone know how to fix this error? (i fixed it by reinstalling @discordjs/opus and @discordjs/voice one by one)
connection.destroy()
because you have to create an audioPlayer with discordjs/voice and subscribe it to the connection (using connection.subscribe()) and then do yourAudioPlayer.play(). it's the audioPlayer that plays the song in v13, not the connection
connection.destroy() to delete the connection
I have socket closed error and abort_err how can I fix this
Anyone can help me? I'm trying to install sodium but it giving an error
is there a way to get an MP3 song length which is on a URL?
I keep randomly getting emmited errors when my bot plays music at @discordjs\voice\dist\index.js:8:288
I figured it had something to do when my bot wasn't idle and something about the audio resource
What is the error?
i want to make a seek command and audio filters with the help of stream url and ffmpeg , is there any repo examples or snippet ? I am lost right now , i tried ffmpeg from prism-media
how can i make the bot join the vc using @discordjs/voice?
I'm trying to play audio from one vc to another but im getting this error
Cannot play a resource that has already ended.
You can't replay AudioResources. You need to make a new one.
Hi, I just deployed my bot from my windows machine to my linux server. Everything worked perfectly fine, but when I switched to linux I suddenly have no sound when playing something without any errors. Do I need to do something differently when using a linux system?
You can install python or use opusscript instead.
I get this error: SyntaxError: Unexpected token '.' from the /node_modules/@discordjs/voice/dist/index.js:1 file and since the first line is really, really long I can't see where the error is
the terminal only says line 1 but not the position in that line so I don't know how to fix this
this is the whole line 1 in that file
could someone help me pls?
nevermind, I think I found a way to find the errors, thanks anyways
const opusStream = connection.receiver.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
const resource = createAudioResource(opusStream, {
inputType: StreamType.Opus,
});
the player playing this audioressource is going into idle state after the first pause (while speaking e.g. starting a next sentence), while streaming to a file or listen through a browser is no problem and the stream doesn't stop at the first speakingpause
i'm using discord.js v12 with ytdl-core and discordjs/opus
is there any way to change the volume?
my current code looks something like this:
filter:'audioonly',
highWaterMark: 1 << 25
});
dispatcher = connection.play(stream,{seek: 0,volume: 1})
/*dispatcher = connection.play(ytdl(musicq[0],{
filter:'audioonly',
highWaterMark: 1 << 25
}));*/
clearTimeout(autodc);
playing = true;
dispatcher.on('finish',()=>{
musicq.shift();
music(message);
playing = false;
});```
(the commented out part is what i used before, the other part from var stream = ... is what i tried from reading random stuff on the internet, but that does not change the volume)
Support is no longer provided to v12, the last post in #769862166131245066 has a link on how to update to v13.
and how would i do that in v13?
In v13 you can use inline volume which is explained in the guide.
oh alright, thank you very much for the help!
np
anybody can help?
getting the recieverstream over a webserver leads to the same problem
the EndBehaviorType isn't the problem. Changed also to Manual and the player goes in idle mode after the first pause/silence
How to get the bot deaf himself?
Pass setSelfDeaf as true when joining a channel
Its true by default anyways tho
how do i get a player from a play command to a pause command?
hey, how would I go about recieving audio?
also what is duration in end?
It seems that the error was that the joinVoiceChannel() function was called in an async function? I removed async and it worked perfectly, but I require it to await client_user..
const client_user = await message.guild.members.fetch(message.client);
const client_channel = client_user.voice.channel;
I use client_user to check for the client_channel, which is the channel, that the bot is currently in, since I don't want anyone outside that voice channel to be able to use the music commands.
Any ideas on how to wait on client_user (other than await, since it breaks @discordjs/voice) or on how to get the bot's channel in a different way?
maybe check for interaction.member.voice or message.member.voice ?!
const member_channel = message.member.voice.channel;
Though that is for the message author's channel/voice, I need that of the bot's and after some time I used that fetch method to get my bot's user
message.member.voice.channel.members.has(message.client.id)
could work
const voice = require('@discordjs/voice');
async execute(message, args) {
const client_user = await message.guild.members.fetch(message.client);
const client_channel = client_user.voice.channel;
const client_connection = voice.getVoiceConnection(message.guild.id);
const member_channel = message.member.voice.channel;
if (client_channel) {
if (!member_channel) {
return message.channel.send('**You have to be in a voice channel to use this command**');
};
if (client_channel !== member_channel) {
return message.channel.send('**You have to be in the same voice channel to use this command**');
};
if (client_connection) {
if (client_connection.state.status !== voice.VoiceConnectionStatus.Ready) {
return console.log('Connection is not ready');
};
console.log('Client is already in channel | Running queue function')
//queue(client_connection);
return;
};
};
if (!member_channel) {
return message.channel.send('**You have to be in a voice channel to use this command**');
};
const connection = voice.joinVoiceChannel({
channelId: member_channel.id,
guildId: member_channel.guild.id,
adapterCreator: member_channel.guild.voiceAdapterCreator,
});
var first_state = 'none'
connection.once('ready', () => {
if (first_state !== 'none') {
return;
};
first_state = 'ready';
message.channel.send(`**Joined** \`${member_channel.name}\``);
//queue(connection);
return;
});
connection.once('disconnected', () => {
if (first_state !== 'none') {
return;
};
first_state = 'disconnected';
return message.channel.send(`Something went wrong while trying to join \`${member_channel.name}\``);
});
},
Here's the short version (edited down), since the queue() & play() functions would be too long and aren't really the problem here.
Before in v12 discord.js, I was able to do const client_voice = message.guild.voice; and I could get the bot's voice channel from there on with client_voice.channel, but now guild.voice has been removed (I can't find this in the docs anymore) and I have no idea how to get the bot's channel/voice. I've been searching around for hours to see how others have coded their music bots (youtube tutorials, other open source bots.. bla bla bla) and I've seen how they all check if the member is in a voice channel, but not one that checks if the member is in the same voice channel as the bot. Maybe I'm just unlucky..
you're trying to join a voicechannel, but you're saying the bot is already in a voicechannel?!
I'm not sure I understand what you're trying to say, but what I want is:
If the bot is already in a voice channel (joined someone in some voice channel earlier), then a member who isn't connected to the voice channel the bot is currently in shouldn't be able to use the music commands.
I have to go to sleep now though
Okay so i spent 12 goddamn hours trying to figure this out, so I'm putting this here in-case anyone else runs into this.
If you are using the same audioplayer and changing what it is playing via the .play method, and it happens to be a stream URL, you can never use that URL again unless you make a brand new audioplayer and subscribe the VC to it
My workaround was just to pass in the audio data via axios, vs letting discord.js handle the URL on it's own
It's literally the most confusing thing, and debug shows nothing about it- literally the only reason I figured this out was by wondering to myself if the docs reference to " the existing resource is destroyed (it cannot be reused, even in another player)" could possibly mean a passed in string to a createAudioResource method
and low and behold, it somehow was.
const connection = joinVoiceChannel({
channelId: message.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const player = createAudioPlayer();
player.on("error", err => {
throw err;
});
// don't get any error when i delete the part below
player.play(ytdl(video.url, {filter: "audioonly"}));
connection.subscribe(player);
this is my code to play song in a channel but everytime i got this error
try:
async execute(message, args) {
const client_user = await message.guild.members.fetch(message.client);
const client_connection = voice.getVoiceConnection(message.guild.id);
const client_channel = !client_connection ? null : client_connection.joinConfig.channelId;
const member_channel = message.member.voice.channel;
...
if (client_channel !== member_channel.id) {
return message.channel.send('**You have to be in the same voice channel to use this command**');
};
Can u show the beginning of the error?
and after there is the big error
Looking at the second line there seems like ur trying to play a resource tvag has already ended
no this is some code
idk for why but that send me the whole code of a file
Does that occur everytime?
yep
but nvm i just go to 12.5.3 version cause 13.3.1 is horrible
channelId: message.channel.id, so you're trying to make your bot join a text channel..?
Or did you want to join the voice channel of the guy who sent the message? (That would be message.member.voice.channel.id)
Though do check first if he's even in a voice channel.
That is a smart idea, I'll try it out tomorrow. Thanks for the help!
yeah i juste that i change the version of disord.js to v13 but there is too much drastic changes so i didn't paid attention, but thx
👍
const connection = Voice.joinVoiceChannel({
channelId: inChannel.id,
guildId: inChannel.guildId,
adapterCreator: inChannel.guild.voiceAdapterCreator
});
const audioPlayer = Voice.createAudioPlayer();
audioPlayer.play(ytdl(video.url, {filter: "audioonly"}));
connection.subscribe(audioPlayer);
i got the same big error...
The number of times I see this error in this channel is astounding. You need to create an audio resource to play in it
but in the docs that say that you can pass a stream data
Inside an audio resource
AAAAAAAAAAAAAAH
that version trigered me soo much
have you seen the guide for the v13 voice library @late vigil, it explains everything
ex:
import { createAudioResource } from "@discordjs/voice"
createAudioResource(streamDataHere, { optionsifany })
and you will play the audio resource, as in, what the method above returns
Admittedly, the docs aren't super clear on that^ so I understand the confusion! hope this helps
yeah don't worry i get it now, its just the v12 that made me don't paid attentions to details
nah you're all good. I've had my fair share of troubles with the voice lib myself because of lackluster documentation lol
the olds devs have left discord xD
hmm, I haven't had to look at the docs for the voice library at all to get my bot to play music (maybe I'm lucky)
is it just me who read the entire guide to the voice library?
i have to cause the intelisense of vscode is broken else idk how did you know how to get variables
Personally I'm doing a lot of unconventional things with it, splitting streams, piping data to and from remote nodes, etc; for the avg joe it's pretty good, but for the more complex things, I've run into lots of odd gimmicks that aren't noted anywhere lol cc: @crisp tangle
that triggered me a lot more to see that we have to go with function instead of classes or object, the v13 change so much, idk why they did this
It's actually super nice quite honestly, because everything is modular
Like I have many of my own classes, and instead of needing to extend off an existing class like in some prior versions, I can just import what I need
This may not be directly related to to the voice library, but was hoping a lovely person could help. I am currently using node-fetch to get an audio stream and then piping that ReadableStream through a transformer, and then passing that ReadableStream to .play(). The problem is sometimes the stream will go to idle suddenly, I figure it's a network problem but I really don't know how to recover gracefully and restart the stream if this happens
I would just listen to the idle statechange and just play the stream again but the idle event is fired when theres no subscribers to the stream
Werid thing is that I didn't have this issue with the same code on v12
Any idea why this would be happening:
Error: Cannot find module '(directory-name)/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-x64-glibc-2.31/opus.node'
Okay I was able to fix it actually.
Appears to have been because I accidentally installed on an older node version (I think I installed on v14).
Removing node_modules and reinstalling (via npm install of course) fixed the problem 
@celest basalt may wanna add another pin for this or something since there is a v0.7, specifically a v0.7.4 as of now 
Up to you of course 
any ideas?
How does the player determine when to throw the player idle event? I've attached listeners to all of the streams including the probe to listen for the end event, but none of them throw that event.
I'm running into the issue of the player ending prematurely
Yeah. It's just the AudioResource.playStream being closed. None of the other streams are emitting close before the playStream, so it's coming from the pipeline
The problem ended up being that I assigned the playStream as the result of a pipe from the stream to a FFMPEG class from prism-media. Instead, I now just manually specify the stdin and stdout
const connection = getVoiceConnection(int.guildId);
if (connection) {
const player = //HOW DO I GET THE PLAYER WHILE IS PLAYING, ive defined the player in a different file!
console.log(player.pause());
}
},
connection.state.subscription.player
Can someone tell me what I am doing wrong here ?
const voicechannel = interaction.member.voice.channel;
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
async function connectToChannel(channel) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30_000);
return connection;
} catch (error) {
connection.destroy();
throw error;
}
}
const record = interaction.options.getString("record");
const audiosPath = __dirname + "../Audios/";
const resource = createAudioResource(audiosPath + record);
const connection = await connectToChannel(voicechannel);
player.play(resource);
connection.subscribe(player);
},
Its joining the voice channel but not playing the opus stream
Checking for the ID instead of the voice channel itself works, thank you very much for the help!
try connectToChannel, then subscribe player, then create resource, then play resource
also check the path is correct
is it still possible to record user voices with the bot?
thanks for posting this code , I am newbee
Hello, I tried making a music discord bot using ytdl. Here's my code:
const Discord = require("discord.js");
const Commando = require('discord.js-commando');
const ytdl = require('ytdl-core');
const client = new Discord.Client({
intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES],
});
client.on('message', async message => {
let args = message.content.split(' ');
const command = args.shift().toLowerCase();
if (command == "amogus!p") {
if(!message.member.voice.channel)
message.channel.send(`${message.author.name} sussy bot`);
const connection = await message.member.voice.channel.join();
let url = "";
for(let i = 0; i < args.length; i++)
url += args[i];
connection.play(ytdl(url));
} else if(command == "!leave") {
message.guild.me.voice.channel.leave();
}
});
client.login("unknown");
I've installed the following packages:
root@1.0.0 /root
├── @discordjs/opus@0.5.3
├── @discordjs/voice@0.7.5
├── discord.js-commando@0.12.3
├── discord.js@12.5.3
├── discordjs-ytdl@2.2.0
├── ffmpeg-static@4.4.0
├── mongoose@6.0.12
├── node@16.6.1
└── openweather-apis@4.4.2
```.
My bot is joining the channel, but after awhile I get this error:
/root/node_modules/discord.js/src/client/voice/VoiceConnection.js:303
this.emit('error', new Error(reason));
^
Error [VOICE_CONNECTION_TIMEOUT]: Connection not established within 15 seconds.
at VoiceConnection.authenticateFailed (/root/node_modules/discord.js/src/client/voice/VoiceConnection.js:303:26)
at /root/node_modules/discord.js/src/client/voice/VoiceConnection.js:324:61
at Timeout.<anonymous> (/root/node_modules/discord.js/src/client/BaseClient.js:83:7)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
[Symbol(code)]: 'VOICE_CONNECTION_TIMEOUT'
The bot is running on my ssh client
Feel free to tag me if you get anything.
May not be the issue but if member.voice.channel is null, you should return after sending the message. Otherwise you'll try to join the channel anyway after that
Yeah, I forgot about that, but it still the same
@deep dome i have looked everywhere sry for @
This feature isn't documented in the Voice API by Discord and is prone to breaking quite a lot. We have basic support for it in the voice library currently, but there is still work going on to add utilities to make it easier to work with.
pinned message
Should I open a thread about my problem ?
I've made a bot with your code and everything worked. The only thing I changed was the audio resource and its stream, so that's probably the source of your problem.
https://github.com/discordjs/voice/tree/main/examples/recorder i assume this is a example relevant to you
thank you
Thats really strange
The funny thing is its saying it ended playing the resource but there is no sound coming from the bot
Playing youtube music via ytdl
Also my resource is a opus audio file
const record = interaction.options.getString("record"); what is this if I may ask?
Its the interaction option value
which is the file name with the extension
I am pretty sure its not a path issue
I tried, same problem :/
I also just tried playing a opus file locally saved, and it worked for me. I'm not exactly sure why it wouldn't work for you. You said the path is not the issue, does that mean you've console logged it and checked it already?
Yes
C:\Users\name\Desktop\discord-bot-test../discord-bot-test/Audios/music_test.opus is what I get when I console log my audiosPath + filename (filename = record) and it doesn't seem to be quite correct.. since it just has a random ../ in the middle of it (also the bot didn't play anything like you said as well)
wouldn't const audiosPath = "./../Audios/" suffice? I tested it with just that and it worked.
Or const audiosPath = "../Audios/";
I guess that works as well. Thanks for mentioning that, I learned more about how to do file related stuff today 
no pb
How can I detect when the songs are finished?
The audio player will return to its idle state once it finishes playing its audio resource. You could listen in on that
player.on('stateChange',(oldState,newState) => {
console.log(newState)
if(newState == "idle"){
guild.nowPlaying++;
player.play(guild.queue[guild.nowPlaying]);
guild.connection.subscribe(player);
console.log('Next Song')
}
})```
I did something like this it didn't even print the new state :/
There isn't an event stateChange for audio players like for connections. You would have to do
player.on('idle', () => {
guild.nowPlaying++;
player.play(guild.queue[guild.nowPlaying]);
guild.connection.subscribe(player);
console.log('Next Song')
});
here are the documented states https://discord.js.org/#/docs/voice/stable/typedef/AudioPlayerStatus
Trying
My song finished but didn't give any response
try AudioPlayerStatus.Idle instead of 'play' just in case (don't forget to import/require AudioPlayerStatus)
player.on(AudioPlayerStatus.Idle, () => {
guild.nowPlaying++;
player.play(guild.queue[guild.nowPlaying]);
guild.connection.subscribe(player);
console.log('Next Song')
});
@crisp tangle ,
What exactly does this event entail?
oh wait... I put in the wrong event
ok basically:
It is in Idle when it's not currently playing any resource.
And it is in Playing when it's currently playing a resource.
I've had the thought that it could fire my Idle listener before I even start playing anything, but I've dealt with that and your code is structured in a way that I think that wouldn't happen
I meant AudioPlayerStatus.Idle in my previous message, not AudioPlayerStatus.Playing, sorry for that mistake
these two should correspond to 'idle' and 'playing', but it didn't work for me when I tried listening in on the strings themselves, so I'm currently using AudioPlayerStatus
Didn't catch :/ 😦
thank you for this information
if you want the other events as well, it's all here
but let me try making a new bot with your code real quick
I'm waiting
Problem is that you're returning when you add to queue or start the queue, so the listerner's code isn't even being ran/registered
Does anyone know how to specify input stream parameters in prism-media ffmpeg module?
Every once and a while I randomly get this error. Any idea why?
AudioPlayerError: aborted
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:407:19)
at TLSSocket.emit (node:events:402:35)
at node:net:672:12
at TCP.done (node:_tls_wrap:580:7)
should I just reconnect the bot if I get this?
I wrote above and problem solved. thank you for all your help
👍
what's your node.js version? (nevermind, I had thought of a possible issue but it isn't one)
v16.10.0
Music stop event for player?
help
This is an issue of ytdl-core
Do you want to do something when the player stops or do you want to stop the player?
I want to auto skip music on music end
need I get music duration and do setTimeout?
so you want to do something when the player stops playing music?
player.on(AudioPlayerStatus.Idle, () => {
//your code
});
ok thx
and how to get all memvers in vchannel?
voiceChannel.members (returns a collection/map of the members in the voice channel) https://discord.js.org/#/docs/collection/main/class/Collection
Is this an ongoing issue? I cannot install @discordjs/opus at all, its giving me some weird node-pre-gyp errors with it trying to find python for some reason
windows or mac?
im using repl node v16 so that would be linux ig?
hmmm - don't know about repl.it
i think repl.it runs projects on linux
yeah i know that, so is the package not supported in it?
can we make it so that on joining a stage a bot starts the stage as well
what do you mean with 'stage'?
stage channel but nvm i found it ty
have you solved the issue?
nop
i think i figured it out though, the project I'm using as a fork in repl lacks builds so its difficult to achieve this
But how do I deaf/undeaf the bot when it is already connected to the voice channel?
I do not know of a way where a bot can deaf itself (self deaf), but if I wanted to do something like that I would have done the closest thing possible:
const client_user = await message.guild.members.fetch(message.client);
client_user.voice.setDeaf(false, 'no'); //.setDeaf(boolean, reason);
I'm fetching the bot as a member in message's guild and getting its voicestate, after that I can server mute/deaf the bot, but that isn't self-mute/-deaf.
Though why would you want the bot to self-deaf/undeaf anyways?
Music bots usually self deaf bc it’s a waste of load to receive voice
They can receive voice?
Bots can receive voice
Server mute and self mute is different
Anyone with perms can edit other member's server mute status, but not self mute
I know that much, that's why I stated it's different than what they wanted
but if the bot does have the permission, instead of self-muting on join, it can server-mute/server-deafen itself, achieving what ragepappa wanted
eh whatever, I have no idea what I'm talking about and what uses the option to self-mute/self-deafen would have anyway
I don’t think self deaf can be edited once the connection has been created due to the way voice is structured
Okay
this <AudioResource>.playStream doesn't look very reliable
any idea about this error? Error: Premature close
happens when I try to play (again) a <AudioResource>.playStream
did you try running it as a function..?
running what as a function?
.playStream, or what did you do to get that error?
doesn't really look like a function to me but
I know, that's why I asked
I'm not sure what this property is, do you know?
I guess it is the stream of this resource?
in case, <AudioResource>||<- THIS resource||.playStream
I'm currently facing an issue where the audio player constantly and randomly aborts songs while playing
does anyone know why this is the case?
what does your code look like for creating an audio resource?
// Convert youtube URLs to audio resources
// @param song - The song to be converted into an audio resource
// @return - no return value
function convertURL(song) {
const resource = ytdl(song.url, { filter: "audioonly" });
return createAudioResource(resource , { inputType: StreamType.Arbitrary });
}
// Convert the song url and create an audio resource
=queue.audioPlayer = createAudioPlayer();
queue.resource = convertURL(queue.songs[0]);
// Play the song
queue.audioPlayer.play(queue.resource);
sendMessage(queue, client);
// subscribe to the connection
connection.subscribe(queue.audioPlayer);
// Catch any errors/disconnects
queue.audioPlayer.on('error', error => {
console.log(`Error: ${error.message} with resource ${queue.resource.metadata}`);
});
// Wait for the song to finish and play the next song
queue.audioPlayer.on(AudioPlayerStatus.Idle, () => {
// Shift queue and play next song
queue.songs.shift();
queue.audioPlayer.stop();
this.play(client, guildId);
});```
okay, it seems you don't have the same problem I had, I'll leave this up to others, since I don't know the exact issue
what I had done is createAudioResource(resource, { inputType: StreamType.WebmOpus }); and that caused the issue of my audio player just stopping and erroring abort somewhere in the middle of the song, and when I just completely removed inputType, it worked again. I think it had to do something with if ffmpeg converted or not. I don't if Arbitrary gets converted by ffmpeg
I'm converting youtube URLs so it told me to use Arbitrary stream typ
well not specifying inputType works for me
const stream = ytdl(current_link, { filter: format => {format.codecs === 'opus'; format.container === "webm"}, filter: 'audioonly', highWaterMark: 1 << 25});
const resource = voice.createAudioResource(stream);
are you using a youtube link for current_link?
yes I am
Ok let me try to implement your code, thanks for helping
👍
what is highWaterMark?
from what I found out, it's the buffer for the stream (how much it downloads/pre-caches before)
and apparently 1 << 25 is 32mb (default is 16mb)
hmm ok, is there a detailed documentation for audio player and resources?
not sure what you mean with detailed, but I only know of one documentation for voice stuff (discord.js.org docs themselves)
https://discord.js.org/#/docs/voice/stable/general/welcome
thanks for the help
👍 no problem, I'm going to bed now though
alright
does anyone know why sometimes an audio player speeds up
I want to find out the number of users on the channel
"discord.js": "v13.3.1"
TypeError: Cannot read properties of undefined (reading 'members')
const cd = client.channels.cache.get(oldChannel).members.size
cd === members count size
Hello! how can i fix it ? reject Promise {
[
{
status: 'connecting',
adapter: [Object],
networking: [Networking]
},
{ status: 'ready', adapter: [Object], networking: [Networking] }
]
} AbortError: The operation was aborted
at abortListener (node:events:838:14)
at EventTarget.<anonymous> (node:events:874:47)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
at EventTarget.dispatchEvent (node:internal/event_target:504:26)
at abortSignal (node:internal/abort_controller:97:10)
at AbortController.abort (node:internal/abort_controller:122:5)
at Object.entersState (/home/runner/Music-Bot/node_modules/@discordjs/voice/dist/util/entersState.js:20:56)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}
remove entersState function from your code.
How to play specific hz?
is the AudioReceiveStream for recording a voice channel?
seek when? 😩
Hello message.member.voice.channel; is always undefined I don't know why
the channel you're trying to get the members of doesn't exist (is undefined) as error says
have you enabled the necessary intents?
aka GUILD_VOICE_STATES
hey! how can i get a whole voice channel's audio?
i want to record a voice channel and then save it to mp3 file
who's the owner of djs/voice?
It works thanks !
AbortError: The operation was aborted
at abortListener (node:events:842:14)
at AbortSignal.<anonymous> (node:events:878:47)
at AbortSignal.dispatchEvent (D:\CracklesCreeper\Discord Bots\Orders\Mega Joshy\node_modules\event-target-shim\dist\event-target-shim.js:818:35)
at abortSignal (D:\CracklesCreeper\Discord Bots\Orders\Mega Joshy\node_modules\abort-controller\dist\abort-controller.js:52:12)
at AbortController.abort (D:\CracklesCreeper\Discord Bots\Orders\Mega Joshy\node_modules\abort-controller\dist\abort-controller.js:91:9)
at Timeout._onTimeout (D:\CracklesCreeper\Discord Bots\Orders\Mega Joshy\node_modules\shoukaku\src\guild\ShoukakuConnection.js:139:53)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
code: 'ABORT_ERR'
}``` this is the full error I get when I try to connect my bot to a voice channel. How do I fix it?
I am trying to use lavalink btw
Do you have the GUILD_VOICE_STATES intent enabled in your client?
Yes
Is your source also playable?
Yes
Try to do it again and log all messages with the debug event on your client to check if your bot can really connect to the Discord API
It doesn't log anything
I tried
Can you show your code?
I was using a framework
https://npm.io/package/shoukaku this one
This is not @discordjs/voice so I won't be able to help you with this
Oh ok, but it gives error while connecting so thought it was related
Hello ```js
if (!voiceChannel) return message.channel.send('I'm sorry but you need to be in a voice channel to play music!');
var connection = await joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const stream = ytdl(video_url, { filter: 'audioonly' });
const resource = createAudioResource(stream, { inlineVolume: true });
resource.volume.setVolume(0.5);
connection.play(resource); ```
This code return my this error : ```js
connection.play(resource);
^
TypeError: connection.play is not a function
at Client.<anonymous>
play() is not a function of VoiceConnection objects. To play an AudioResource you must create an AudioPlayer and call <AudioPlayer>.play(resource) on that.
how do I seek?
Today i can kick my bot in voice channels by this
if(message.member.voice?.channelId) and connection.destroy()
But i can also kick from just being in a voice channel, any way to make bot understand not to leave the channel if you are in any other channel that the actual one that bot are in?
Get the connection of that guild and check whether the channelId of the bot's connection is the same as the one of the message.member @cloud vine
Seek option doesn't work anymore you can use ffmpeg as a workaround
I know, and I tried that
but I don't know if I'm doing something wrong
because, it's taking A LOT to seek, about 20 seconds to seek to 2 min of a song
Google djs voice receiver there are a couple examples for v13 as well
const ffmpeg_instance = new prism_media.FFmpeg({
args : ['-ss', '5000ms', '-accurate_seek' ,'-i', songurl, ...FFMPEG_OPUS_ARGUMENTS ]
})
looks great! but what is this "prism_media", and what is "...FFMPEG_OPUS_ARGUMENTS"?
prism-media npm package I believe
makes sense, and songurl can be the stream?
or what?
what about ...FFMPEG_OPUS_ARGUMENTS?
nvm
just found it
const FFMPEG_OPUS_ARGUMENTS = [
'-analyzeduration',
'0',
'-loglevel',
'0',
'-acodec',
'libopus',
'-f',
'opus',
'-ar',
'48000',
'-ac',
'2',
];
Yeah that one work😀👍
or that, ye
and the songurl?
because I have the stream from ytdl / soundcloud
Uhm I downloaded the song and than used seek on it... I don't know whether you can directly use it on the stream (I don't think so)
And then just passed the file path
'-'
I just read the docs
and apparently you can input a readable stream too
so I'll try that
thanks for the help
Great 👍
that aint working bro
I tried for a long time
check this out: I have my args here
I tried creating the ffmpeg transcoder, pipe, and then play
the bot appeared with the green ball of speaking, but wasn't playing anything
I also tried using -i ytdlStream, same result
I used ```js
const info = await ytdl.getInfo('url')
await ytdl.downloadFromInfo(info, { quality: 'highestaudio'}).pipe(fs.createWriteStream('./filename')
well, doesn't look like you used ffmpeg at all
And than ```js
const FFMPEG_ARGUMENTS = [
'-analyzeduration', '0',
'-loglevel', '0',
'-f', 's16le',
'-ar', '48000',
'-ac', '2',
];
const stream = new prism_media.FFmpeg({
args: ['-ss', 00:00:10, '-i', './filename' , ...FFMPEG_ARGUMENTS],
});
const resource = createAudioResource(stream, { inputType: StreamType.Raw });
oohh
now we talking
no, we not talking
same thing as always 😭 not working
Tanks ! ```js
var connection = await joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const player = createAudioPlayer();
const stream = ytdl(video_url, { filter: 'audioonly' });
const resource = createAudioResource(stream, { inlineVolume: true });
resource.volume.setVolume(0.5);
player.play(resource);
connection.subscribe(player); ``` But my bot doesn't join the channel
The channelId property of the object you parse in a joinVoiceChannel() function must be the ID of a VoiceChannel not the channel itself. Just change that to channelId: message.member.voice.channel.id,.
does anyone know what Error: Status code: 410 with resource null means?
// Catch any errors/disconnects
queue.audioPlayer.on('error', error => {
console.log(`Error: ${error.message} with resource ${queue.resource.metadata}`);
});```
Ytdl core is throwing error status 410
How to change volume of resource?
{
library: 'SSL routines',
function: 'ssl3_get_record',
reason: 'decryption failed or bad record mac',
code: 'ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC',
name: 'PlayingError'
}``` what does this error mean when I try to play an audio?
Try search on it in google
There is a section in the guide on how to change the volume of the player
nvm I fixed it
How do i access resource which is being played through an AudioPlayer class instance?
does anyone know why sometimes the discordjs audio player randomly throws an error with a status code 403?
its an error that came from ytdl-core
It does not give an error, but the song does not play, what could be the reason?
There is a sound at first, but it cuts off immediately
He doesn't do it on every song, occasionally
My song play code
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
const resource = createAudioResource(ytdl(song_info['url']), {
metadata: {
song: song_info
}
});
player.play(resource);
guild.connection.subscribe(player);```
Hi,
my bot every time getting this error
AudioPlayerError: aborted
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:407:19)
at TLSSocket.emit (node:events:406:35)
at node:net:672:12
at TCP.done (node:_tls_wrap:580:7)
does anyone know why
node v16.9.1
{
"dependencies":{
"@discordjs/opus": "^0.5.3",
"@discordjs/voice": "^0.6.0",
"discord.js": "^13.1.0",
"ffmpeg-static": "^4.4.0",
"libsodium-wrappers": "^0.7.9",
"youtube-dl-exec": "^1.2.6",
"yt-search": "^2.10.2",
"ytdl-core": "^4.9.1"
}}
my bots joining the voice channel i want it to join but it deafens itself and doesnt undeafen itself when i tell it to even though the selfDeaf part of the voicestate object changes to false heres the relevant code ```js
joinVoiceChannel({
channelId: channel.id,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator
});
message.guild.voiceStates.resolve(client.user.id).selfDeaf = false;
await message.reply("i have arrived");
const receiver = new VoiceReceiver(getVoiceConnection(message.guildId));
try this
joinVoiceChannel({
channelId: channel.id,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator,
selfDeaf: false
});
that worked thanks

I always get this error, even if I'm moving from ytdl/@discordjs/voice
I just wanted to play Audio:
let VoiceConnection = joinVoiceChannel({channelId: channel.id,guildId: channel.guild.id,adapterCreator: channel.guild.voiceAdapterCreator});
const resource = createAudioResource(path.join(__dirname + `/audio/${CmdName}.mp3`), {inlineVolume: true});
resource.volume.setVolume(0.2);
const player = createAudioPlayer();
VoiceConnection.subscribe(player);
player.play(resource);
player.on("idle", () => {
try {player.stop();} catch (e) {console.log(String(e).grey)}
try {VoiceConnection.destroy();} catch (e) {console.log(String(e).grey)}
});
It didn't work..
found out that i need: Intents.FLAGS.GUILD_VOICE_STATES
Didn'T know that... and docs / guide don't tell me that..
maybe that should be told in the guide
Any idea what causes this error or how I can solve it?
20:03:28: AbortError: The operation was aborted
20:03:28: at abortListener (node:events:838:14)
20:03:28: at EventTarget.<anonymous> (node:events:874:47)
20:03:28: at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
20:03:28: at EventTarget.dispatchEvent (node:internal/event_target:504:26)
20:03:28: at abortSignal (node:internal/abort_controller:97:10)
20:03:28: at AbortController.abort (node:internal/abort_controller:122:5)
20:03:28: at Timeout.<anonymous> (/home/dzlandis/Discord-Scriptly-Free/node_modules/@discordjs/voice/dist/index.js:9:420)
20:03:28: at listOnTimeout (node:internal/timers:557:17)
20:03:28: at processTimers (node:internal/timers:500:7) {
20:03:28: code: 'ABORT_ERR'
20:03:28: }
what are AudioResource#metadata for? i mean, how can i use them once i assigned a value?
connection.state.subscription.player.state.resource.metadata
Error: Cannot play a resource that has already ended. How can I solve this error?
you create a new resource isntead of trying to play the already played one
How can i record user voice with my bot? I'm using this code but doesn't work
const rec = new VoiceReceiver(server.connection);
const stream = createListeningStream(rec, data.interaction.user.id);
setTimeout(()=> stream.destroy, 5000);
stream.pipe(fs.createWriteStream('test.ogg'));
function createListeningStream(receiver, userId) {
const opusStream = receiver.subscribe(userId, { emitClose: false, autoDestroy: false });
const resource = createAudioResource(opusStream, { inputType: StreamType.Opus });
const player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Play } });
player.on(AudioPlayerStatus.Idle, () => {
console.log('IDLE');
});
player.play(resource);
setInterval(() => console.log(opusStream.destroyed), 1000);
receiver.voiceConnection.subscribe(player);
return opusStream;
}
I'm getting this error when i try to play audio from one vc to another
Cannot play a resource that has already ended.
I'm already aware it's something like i can't replay an audio resource, if so how can i fix this
It's exactly as you suspect. You just have to make a new one.
but i have to pass in an user id to listen to the user who's speaking and i need to listen to the start event for that so i'm not sure how i'd do that, would you mind showing me an example?
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('pokedex is online!!');
});
// Login to Discord with your client's token
client.login(token);
this is my code in discord js. i have installed ffmpeg - static in my folder
also i have a folder named songs. It contains a song named cloud9.mp3 in it.
how do i make my bot play cloud9 thats inside my folder, in a VC?
├── discord.js@13.3.1
├── eslint@8.2.0
└── ffmpeg-static@4.4.0
these are the packages in my project
Check out the voice guide in the pins
How can I check if a stage channel is a stage channel?
Does anyone know what error code 403 with audio resource means? I looked at the discord dev portal and they said The Authorization token you passed did not have permission to the resource.
Is there a way to prevent this error?
nvm aparrantly this has to do with bot permissions
voice.channel.type

Hi, is there a way to have my bot undeafened when it is in the VC? If so, where would I find the resources for this? If not, no problem at all and I am just wondering since I haven't used DJS for a few versions.
Thanks in advance for any help you can provide!
I have been attempting to listen to a specific user, and then play that audio back through the bot, however this code simply does not work and I have no idea why: js client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`) let paChannel = client.guilds.cache.get("579616320488734740").channels.cache.find(channel => channel.name == "PA System") const connection = joinVoiceChannel({ channelId: paChannel.id, guildId: paChannel.guild.id, adapterCreator: paChannel.guild.voiceAdapterCreator, selfDeaf: false, selfMute: false }); var receiver = connection.receiver const userListeningStream = receiver.subscribe("472158867183108118", { end: { behavior: EndBehaviorType.AfterSilence, duration: 100, }, }); var writable = fs.createWriteStream('test.pcm'); userListeningStream.pipe(writable) userListeningStream.on("end", async () => { var readable = fs.createReadStream('test.pcm'); var resource = createAudioResource(readable, {inputType: "opus"}) var player = createAudioPlayer() connection.subscribe(player) player.play(resource, {seek:0, volume: 1}) }) })
It and listens fine, however when it comes time to play the source audio back, the bot stays green as though it's talking forever, and no audio comes out.
how to change volume of resource that is playing through an audio player?
Get connection from somewhere and then do this
connection.state.subscription.player.state.resource.volume.setVolume(0.1)
i figured it out in ts i had to do something like this
(this.audioPlayer.player.state as AudioPlayerPlayingState).resource
then only i got access to resource property
Yep for ts, you need to do that.
Why does N [Error]: aborted give this error?
ytdl-core issue
discordjs voice has nothing to do with it
Try using play-dl as it is a more stable package at the moment
how to fix AudioPlayer: aborted? My friend was using my music bot and apparently it crashed near the end of the 4:23 long song
hey! how can i subscribe to a whole channel's audio? like not just for a specific user?
You can't... all you can do is subscribe it to every user
can someone help me out? im trying to use the voiceStateUpdate event but it wont detect a leave? when i kick the bot out of the vc it still thinks that its in a channel???
if (oldState.id === client.user.id) {
console.log(oldState.channelId)
console.log(newState.channelId)
}
this is what gets logged
904411061879455819
904411061879455819
discord.js v (13.3.1)
you have GUILD_VOICE_STATES intent?
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| https://embed.rauf.wtf/?title=clapclap&color=2f3136&image=https://cdn.clapan.wtf/ry8.png&redirect=https://cdn.clapan.wtf/ry8.png
If you use newState.channel.id is it the same ?
yep same thing
it works good for users tho? just not the bot
Hi! I have a problem with Youtube Together, I use a "message.member.voice.channel" and it does not recognize whether I am in a voice or not. For him if I'm not starting the bot I would never be, and if I'm at the start, I would be forever
That's because you don't have the GUILD_VOICE_STATES intent. You need that for your client to receive voice state updates (I.e joining/leaving/changing channels).
Oh maybe ! I try this in 2-3 hours when i back :)
how can i get the channel when i have VoiceConnection ?
Hi anyone know how to play URL music link in discord.js? (I don't wan't package with youtube api)
<VoiceConnectio>.destroy()
getVoiceConnection(message.guild.id).destroy();
No, <VoiceConnection> in that instance must be an actual VoiceConnection object. You can store it from your joinVoiceChannel() function.
currently building an app that allows a user to mute or deafen all of the users in a voice channel- the size of those voice channels will regularly be 10+ users, which presents a problem- the route used to change a user's server-mute or server-deafen state is rate limited as 10-per-10 it looks like (i regularly get rateLimited client events sent as a limit of 10, with a timeout between 1000-9000ms)
is there any way to batch these commands to reduce the overall requests needed to achieve a "channel mute" or "channel deafen"? i could batch the commands myself, but it would still take a full 10+ seconds to mute any channel with 10-20 users
you have the wrong prism-media version
try to use these:
"node-crc": "^1.3.2"
"prism-media": "^2.0.0-alpha.0"
Hey, simple question hopefully, what event gets fired when a client gets moved from one voice channel to another in v13+?
Same as in v12. voiceStateUpdate
Ok so, I'm guessing to see if the client was moved or disconnect I need to compare the old new voice channels?
Yep
When disconnecting/joining a channel the state.channel will be null
Can anyone help me, the bot shows a green ring around it but no audio is heard
is there a guide for djs voice?
nvm found it
Hello, I am getting this error when i try to join a vc
hello! i'm using prism-media and the voice library together and the problem is that if a pipe the voice stream to the prism-media VolumeTransforer the volumeDecibels is always -6.020599913279624
how can i fix it?
Does anyone know why docker deployed bot disconnect as soon as it start playing music?
client.on('interactionCreate', async (interaction) => {
const { channel } = interaction;
if (interaction.commandName === 'play') {
await interaction.reply('play....');
const url = interaction.options.get('song').value;
let connection = await joinVoiceChannel({
channelId: '802231559175274502',
guildId: process.env.ZZ_GUILD,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const stream = ytdl(url, { filter: 'audioonly' });
const resource = createAudioResource(stream, {
inputType: StreamType.Arbitrary,
});
const player = createAudioPlayer();
player.play(resource);
connection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => connection.destroy());
}
});
Works when not deployed on docker (macOS)
how to disconnect someone ?
error: "newState.member.setChannel is not a function".
forgot voice
member.channel.estChannel ?
newState.member.voice
I'm trying to get the basic example to work but i get no sound, everything "seems" to work, no errors etc. https://github.com/discordjs/voice/tree/main/examples/basic
i also tried creating my own bot without success.
in both cases the bot joins, no errors, but no sounds
Core Dependencies
- @discordjs/voice: 0.7.4
- prism-media: 1.3.2
Opus Libraries
- @discordjs/opus: 0.5.3
- opusscript: 0.0.8
Encryption Libraries
- sodium: not found
- libsodium-wrappers: 0.7.9
- tweetnacl: 1.0.3
FFmpeg
- version: 4.4-essentials_build-www.gyan.dev
- libopus: yes
how can I leave a voice channel please?
destroy the connection
If you're allowing voice to send ws packets, destroying the connection should also send a corresponding voice state update to Discord, otherwise you have to send it yourself.
There should be methods to set the volume on the VolumeTransformer. Otherwise, VolumeTransformer.volume is writable and the change takes effect on the next chunk.
Well, i just want to know if someone speaks then how loud is the user. I wanted to do this with the decibel thing.
Wait what? How loud is the ClientUser or are you talking about receive?
For receive, you'd need to do processing yourself and analyze the incoming opus chunks to get the volume in DB. I don't think the voice lib handles that for you and if receive has a VolumeTransformer, that'll be for local transforming purposes only and shouldn't be used as a means of measurement unless altered
can someone help me please, i've been trying for 3 days now with 0 sounds
switch (command) {
case "startthesong": {
const channel = await message.guild.channels.cache.get(config.channel);
const player = createAudioPlayer();
const resource = createAudioResource("/home/container/song/song.mp3");
player.play(resource);
const connection = await joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
connection.subscribe(player);
message.channel.send("🎶 Playing music!");
break;
}
bot join voice and say "Playing music" but nothing happening
no sound?
So using VoiceReciever is like new VoiceReceiver(<voiceConnection>); and then run subscribe(<userID>); on the instance of VoiceReciever to receive opus packets as AudioRecieveStream of the subscribed user from discord??
And btw what is a ssrc map
@carmine timber dm me 1 min
How loud is the user who is speaking.
That's still a very ambiguous statement. I'd still just recommend reading what I posted right after
are any of you here getting node @discordjs/voice to work?
i saw some github issue where some guys didnt get sound either like me
Yeah, what issues are you running into?
I've tried to do a proof of concept but i get no sound and no errors, tried "everything" for multiple days
require('dotenv').config()
const path = require('path')
const {Client} = require('discord.js')
const {joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus} = require('@discordjs/voice')
const resource = createAudioResource('./website.mp3')
const client = new Client({intents: ['GUILDS', 'GUILD_MESSAGES']})
const player = createAudioPlayer()
client.on('ready', () => {
player.play(resource)
})
client.on('message', async message => {
if (message.content == 'play') {
if (!message.member.voice.channel) return message.reply('You must be in a voice channel')
if (message.guild.me.voice.channel) return message.reply("I'm already here")
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.member.voice.channel.guild.id,
adapterCreator: message.member.voice.channel.guild.voiceAdapterCreator,
})
connection.subscribe(player)
// connection.play(resource)
// connection.play(path.join(__dirname, 'website.mp3'))
}
})
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!')
})
player.on(AudioPlayerStatus.Idle, () => {
console.log('wat')
})
player.on('error', error => {
console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`)
})
client.login(process.env.DISCORD_TOKEN)
First thing I'm seeing is that you're missing the GUILD_VOICE_STATES intent. You need that to get voice state update which is necessary for joining channels and stuff.
Firstly, thank you so much for helping me
I'll try that now (however the bot can join currently)
omg it works ❤️
No problem. Also, it can sort of join. It will be in the voice chat, but it will be stuck in its signalling state which means it can't actually do anything.
Great :)
Thank you so much! Have a super great day hehe
You too
One more question, the docs say https://discord.js.org/#/docs/voice/stable/class/PlayerSubscription
new Voice.PlayerSubscription(connection, player)
That didn't work, but connection.subscribe(player) works
Whatsup with that?
has anyone been able to get discordjs/voice working with prism and ffmpeg?
const FFMPEG_ARGUMENTS = [
"-i", "./test.mp3",
"-analyzeduration", "0",
"-loglevel", "0",
"-acodec", "libopus",
"-f", "opus",
"-ar", "48000",
"-ac", "2"
];
serverQueue.resource = createAudioResource(new prism.FFmpeg({...FFMPEG_ARGUMENTS}), {inlineVolume: true});
player.play(serverQueue.resource);
ive tried this among many other solutions and i cant for the life of me get it working. i get an AbortError: The operation was aborted error which there also doesnt seem to be many docs for online. i'm just trying to play a url, like an internet radio. anyone know how?
That is the constructor for a player subscription. Generally try to avoid those if you can use methods to achieve the same thing.
Thank you
I'm developing this for a local online christmas radio station, it's all done for free etc so no worries. But if i released this exact bot to 10k ppl, what issues would i run into? :p
i would guess maybe 500 channels
.
I have no clue. I've only made small private bots. I think are some memory usage issues that may occur, but if so there's nothing you can do about that.
great, i'll try then and see how it goes.
I'm a little worried about connection.subscribe(player) can one channel subscribe multiple times and ddos it?
I can't find any if (!connection.isAlreadySubscribed()) { //subscribe }
maybe it handles that automatically
One Client can have one voice connection per guild and that connection is your <connection>
You can check if it already has a connection with trying getVoiceConnection(guildId)
Or you can check whether the connection already has a subscription with <connection>._state.subscription.player which would return the player if there was any
@loud ginkgo
Thank you! That worked nicely
I'm trying to figure out a way to resume playing after restarting the bot, any ideas?
I've tried a lot of client.on('messages like channelUpdate, channelCreate, webhookUpdate, etc')
I'd like some type of "reconnected" event
Anyone?
why do i get this error here's a clip (sorry for quality)
it joins then leaves
No just joinVoiceChannel and then just get opusStream by using receiver subscribe function.
https://github.com/discordjs/voice/releases/tag/v0.6.0
// A Readable object mode stream of Opus packets
// Will end when the voice connection is destroyed, or the user has not said anything for 100ms
const opusStream = voiceConnection.receiver.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
// -------------------------
// You can re-use the Opus stream, e.g. to play in another channel as an echo
const resource = createAudioResource(opusStream, { inputType: StreamType.Opus });
Do you have entersState function in your code ??
no i don't
should i show you my code?
Which error you want to resolve ?? Aborted OR IP discovery ??
yep show me
the first one
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return;
if (interaction.commandName === "play" || interaction.commandName === "soundcloud") {
await interaction.deferReply();
const query = interaction.options.get("query").value;
const searchResult = await player
.search(query, {
requestedBy: interaction.user,
searchEngine: interaction.commandName === "soundcloud" ? QueryType.SOUNDCLOUD_SEARCH : QueryType.AUTO
})
.catch(() => {});
if (!searchResult || !searchResult.tracks.length) return void interaction.followUp({ content: "No results were found!" });
const queue = await player.createQueue(interaction.guild, {
metadata: interaction.channel
});
try {
if (!queue.connection) await queue.connect(interaction.member.voice.channel);
} catch {
void player.deleteQueue(interaction.guildId);
return void interaction.followUp({ content: "Could not join your voice channel" });
}
await interaction.followUp({ content: `⏱ | Loading your ${searchResult.playlist ? "playlist" : "track"}...` });
searchResult.playlist ? queue.addTracks(searchResult.tracks) : queue.addTrack(searchResult.tracks[0]);
if (!queue.playing) await queue.play();```
so you need to remove this function from your code
What is player here ??
discord-player
That's where issue lies. Tell the developer not to use entersState in his code.
Instead try to create his own function.
oh-
so its the package?
Yep
what package would u recommend if i may ask?
If I am correct, discord-player is based on ytdl-core right ??
https://www.npmjs.com/package/discord-play
I recommend ^^
ohh okay thx for the help 
what's wrong with entersState?
Hello, I asked this question nearly a week ago, but no one could solve it and I still haven't, also I'm desperate, so I decided to ask one more time.
Here is the code I have copied from: https://www.npmjs.com/package/discordjs-ytdl
let stream = ytdl("https://www.youtube.com/watch?v=QnL5P0tFkwM", {
filter: "audioonly",
opusEncoded: false,
fmt: "mp3",
encoderArgs: ['-af', 'bass=g=10,dynaudnorm=f=200']
});
message.member.voice.channel.join()
.then(connection => {
let dispatcher = connection.play(stream, {
type: "unknown"
})
.on("finish", () => {
message.guild.me.voice.channel.leave();
})
});
On my local host ( computer ) it is working perfectly fine with those npm packages:
├── @discordjs/builders@0.5.0
├── @discordjs/opus@0.5.3
├── 14@3.1.6
├── canvas@2.8.0
├── discord.js-buttons@1.0.0
├── discord.js-commando@0.12.3
├── discord.js@12.5.3
├── discordjs-ytdl@2.2.0
├── express@4.17.1
├── ffmpeg-static@4.4.0
├── mognoose@1.0.3
├── mongodb@4.0.1
├── mongoose@5.13.4
├── node@16.6.1
└── openweather-apis@4.4.1
On my ssh client ( server ) I use the exact same code with those npm packages:
techbot@1.0.0 /root
├── @discordjs/builders@0.5.0
├── @discordjs/opus@0.5.3
├── 14@3.1.6
├── canvas@2.8.0
├── discord.js-buttons@1.0.0
├── discord.js-commando@0.12.3
├── discord.js@12.5.3
├── discordjs-ytdl@2.2.0
├── ffmpeg-static@4.4.0
├── mognoose@1.0.3
├── mongodb@4.0.1
├── mongoose@5.13.4
├── node@16.6.1
└── openweather-apis@4.4.1
but I get an error:
Error [VOICE_CONNECTION_TIMEOUT]: Connection not established within 15 seconds.
at VoiceConnection.authenticateFailed (/root/node_modules/discord.js/src/client/voice/VoiceConnection.js:303:26)
at /root/node_modules/discord.js/src/client/voice/VoiceConnection.js:324:61
at Timeout.<anonymous> (/root/node_modules/discord.js/src/client/BaseClient.js:83:7)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
[Symbol(code)]: 'VOICE_CONNECTION_TIMEOUT'
}
the bot is joining the channel, but not playing any music.
Could someone please try to help me out ?
This is v13 voice support not v12 voice support
Sorry, I didn't get that. ytld-core is supposed to work on v13 or it is on v12 and you help only v13 voice support ?
If so what do you use on v13 ?
ytdl-core works on v12 and v13
v12 is just not supported anymore
to update to v13 look at the guide
-> https://discordjs.guide/voice/
Ohhh alright tysm, but can I subscribe to multiple users at a time?
I did go to v13, but to join the channel I am using this:
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
but it is not even a promise and in ytld-core documentation there is nothing about v13 that I can see ?
Yes you can
So I can pass a array? <voiceConnection>.receiver.subscribe([userIds], ...)
No you can't, you need to subscribe individually. You will get separate opusStreams.
Hello, I have the current code:
const {
AudioPlayerStatus,
StreamType,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
} = require('@discordjs/voice');
// ..
if(!message.member.voice.channel) {return;}
console.log("asd");
let connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const stream = ytdl('https://www.youtube.com/watch?v=7jrZu0qb8PE&list=RD7jrZu0qb8PE&index=1', { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
const player = createAudioPlayer();
player.play(resource);
connection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => connection.destroy());
My bot is joining the channel, but not playing anything. Why is that ?
I have no idea what the problem may be
Do you have GUILD_VOICE_STATES intent?
I haven't. When I added them it worked out ! But it worked on my local host and not on my server ( ssh client )
On my ssh client I am getting this error:
/root/node_modules/prism-media/src/core/FFmpeg.js:143
throw new Error('FFmpeg/avconv not found!');
^
Error: FFmpeg/avconv not found!
I have those packages:
techbot@1.0.0 /root
├── @discordjs/builders@0.5.0
├── @discordjs/opus@0.5.3
├── @discordjs/voice@0.7.5
├── 14@3.1.6
├── canvas@2.8.0
├── discord.js-buttons@1.0.0
├── discord.js-commando@0.12.3
├── discord.js@13.3.1
├── discordjs-ytdl@2.2.0
├── ffmpeg-static@4.4.0
├── ffmpeg@0.0.4
├── libsodium-wrappers@0.7.9
├── mognoose@1.0.3
├── mongodb@4.0.1
├── mongoose@5.13.4
├── node@16.6.1
├── openweather-apis@4.4.1
└── ytdl-core-discord@1.3.1
install ffmpeg natively on your server with sudo apt install ffmpeg
Aight, give me a minute
I did install it and it is joining, but doesn't play anything. I do have GUILD_VOICE_STATES intent
Oh, I've just got something
Error: Cannot perform IP discovery - socket closed
at Socket.<anonymous> (/root/node_modules/@discordjs/voice/dist/index.js:1:6361)
Maybe you need to configure port forwarding
W-what 👀
( I am a begginer on topic servers )
Could you please describe that or give me a source ?
Is it possible to play same resource again when it ended? Kind of repeat mode
How to join stage channel?
Try tu use setInterval()
When a resource ends the player will enter its idle state. You can use <AudioPlayer>.on('idle', () => {}) to execute some code whenever a song ends. Use that to do repeat functions or continue to the next song in a queue for example.
is there a way to properly set a framesize when encoding using prism-media? it keeps segfaulting when changing the framesize/rate
Is there any alternatives to ytdl-core, i heard it's bugging out a lot
play-dl seems to be a good option as of now
okay thanks
how to make a bot leave a vc
Hi, so I use a M1 13' Macbook Pro but when I try installing I get this error
npm ERR! code 126
npm ERR! path /Users/kavishgulati/Desktop/GitHub/brainbot/node_modules/@discordjs/opus
npm ERR! command failed
npm ERR! command sh -c node-pre-gyp install --fallback-to-build
npm ERR! sh: /Users/kavishgulati/Desktop/GitHub/brainbot/node_modules/.bin/node-pre-gyp: Permission denied
npm ERR! A complete log of this run can be found in:
npm ERR! /var/root/.npm/_logs/2021-11-26T19_57_47_732Z-debug.log
sh-3.2# ```
I am running it in sudo and I have admin perms so I dont understand the issue. I was also told others using M1 Macs are experiencing this issue. If you have any solutions please let me know.
how could you get the duration left of an audio resource?
Hey mates,
I am currently want to work with discord voice and want to record the users audio in a VoiceChannel. How can I do that?
Thanks for your help 🙂
Oh alright thanks
But what is a ssrc map
Any examples or documentation on how can I record voice and process or use it for recognition?
Refer to the link above the message you just sent
when I try to npm install the example/recorder, I get following error
Try running npm config set msvs_version 2019 --global then install again
> receiver-bot@0.0.1 start
> npm run build && node -r tsconfig-paths/register dist/bot
> receiver-bot@0.0.1 build
> tsc
../../tsconfig.json:8:3 - error TS5023: Unknown compiler option 'exactOptionalPropertyTypes'.
8 "exactOptionalPropertyTypes": false,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../../tsconfig.json:15:3 - error TS5023: Unknown compiler option 'useUnknownInCatchVariables'.
15 "useUnknownInCatchVariables": true,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/createListeningStream.ts:2:1 - error TS1371: This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'.
2 import { User } from 'discord.js';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/deploy.ts:1:1 - error TS1371: This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'.
1 import { Guild } from 'discord.js';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/interactions.ts:69:2 - error TS6133: 'client' is declared but its value is never read.
69 client: Client,
~~~~~~
Found 5 errors.```
Check ur ts version?
4.5.2
Weird, exactOptionalPropertyTypes was added in 4.4
Do tsc --version
Yes it is showing Version 4.5.2
Try npx tsc --version
now its version 4.3.5
I have updated it, but now another error occurs at runtime
> receiver-bot@0.0.1 start
> npm run build && node -r tsconfig-paths/register dist/bot
> receiver-bot@0.0.1 build
> tsc
Ready!
C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\examples\recorder\dist\createListeningStream.js:19
const oggStream = new prism_media_1.default.opus.OggLogicalBitstream({
^
TypeError: Cannot read properties of undefined (reading 'opus')
at createListeningStream (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\examples\recorder\dist\createListeningStream.js:19:49)
at se.<anonymous> (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\examples\recorder\dist\interactions.js:30:67)
at se.emit (node:events:390:28)
at se.onPacket (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\dist\index.js:8:3788)
at q.onUdpMessage (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\dist\index.js:8:6020)
at X.emit (node:events:390:28)
at X.onMessage (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\dist\index.js:1:5591)
at Socket.<anonymous> (C:\Users\Dell\Desktop\Kaustubh\Testing2\voice\dist\index.js:1:5121)
at Socket.emit (node:events:390:28)
at UDP.onMessage [as onmessage] (node:dgram:931:8)```
This will not join or play any music
I keep getting an error that says cannot find module node:dgram
but when i installed it the error still shows
what node version are you using
14
voice requires node 16
@carmine timber you mentioned the other day that we shouldn't use entersState. Why is that?
is there a way to speed up/slow down or change the bass of audio
Pipe the audio through FFMPEG
can you link some code examples
GitHub is down, otherwise I would happily link you to one of my projects
This is the index signature for applying filters in my project.
Line 370 would be of interest of you for speeding up and slowing down.
https://github.com/AmandaDiscord/Volcano/blob/main/src/worker.ts#L357
This is where I apply those filters and play the track. (you need to restart the track and seek to the last position if you want to apply filters since ffmpeg doesn't allow dynamically adjusting args)
https://github.com/AmandaDiscord/Volcano/blob/main/src/worker.ts#L214
ye I'm not really sure how it works xd
thx for sharing tho, I'll try and see if you can make an audio equalizer with just the audio player or resource
Can someone help?
Did you installed dependencies in that folder ??
Because many people have suffered from this issue. Even hydrabolt was also confused about it. So I recommend to avoid it. You can create your own entersState function.
As far as I think, the issue lies when you use VoiceConnection Connecting state in entersState. So suppose you created a connection and the connection by the time [ you created entersState function ] have passed that event, so it won't emit that event. While entersState will be waiting for that event to emit.
b
Yes I did
how can i make a queue system for djs voice?
i have everything else but i need help with queue system
and skip system. please ping me if you can help
PING PLEASE
Thanks i will Test it
Hello! how do i check if a bot, that is into a channel, is playing audio or not?
check if player state is Status.Playing
How do i force audio player to Idle state while it is in Playing State?
<AudioPlayer>.stop(), this ends the currently playing resource which puts it in idle.
<AudioPlayer>.stop(true) force stop a player
hi is onFailureCallback working ?
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:407:19)
at TLSSocket.emit (node:events:406:35)
at node:net:672:12
at TCP.done (node:_tls_wrap:580:7) {
resource: j {
playStream: OggDemuxer {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_remainder: null,
_head: null,
_bitstream: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: [Function: bound onwrite]
},
edges: [ [Object], [Object] ],
metadata: null,
volume: undefined,
encoder: undefined,
audioPlayer: H {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_state: [Object],
subscribers: [Array],
behaviors: [Object],
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
},
playbackDuration: 149300,
started: true,
silencePaddingFrames: 10,
silenceRemaining: -1
}
}``` sometimes while playing something I get this error (always near the end), does anyone have any idea what could be causing this?
^^ ping me
You can use the connection.finish event.
But it's simpler to use a package like discord-player (https://discord-player.js.org/)
ye how can i set it up. like with a collection? its a tiny bot so ill use collection or maps. how can i do that?
ping me
Don't use connection.finish that is v12 and does not exist in since v13. A queue is easily achieved by just storing the AudioResources in an array and creating a listener on your AudioPlayer like so
<AudioPlayer>.on('idle', () => {
//Here you play the next song in the queue, the following code is a rough example
if(myQueue.length > 0) {
<AudioPlayer>.play(myQueue.shift())
}
})
The listener is called whenever a song (resource) ends so you just make it play the next song until your queue ends.
ohh i see. ill see if i can work this with a skip command. thanks so much. also how can i check if the queue is done?
Just check if it is empty like in my example. If it's not you play the next song, otherwise do nothing or notify the user that it is empty or whatever you want.
oh ok. thanks. i appreciate you
The <Array>.shift() method pops the first element out of the array and returns it so it will make the queue gradually become empty.
np
<AudioPlayer>.on('idle', () => {
let channel = interaction.channel
//Here you play the next song in the queue, the following code is a rough example
if(myQueue.length > 0) {
<AudioPlayer>.play(myQueue.shift())
} else {
channel.send("Queue Is Over")
}
})```
this works?
Yeah should I think, do make sure to insert an actual AudioPlayer object instead of the <AudioPlayer> placeholder of course though.
ye i know. also for skip i can just do <AudioPlayer>.play(myQueue.shift)?
If you have the above code in play you can use the <AudioPlayer>.stop() to skip a song. The stop() method will end the current song and your listener will play the next.
thanks!
how to see if the user is connected to a vc or not and to fetch the channel info if the user is connected
how do you pipe audio to ffmpeg so that you can add more audio settings
<member>.voice.channel returns the voice channel of the user (null if they're not in one)
oh i noticed this thanks for help btw
my bot wont play any audio
it joins correctly
--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.7.2
- prism-media: 1.3.2
Opus Libraries
- @discordjs/opus: 0.5.3
- opusscript: 0.0.8
Encryption Libraries
- sodium: 3.0.2
- libsodium-wrappers: not found
- tweetnacl: 1.0.3
FFmpeg
- version: 4.3.3-0+rpt1+deb11u1
- libopus: yes
--------------------------------------------------```
https://github.com/walksanatora/basic-bot-js/blob/nationStates/commands/audio.js
You are missing GUILD_VOICE_STATES intent.
const connection = await djsVoice.joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator,
});```err:
```log
Cannot read properties of undefined (reading 'status').```
pls help
Please send full error logs
[10:37:36:501]: ERROR Unhandled promise rejection: Cannot read properties of undefined (reading 'status').
TypeError: Cannot read properties of undefined (reading 'status')
at Object.sendPayload (C:\Users\Admin\Downloads\bot\node_modules\discord.js\src\structures\Guild.js:1320:26)
at Ie (C:\Users\Admin\Downloads\bot\node_modules\@discordjs\voice\dist\index.js:8:12615)
at Object.gt (C:\Users\Admin\Downloads\bot\node_modules\@discordjs\voice\dist\index.js:8:12763)
at Object.run (C:\Users\Admin\Downloads\bot\SlashCommands\Music\play.js:45:38)
at Client.<anonymous> (C:\Users\Admin\Downloads\bot\Events\client\interactionCreate.js:50:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)```
@carmine timber here
What is voiceChannel here ??
interaction.member.voice.channel
Can you show me what is in C:\Users\Admin\Downloads\bot\node_modules\@discordjs\voice\dist\index.js file at line 8 ??
thats the @discordjs/voice npm package
I know, just show me the codes
here
Debug your dependencies
I dint get that
create a new test.js file and add this code there.
const { generateDependencyReport } = require('@discordjs/voice');
console.log(generateDependencyReport());
and run it like node test.js and show me the console log
--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.7.4
- prism-media: 1.3.2
Opus Libraries
- @discordjs/opus: not found
- opusscript: 0.0.8
Encryption Libraries
- sodium: not found
- libsodium-wrappers: not found
- tweetnacl: 0.14.5
FFmpeg
- version: 4.4-essentials_build-www.gyan.dev
- libopus: yes
--------------------------------------------------``` @carmine timber
I installed opus now
@carmine timber pls help
Can you install libsodium-wrappers ??
and try your code again.
<@&839912195994812420> ^
What happened ??
What did I do wrong ?
nothing you did. A scam
Ok
how?
@carmine timber i did npm i libsodium-wrappers and its still the same
Show me your code
here
@carmine timber
Can you downgrade your discordjs voice to 0.6.0 ?? by npm i @discordjs/voice@0.6.0 ??
same thing
You are playing the song in wrong way.
?
then tell how.
Connecting to Voice Channel : https://discordjs.guide/voice/voice-connections.html#creation
Playing a Song : https://discordjs.guide/voice/audio-player.html#playing-audio
thats what i was reading
could you tell me how to do it then?
Is there anything like connection.play(stream, {seek: 0, volume: 1}); this ??
according to err this is the part where I have gone wrong
const connection = await djsVoice.joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator,
});```
How to reduce bot voice crackling?
Just make a separate voice module EZ
Is there any way to seek around a track while it's playing?
You need to create a new Resource and use ffmpeg for seeking purposes
So i should pipe the audio stream through ffmpeg and create a resource based on that?
you need to create a separate resource with ffmpeg and force play that on current AudioPlayer.
That doesn't seem very practical
Why when bot playing YT live stream, it plays only 3-4 secs, then disables?
you can't seek on current resource.
Any Errors ??
Which YT module ??
Since I have installed @discordjs/voice I get this error.
The script i'm using here is still v12, but we plan to update to v13 soon
Can someone help me with this: https://srcb.in/iciKQD1nw9
I got told to go here... Because it should be an voice problem instead... Or something...
client.voice.createBroadcast(); what should I use in the new version ? (the first code is the old version one)
how can I add audio filters to an audio resource
such as volume changing and bass boosting
Q: How can I join a voice channel? (I need to join a member in a vc)
Did you ever figure this one out? I've also been having issues with passing readable opus stream. Just idles out immediately
don't pass the FFMPEG instance directly to createAudioResource. Pipe the stream into the FFMPEG.process.stdin and pass FFMPEG.process.stdout to the voice lib. If you have errors with that, then you should pipe the stdout to a stream.Passthrough and then pass the Passthrough to createAudioResource
https://github.com/AmandaDiscord/Volcano/blob/7e8a755e17dd422020dd8512213ad666d6fd33eb/src/worker.ts#L206
@quartz cypress if you're using ffmpeg as well, you might be interested in this
Thanks will take a look! What I'm currently doing is handing off a passthrough to createAudioResource as an argument. Strange it has to be done this way
awesome thank you! ill check it out
The lib will sometimes read the stream to the end and cause it to fire the end event
The Duplex ChildProcess class the prism FFMPEG class extends is really jank as well. It's a lot easier to just use the raw child_process in the class
yes i know what that means
It is not a voice issue, you can create a issue at https://github.com/discordjs/opus/issues
I had no problems in v12 with it. Unless it's the new voice library that tends to do that. Also no luck with using child process unfortunately
Just click on the Voice Channel name and you will join that voice channel.
Volume changing is a part of discordjs voice module.
Just set inlineVolume to true while creating audio Resource and to change volume at any point, do like this
<AudioResource>.volume.setVolume(0.1) Sets volume to 10%
voice is somewhat of a reimplementation on the back end, but is updated for new node features and has a different interface and feature set to be modular considering there aren't any other major modular voice libs for node if any at all.
i started developing my bot on windows and @discordjs/opus crapped out and wouldnt install so i was using opusscript. now i'm running it on proper bot hosting (linux) and ive just switched to @discordjs/opus and uh it just started working lmao.
pls help err
pls
const voiceChannel = interaction.member.voice.channel;
const connection = await djsVoice.joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator,
});```code....
ded
play.js line 45?
45?
ok one sec
44 | const stream = ytdl(song, {filter: 'audioonly'});
45 | const resource = createAudioResource(stream)
@vivid cedar
or 37
const connection = await djsVoice.joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator,
});```
o
Cuz like , it says 45:37
ok lol
45 is const resource = createAudioResource(stream)
const stream = ytdl(song, {filter: 'audioonly'});
@raw ferry log your stream object and show output plz.
wait
that was old this is the err after I editted the file
this is the line 50
@rugged sky @vivid cedar
Like touche said , log your steam object. console.log(stream)
i cant do that fr sm reasn..
the err is before that itself and it returns.
Alright, can you send the entire play.js code?
@rugged sky here
ping on reply
is audio seek a feature yet?
@rugged skypls help
I'm in class, I will look at it later.
not directly, but indirectly yes.
Send me your index.js file.
is there any documentation you can link?
I don't have a documentation but a package developer have given some codes.
why?
You are overwriting some methods of guild.
require('dotenv').config()
const { Collection, Client } = require('discord.js');
const config = require('./config.js');
const fs = require('fs');
const client = new Client({
intents: [
"GUILDS",
"GUILD_MEMBERS",
"GUILD_BANS",
"GUILD_INTEGRATIONS",
"GUILD_WEBHOOKS",
"GUILD_INVITES",
"GUILD_VOICE_STATES",
"GUILD_PRESENCES",
"GUILD_MESSAGES",
"GUILD_MESSAGE_REACTIONS",
"GUILD_MESSAGE_TYPING",
"DIRECT_MESSAGES",
"DIRECT_MESSAGE_REACTIONS",
"DIRECT_MESSAGE_TYPING",
],
partials: [
'MESSAGE',
'CHANNEL',
'REACTION',
],
});
const activehandlers = [
"Command",
"Event",
"Slash",
"SlashCommandList",
"EventList",
"CommandList",
];
module.exports = client;
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./Commands/");
client.cooldowns = new Collection();
client.logger = require('./Utils/Logger');
client.emoji = require('./JSON/emoji.json');
client.config = require('./config.js');
client.delay = ms => new Promise(res => setTimeout(res, ms));
client.embedCollection = new Collection();
client.slashCommands = new Collection();
activehandlers.forEach(handler => {
const exp = require(`./Structures/${handler}`);
exp(client);
}
);
process.on('unhandledRejection', err => {
client.logger.error(`Unhandled promise rejection: ${err.message}.`);
console.log(err);
}
);
client.login(process.env.token).catch(e => client.logger.error(e.message));```
Have you touched with shard property in guild Class anywhere ??
?
Looking at discord.js codes, I found out that this.shard == undefined as in your case.
what is shard?
how do i fix it?
@carmine timber
done?
@discordjs/opus has a memory leak in it when encoding opus packets. You should use opusscript regardless
play-opus is good alternative to @discordjs/opus
When did this become a thing? 👀
Yep it is, I am currently working on play-audio alternative to prism-media [ supporting play-opus and opusscript ]
Documentation is still incomplete though
the voice lib would have to have a peer dep on it though.
Is play-opus compatible with @discordjs/opus' API or are there breaking differences to where people would have to wait to use it
Same like @discordjs/opus but some changes in code like memory issue solved.
Based on same NAPI technology.

guess I can always define "@discordjs/opus": "github:play-dl/play-opus"
Yep you can but prism-media will not pickup that I think
Oh yeah right
OpusEncoder and OpusDecoder are done in play-audio. You can use those.
I don't have any encoding needs currently since I just encode through ffmpeg and have the voice lib determine when to encode. Doing that manually for the time being wouldn't be worth, so I'd wait
Yup right choice
Can't figure out what's wrong. Only thing I'd recommend is cleaning up your play.js code since right now you're creating a connection and a player two or three separate times based on conditions. That will probably not cause this error, but it's bad practise either way.
Hey it looks like some of the docs are missing. How would I go about setting a callback for when the file is finished playing?
So how can I check if a player is in a voice chat I know I can do it with a VoiceState but I have no idea how to use it. If you have a code exemple that would be great!
Guys I have a problem, everytime I try to connect with a another bot to same server it disconnects the first bot from its channel and connects it to channel where the second bot was supposed to be, any ideas why ?
(both bots are running at the same node.js process)
Do you meen, how to detect bot leaving channel ?
this has got to be the most useless error ive ever seen
@stuck spindle Are you keeping 2 separate client instances
you'll have to have 2 different discord.js imports if im correct
Show server.js line 121
Yea, now voice gets minified when compiled. Not a big fan of it tbh
I could be feeding in bad data, but idfk
Line 121: const connection = await connectToChannel(channel)
connectToChannel: (I just ripped the basic one and un-typed it)
async function connectToChannel(channel) {
const connection = joinVoiceChannel({ // line 149
channelId: channel.id,
guildId: channel.guild.id,
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
return connection;
} catch (error) {
connection.destroy();
throw error;
}
}```
@icy maple
You forgot to provide the <Guild>.voiceCreatorAdapter
I couldn't find any docs on that so i'm in the dark as to what it does or how it works
There is a guide in the pins
It covers voice connections, audio players, and audio resources
thank you
all thats completely blank in the docs
this is a lot compared to v11
That’s why voice is its own module
And only released in a major version change
so can createAudioResource take file paths?
Yes
Do i need the file:// prefix?
No
cool. Thank you!
The guide uses path.join to pass an absolute path using a relative path
I take it back about v13, im actually closer to making a project that ive tried and failed at before, and ive almost got it working now
how do you set volume of the dispatcher in v13?
.setVolumeLogarithmic() used to use this but no longer supported
ok
dose anyone know why I’m getting this error?
play-dl
No check if a user is in a voice Chanel or not
your ip maybe banned or temporary rate limit
429 is your IP is temporarily banned
Bans on YouTube usually last from 1 day to 1 week
No it is not a temporary ban.
The robot verification screen gives 429 status Code. It means that YouTube has identified some unusual traffic from that IP.
well where is problem?
+- 3 week ago it worked fined today it say i need opusscript so installed it and this happend
This is ytdl-core package issue.
so?
Change your package. EZ
to?
play-dl
what
and i have this js stream = await ytdl(LIVE); and this js stream = await ytdl(LIVE, { highWaterMark: 100 << 150 }); just change to js stream = await playdl(LIVE); and this to js stream = await playdl(LIVE, { highWaterMark: 100 << 150 }); ? or to play-dl ?
No play-dl is a separate package, you need to go through its docs to find out the required function.
And why I’ve got banned 
@rose helm
too many requests simply
Where can i read more about this
theres nothing to read more about it
youtube has simply blocked your ip address from sending requests
it usually goes away in a few hours or days
Ok ty
Hello guys, im trying to use an express.js app as a bridge between my discord.js bot and youtube (ytdl-core). I managed to proxy youtube videos from ytdl to discord, querying ytdl in the express.js app and returning the stream piped to the response. However, Im struggling trying to do the same with youtube live videos (hls), what should I return? I've seen people return hls videos with an html view and hls.js, would that work? what glue code would i need to at to the discord.js?
I prefer you to switch to dash manifest rather than hls. HLS requires 2 requests to get data while DASH requires only 1 request to get audio url data.
You can create a class which will read dash file and get Live Stream data from those urls [ contained in dash file ] and just pass it to end user.
I know it is quite hard to implement. This is the only method
Does youtube support that protocol?
Yup it does.
And I would need to convert it to opus for discord.js, right?