#archive-voice
30636 messages · Page 25 of 31
Is there a way for me to check what's currently playing on an audio player?
Or do I have to keep track of that manually?
Already but nothing happen
So I should install @discordjs/voice?
This is my code, how can I make my bot leave the channel after it's done speaking?
const call = args.join(" ");
if (!call)
return message.reply(
`Emergency Services was not contacted as you did not mention a reason for them to come.`
);
const stream = TTS.getVoiceStream(call);
const audioResource = createAudioResource(stream, {
inputType: StreamType.Arbitrary,
inlineVolume: true,
});
if (
!voiceConnection ||
voiceConnection?.status === VoiceConnectionStatus.Disconnected
) {
voiceConnection = joinVoiceChannel({
channelId: "927568962139590677",
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator,
});
voiceConnection = await entersState(
voiceConnection,
VoiceConnectionStatus.Connecting,
5_000
);
}
if (voiceConnection.status === VoiceConnectionStatus.Connected) {
voiceConnection.subscribe(audioPlayer);
audioPlayer.play(audioResource);
message.reply(`Contacting Emergency Services\n> ${call}`)
}
I don't want to record it, i want to hear what someone is saying and check if someone said: "play" or "stop" or "skip" and etc..
Somebody experienced that it is not possible to play something after some time when ytdl was used?
const stream = ytdl(url, {filter: 'audioonly'});
resource = createAudioResource(stream, {inlineVolume: true, inputType: StreamType.OggOpus});
Switch to play-dl
and youtube-dl does not have any explanation how to read as stream or it is not supported...
Neither ytdl nor play-dl is working.
- play something via
ytdlorplay-dl - after that play a file
- player is stuck in
buffering
Note: I'm re-using the AudioPlayer instance
idk if just discord.js is a huge mess...
if I provide the file via createStream instead of just the path, it is not stuck in buffering
Hey, does anyone know how to choose what client you want to connect?
?
Is there a way of having silence and sometimes add a Sound into that so the bot starts with the playing and then starts Listening so am able to add a Sound from a mp3 file into that silence so the Sound gets played insted of trying so send Sound after i started listening
`
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
description: 'Joins and play a youtube video',
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You need to join a voice channel to use this command dumbass.');
const permissions = voiceChannel.permissionsFor(message.client.user);
if(!permissions.has('CONNECT')) return message.channel.send(' You lack the required perms, peasant.');
if(!permissions.has('SPEAK')) return message.channel.send(' You lack the required perms, peasant.');
if (!args.length) return message.channel.send('You must add a link or a keyword, stupid.');
const connection = await voiceChannel.join();
`
error says: voiceChannel.join(); is not a function
Guide suggestion for @blissful hearth:
discordjs.guide results:
• Library: Voice Connections
• Library: Cheat sheet
Can anyone help?
I made a music bot which works with play-dl it works but when adding another song to my queue the music stops for a short time and I dont know how to solve this. This is the code where I add a song to the queue:
var song;
if(!message.content.startsWith("https")){
const {videos} = await yts(message.content);
if (!videos.length) return message.reply("No songs were found!");
song = {
title: videos[0].title,
stream: await (await playdl.stream(videos[0].url)).stream,
url: videos[0].url
};
}else if(playdl.yt_validate(message.content) === "video"){
const vid = await playdl.video_info(message.content)
song = {
title: vid.video_details.title,
stream: await playdl.stream_from_info(vid),
url: message.content
};
}else{
message.reply("URL isn't valid").then(msg => setTimeout(() => {msg.delete()}, 10000));
return;
}
setTimeout(() => {message.delete()}, 4000);
message.reply("Song was added! "+song.url).then(msg => setTimeout(() => {msg.delete()}, 10000));
if(musicqueue.length == 0){
playmusic(song.stream);
}
musicqueue.push(song);
updateQueue(message);
Just a quick question, is it possible to get access to voice-channels webcam feeds?
No with this library if with any at all, you can know if people have the webcam on though https://discord.js.org/#/docs/discord.js/stable/class/VoiceState?scrollTo=selfVideo
it's a bad idea to store the stream when adding a music to the queue, you should only get the stream when you have to play it...
Not via the official discord API, its only possible by creating a bot that uses the web, however this is against ToS.
Anyone know a package that counts time on the Voice Channel?
and displays the top voice?
time on the VoiceChannel can easily be done by just storing Date.now() somewhere when you join the voice channel.
As for "displays the top voice"; You're kinda being ambiguous here
GuildMemberSpeaking
It still works ?
It’s not on the client anymore
what should i use instead?
You would have to make use of the VoiceReceiver from the voice package
Tho, I would just remove it if it’s a useless feature
but i use v12
Then it should still work with the same restrictions
Documentation suggestion from @storm storm:
VoiceState
Represents the voice state for a Guild Member.
WARN Issues with peer dependencies found
.
└─┬ @discordjs/voice
└─┬ prism-media
└── ✕ unmet peer @discordjs/opus@^0.5.0: found 0.7.0
Shall I use @discordjs/opus@0.5.3 (auto downloaded as dependency) or 0.7.0 (from pnpm add) then?
install the latest
npm i @discordjs/opus@latest
yeah, so 0.7.0, just as I did
0.7.0 yes
gotta deal with annoying WARN then, thanks
This is correct if am not wrong
const connection = voice.joinVoiceChannel({
guildId: interaction.guild.id,
channelId: interaction.guild.members.cache.get(interaction.user.id).voice.channel.id,
adapterCreator: interaction.guild.voiceAdapterCreator
})
const player = voice.createAudioPlayer()
const res = voice.createAudioResource(stations[num - 1].url)
player.play(res)
connection.subscribe(player)
but it doesnt play anything
can anyone reply?
You can simplify this interaction.guild.members.cache.get(interaction.user.id).voice.channel.id, to this interaction.member.voice.channel.id,, but what is wrong about the code is the createAudioResource() function does not take a URL as input. It only takes either a String in the form of a file path to an audio file or a readable stream.
so its not possible to play audio from url?
Nope
You can use other libraries to get a readable stream from a url. Often ytdl-core or play-dl are used to get a stream of a youtube video from the url for example. I'm sure there's a package that works for you.
okay
is there any problem with this code ? https://sourceb.in/BtyPqB84zt
because for example sometimes connect to wrong voice
or
im not mute but send me mute err
or
im connect to voice but told me that you are not in any voice
Do you have the GUILD_VOICE_STATES intent?
oh
nope
XD
how can i check that bot is talking or no ?
i mean when someone play voice 1 and another one play voice 2 after that bot tell him that i am playing voice 1 and i cant play your voice rn
still same !
You can check the AudioPlayer of that bot's status. If it is playing, the status will be 'playing'.
From the code you sent I don't see anything that would cause any of the errors you described.
no err 0,0
oh
if (voiceDiscord.AudioPlayerStatus.Playing) return interaction.editReply({ content: `I Cant Play your voice i am playing something else right now`, ephemeral: true })
This doesn't work. You're checking if the Playing status exists in the package, which it of course does. You should check the status of your own player. Let's assume you called it player. It would be something like this: if(player.state.status === 'playing') {}.
ok got it
Hello, when the bot stop playing the music when he is alone on the channel for a long time ?
When I play music with play-dl and than play music via mp3 streams no sound comes up does anyone know whats the problem?
How can i check, when an audio / song finish?
Hi guys!
How could I increase performance?
I have a working music bot with queue system using play-dl. The problem is the audio is very laggy and it's crackling sometimes. Even if I type a new song to play and press enter the playing stops for about 1 sec.
My internet connection is good, 150/50 Mbps, so I don't think that would be an issue.
How do I check if my bot is in a voice channel?
EU Central
Like you check if a member is in a voicechannel with <member>.voice.channel what do I need to check if the bot is in a voice channel?
why? should I host it on a hosting service?
maybe ur queue system takes power? idk
I have a bot that is trying to join 800ish voice channels on different servers and it is unable to establish connection on any of them. I have it in multiple shard but it sill cant seem to handle that. Is this just something beyond discord js capabilities?
I don't know. CPU usage didn't rise much
What about free hosting services likes heroku glitch or repl.it? I saw some people telling that heroku is not the best...
well, i have a music bot that uses heroku, it works fine
i created my own queue system so that it optimize the computing power
My bot is only for one server
Okay, then I'll try out some hosting. I hope it'll be better
do u use github?
I don't have one
what i do is i use github, edit on my local machine, then push to github then my bot updates on heroku
that's quite handy.
I am trying to detect if a specific user is speaking.... I am newer to coding but have been scouring the docs and cant understand how to use it appropriately I would assume I can use Voice.SpeakingMap somehow since it has a users property on it but cant seem to even get it working in my code. Anyone have any ideas on speakingmap?
Okay, so the lagging problem looks like fixed now. I'm hosting on repl.it.
But the 1 sec stopping when new song is added is still an issue. The music stops, and continues but it speeds up a little bit and then goes back to normal speed. Weird..
I have the same problem, do you have an fix already?
hey im still confused with this package (even after the examples) 
Ask away
is the packages below required to be downloaded?
(if not what should i download here)
One from each section
Top is the recommended one (usually gives best performance, mainly for production)
can this module play music?
(also how do i setup this package)
so lets say i have an mp3 file how do i join a vc and play that file 🤔
Continue reading the guide. It’s covered in the Audio Resources section
Yes, that’s the main function of this module
alright 
oh cool
how do I create an AudioResource with ytdl?
I am new to discord.js/voice
Using YTLD-core returns a readable stream from a URL. The createAudioResource() method takes a readable as parameter. Just shove the return value of ytdl() into the createAudioResource() and you're done.
tysm
how do I change the volume of an existing track that playing?
if i used player.play(resource)
Make sure inline volume is enabled on your resource and use setVolume().
oh got it thanks
Is there any way to check if a song/audiofile has ended?
In V12 you had something like dispatcher.once('finish', ()) But how do you do this in V13?
omg thank you, I feel stupid 😂
Hey so I am wondering about the memory usage of my bot (I think I have a leak somewhere, but I can't find it)
I have one of those usual yt music bots and run it via pm2.
If repeatedly tell my bot to play something and disconnect over and over again, after a while it uses near to 200mb of RAM which seems kinda out of order to me. (It uses around 60mb after startup)
This leak only appears to happen for the voice stuff, as my image command (the usual "enter tag", fetch images from api, post) works just fine and the memory usage returns to around 60mb.
Has someone got an idea maybe? (should I send the code I use for the playback?)
(Discord won't let me post it here)
So here is the code I use for starting the playback:
https://pastebin.com/ANFJ6JXE
And this is the code I use for disconnecting:
export const disconnect = async function disconnect(guildId) {
return cleanUp(guildId);
}
async function cleanUp(guildId) {
const connection = getVoiceConnection(guildId);
if (connection) {
connection.subscribtion.unsubscribe(player);
connection.subscribtion = null;
connection.destroy();
}
if (queue) queue = null;
if (player) {
const ret = player.stop();
player = null;
return ret;
}
return false;
}
Unfortunately, no. :/
When someone does answer, feel free to ping me.
Thx
Encountered error on command "play" at path "G:\New folder (4)\namemc-namechecker\bot\commands\play.js" TypeError: Cannot read properties of undefined (reading 'once')
at H.play (G:\New folder (4)\namemc-namechecker\node_modules\.pnpm\@discordjs+voice@0.7.5_7dc12e6632e2c96122987847b0dba7c5\node_modules\@discordjs\voice\dist\index.js:8:430)
``` why is this happening?
Hi. I'm attempting to copy the code in this example to get familiar with the new discordjs voice https://github.com/discordjs/voice/tree/main/examples/recorder
idk why I'm getting these error messages, when I have the packages installed
The packages are installed, but the properties of opus you're reading don't exist
hello, im trying to kick my bot if no one is in channel for x seconds. Im using .leave but i get typeerror .leave is not a function. What should i use instead of leave?
<connection>.destroy()
Like this?
client.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.channelID !== oldState.guild.me.voice.channelID || newState.channel)
return;
if (!oldState.channel.members.size - 1)
setTimeout(() => {
if (!oldState.channel.members.size - 1)
oldState.channel.destroy(); // leave
}, 5000); // 300000
});
No
You need the voice connection
Also, that if statement is faulty due to operator precedence
Use getVoiceConnection(guildId) to get the current voice connection
Ok now i do like this and it doesnt crash but bot doesnt leave the channel after 5000 ms
client.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.channelID !== oldState.guild.me.voice.channelID || newState.channel)
return;
if (!oldState.channel.members.size - 1)
setTimeout(() => {
if (!oldState.channel.members.size - 1) {
//oldState.channel.destroy(); // leave
var voiceConn = getVoiceConnection(oldState.guild.me.voice.channelID);
if (voiceConn) {
voiceConn.destroy();
}
}
}, 5000); // 300000
});
what does it mean?
The expected type comes from property 'adapterCreator' which is declared here on type 'JoinVoiceChannelOptions & CreateVoiceConnectionOptions'
let queue = client.queue.get(interaction.guild?.id!)
let voice_channel = member.voice.channel;
const connection = joinVoiceChannel({
channelId: voice_channel!.id,
guildId: interaction.guild!.id,
adapterCreator: interaction.guild!.voiceAdapterCreator,
});
``` this is the code
nvm
How can i receive voice?
is there a way to change the volume level of a playing resource?
anyone know how to play from soundcloud or spotify?
search it up on youtube or google first
Hi, question, I have a music bot that supports both youtube and file URLs my problem is, after playing a youtube video no files will play only other youtube videos, any help is appreciated
(Ping reply please)
I’m using one resource URL to play audio. Is there a way to improve the quality and functionality to be flawless? Like should I make a new resource every time when a user types a command for bot to join?
Can you please provide a code
i have noticed that my bot, which uses slightly modificated version of MusicSubscriptions in the examples/music-bot, doesnt clear these two handles everytime i use function stop() any ideas why its doing this note: it does properly dispose all handles when music is ended properly without stoping
What am i doing wrong 😦
Is there a way to preload videos for djs-voice and ytdl-core (I am calling the play stuff in a timeout function)?
apologies for the late reply
if(this.playing.has(guild.id))return;
const musicData = await this.fetchMusicData(guild);
if(!musicData) return;
try {
this.playing.add(guild.id);
var player = music.createAudioPlayer();
var connection = music.joinVoiceChannel({
channelId: VC.id,
guildId: VC.guild.id,
adapterCreator: VC.guild.voiceAdapterCreator,
})
await music.entersState(connection, "ready", 30e3);
if(!connection) return;
connection.subscribe(player);
var resource = music.createAudioResource(musicData.queue[0].URL); // <- string for files and whatever ytdl produces for yt
player.play(resource);
player.on(music.AudioPlayerStatus.Idle, async () => {
if(!musicData.queue[1]) {
musicData.queue.shift();
this.playing.delete(guild.id);
connection.destroy();
return;
} else {
musicData.queue.shift();
this.playing.delete(guild.id);
await functions.playMusic(guild, VC, functions).catch(() => {null;});
}
})
} catch(e) {
console.log(e);
this.playing.delete(guild.id);
}```
You have to use a separate package that retrieves a stream from a yt url
Would recommend using play-dl
alright thanks
wait, I have that, ytdl, playing the yt video works fine but after the video ends no mp3 files will play
before playing a video, no problems but after the queue won't play any mp3 files
Then it’s prob smth wrong with the functions.playMusic function
everything works fine up until the part the audio should play so somehow the stream ytdl provides screws up something
also the code should be this.playMusic(), just haven't redone my old code yet
ytdl only takes yt urls, not file paths
ik
my problem is after a youtube video completes, the format YTDL provides seems to ruin something and nothing except other youtube videos converted through ytdl will play
I am trying to see if anyone knows what it's messing up with their experience
That seems far-fetched
Are you getting an error?
From the code you shown, it doesn’t seem like ur handling yt urls differently from file paths
I am assuming that music is just the voice package, not a special object with the same exports as the voice package. Especially since you have a separate functions variable
I handle fetching everything in my designated play commands and push them to the queue, for ?play-yt <youtube video> it pushes the YTDL result and for ?play-file if pushes the file URL (from a Discord attachment) I simply am trying to figure out what the ytdl stream is breaking which causes .mp3 (via the Discord link) files to no longer play after a youtube video finishes
music is my definition of discordjs/voice
It’s being added to the same queue
yes
So the functions.playMusic function must be able to handle both types of urls
everything works until a youtube video plays and then the queue stops and won't play anymore .mp3s
Where are you adding to queue actually?
for play-file I add the file attachment URL https://discord.com/attachment/whatever and for play-yt it is whatever YTDL's output is
ytdl puts out some sort of stream
Where are you adding the song to queue?
I'll fetch an example
@icy maple
and for pushing .mp3s, we just push the Discord attachment URL
That doesn’t rly answer my question
I’m asking where are you adding the song to queue? As in show the line(s) in the code that add the song to the queue
//in my exports
//...
queue: {};
//...
//in my add song files
//...
//after fetching the queue for the quild
queue.queue.push({name: "song", tags: [], URL: <the ytdl result or attachment URL>, source: `${interaction.member.user.tag}`})
//...
really new to voice, forgive me if i am being blind,
when someone joins the voice channel, make a new channel is my intention, but when they leave the voice channel it makes another channel. is there a way to determine when someone joins / leaves?
client.on('voiceStateUpdate', async (oldState, newState) => {
const primarychannel = newState.channelId;
const newID = newState.id;
const oldID = oldState.id;
console.log(`old ${oldID}`);
console.log(`new ${newID}`);
newState.guild.channels.create(`temporary`, {
type: 'GUILD_VOICE',
position: 256,
})
});
is there a property that can help me count the amount of users in the voicestate?
figured it out
nevermind
I'm trying to find out when a user is talking. I can do it very well in v12 with this code
connection.on('speaking', async (user, speaking) => {
if (speaking.has('SPEAKING')) {
console.log(`${user.username} Speaking !`);
}
})
but i tried in v13 it doesn't work, i tried to explore files such as index.d.ts in v12 and in v13 i noticed that the function didn't exist anymore, did v13 bring an alternative to access the audio of a user?
AbortError: The operation was aborted why does this happen?
How to avoid getting rate limited by Miniget!
Please help me.
wanna help ?
Yes please
come in dm bro
Sure
ok
410 isn't for only age restricted videos?
can anyone help 😩 2 left open Sockets really mess my bot
if I want my bot to join a voice channel when someone joins a voice channel using voiceStateUpdate (unless there's already a user in said channel) how to I check to make sure the bot isn't already in a channel? sorry if this is a dumb question
kk
nvm
is it possible for an existing bot to play music? because I just want to have my existing bot to join and play a specific playlist
I was able to have it automatically join but it doesn't play music
or have it play music I have downloaded on my pc
why isnt my bot playing attachments? it was working before when .join() was still a function```js
const stream=msg.attachments.first().proxyURL
const resource=createAudioResource(stream,{inlineVolume: true})
resource.volume.setVolume(text.substring(5, text.length))
player.play(resource)
all code pls
got eny errors?
no errors
I cant know what is your player....defined as
assignAudioConnection(msg.guild.id,voice.channelId,msg.guild.voiceAdapterCreator).then(connect => {
const player=createAudioPlayer()
connect.subscribe(player)
just show all code in the file with sourcebin
why
just show bruhhhhhh, how I know your everything defined
my codes 470 lines
...
code not code line bruhhhhh
msg is the guildmember message
const {joinVoiceChannel, getVoiceConnection, createAudioPlayer, createAudioResource}=require("@discordjs/voice")
its working for ytdl-core but not attachments
did you join the channel first?
yes
I cant really help you in djs voice since I dont work on it
How to get the event when a user speaks from AudioReceiveStream of receiver.subscribe(user.id) ?
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false,
});
const receiver = connection.receiver;
var capture = receiver.subscribe(message.author.id);
capture.on('data', async (user) =>
{
await console.log(`${user} a fini de parler`);
});
I have tried every type of event possible and never get one
does someone know whats wrong with my code?
.. Line 18 you're missing a colon after description
Hi, I'm trying to install @discordjs/opus but I always get that error:
npm ERR! code 126
npm ERR! path /home/musicbot/node_modules/@discordjs/opus
npm ERR! command failed
npm ERR! command sh -c node-pre-gyp install --fallback-to-build
npm ERR! sh: 1: node-pre-gyp: Permission denied
npm ERR! A complete log of this run can be found in: /path/to/logfile.log
I'm using Ubuntu server 64 bit on my raspberry pi. Running npm install @discordjs/opus as root throws the same error.
Edit: I tried nodejs 16 and 17 but none of them works.
what about other packages?
is it just me or voice channel connection API is broken again
Hey there, I'm trying to seek around in a resource, but I can't seem to figure out how. While searching, I found that discord.js had this feature in v12 (before @discordjs/voice).
https://discord.js.org/#/docs/main/v12/class/VoiceConnection?scrollTo=play
https://discord.js.org/#/docs/main/v12/typedef/StreamOptions
Is this functionality still retained in @discordjs/voice? If so, how can I use it?
does anyone know whats wrong with this?
Not djs voice related
but I will tell you that string.setDescription is not a function
Is it possible to do something after a song is playing for example 30 seconds?
Ah, i found a way!
What is the best way to have the bot join a specific channel in every server it's in?
Like if the voice channel name is
24/7 radio
it will join and start playing from a specific channel
Is there an event dispatcher for when the bot gets DC'ed from a vc? or any sort of event dispatcher for vc events, I tried taking a look at the documentation but couldn't find anything about it as it seems to be unfinished?
Just took another look at the docs and found
https://discord.js.org/#/docs/voice/stable/typedef/VoiceConnectionStatus
Not sure if im right but im assuming the state "disconnected" means dc'ing from a vc or does it mean something else like an error
It’ll become destroyed after disconnected
I believe this was explained in the guide somewhere
Or nvm, it’ll start signaling a little after being disconnected
discordjs.guide results:
• Library: Handling disconnects
if (this.shard.status !== Status.READY) return false;
^
TypeError: Cannot read properties of undefined (reading 'status')
``` tried a bunch of different things any idea why this is happening
when i run my distube bot with
client.distube = new distube(client, { searchSongs: false, emitNewSongOnly: true})
it says distube is not a constructor, can someone help??
My bot is experiencing Error: Unexpected server response: 525 and AbortError: The operation was aborted errors, do anyone also get the error when the bot is joining a voice channel?
Show code
it dosent say anything about supporting ras pi4 on the github for discordjs/opus and i get an error when i try to install it is there an alternative way to install?
It doesn't work, according to the guide it should join the channel and play the audio file
you should probably subscribe to the player before playing.
probably going to want to add the file extension to the resource path as well
subscribe to the player?
connection.subscribe(player)
thats what im doing
read my initial message again
oh before
it joins but it doesnt reproduce the file
@frank kelp
have you done this
probably going to want to add the file extension to the resource path as well
i added
const resource = createAudioResource('./audio.mp3')
@frank kelp found the problem, intents xd
GUILD_VOICE_STATES
Again any idea why I keep getting this
if (this.shard.status !== Status.READY) return false;
^
TypeError: Cannot read properties of undefined (reading 'status')```
is there any guide on receiving audio from users in voice channels? Or any examples of how to use Voice.VoiceReceiver?
yes. check the examples in the pinned message
I was reading over that example earlier, the problem is I couldn’t get prism to work no matter what I did so I’m looking for examples that don’t use it.
Ty anyway though
I worked it out, you had to require it with .default
const Distube = require("distube").default;
client.distube = new Distube(client, { searchSongs: false, emitNewSongOnly: true})```
thanks for asking though
Again any idea why this happens every now and than when I try to start the bot..
pls help me out withthis error
But where is your error
just a sec
And what you provided isn't djs, neither is it voice
by mistake here is error and the code
can u help?
pls anyone help me out with this
joinVoiceChannel has a required parameter
discordjs.guide results:
• Library: Voice Connections
Guide tells you what you need to provide
what parameter?
but in your guide it requires channel id but i want the bot to join channel to which i am joined
Then get that channel id
<Member>.voice.channelId or .channel to get the full VoiceChannel
cant understand!
<Member>.voice.channel gives a voice channel
const connection = await joinVoiceChannel(<Member>.voice.channel) like this?
No
then?
The guide shows the proper format
I showed how to get a voice channel from a member so you can use it
how to use that?
should i give params to const connnection?
You have to provide an object into joinVoiceChannel
With the properties shown in the guide
cant understand now also
what did they change VoiceChannel#Join to?
how can I get the boit join in staged channel as speaker ?
if(voiceChannel.type == "GUILD_STAGE_VOICE") {
await voiceChannel.guild.me.voice.setSuppressed(false).catch(e => {
voiceChannel.guild.me.voice.setRequestToSpeak(true).catch(e => {});
});
}
if the bot has permission, it will become a speaker, otherwise, the bot will request to speak
thanks ❤️
can you help me too? lol
maybe
you're looking to make the bot join a voice channel?
i want to make join, leave, queue all these commands
woah woah woah
lololol
I ain't help you coding your entire bot
i tried using one off a tutorial and now it wont work since its in v12
const stream = ytdl(video.url, { filter: 'audioonly' });
^
ReferenceError: video is not defined```
well
that is as simple as reading, "video is not defined"
ye but look const video = await videoFinder(args.join(' '));
how can I make the bot always stay same channel (when its disconnected it will rejoin or move to another channel rejoin old channel again) with voiceStateUpdate ?
const connection = joinVoiceChannel({ channelId: message.member.voice.channel, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator });
const stream = ytdl(video.url, { filter: 'audioonly' });
const player = createAudioPlayer();
const resource = createAudioResource(stream);
async function play() {
await player.play(resource);
connection.subscribe(player);
}
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
}
}```
videoFinder to ytSearch
some crazy stuff going on uh?
Ey how do if nobody join to channel this bot no search a id?
Hi again. Is there a way to get a player element, from a specific guild and voice channel? Like, in Djs 11-12 you could get the connection(and dispatcher) by joining channel, that you're in. But Djs 13 does not have a connection/dispatcher, only AudioPlayer. And how can I get it from a specific guild and vc, like I could do with connection object?
I alr reply before in djs help
it does not help me
use modules @discordjs/voice
i know how to join vc, but question is - How to get a PLAYER object?
Oh i get2
i do
nice
wait let me think first
player object id name or what?
yes, player object(AudioPlayer)
Wait
so we can subscribe player to connection
and if it is global - control it
but I want get the player that is associated with some vc/connection
and get it everywhere, when the other connections have different players, and I control for example, only player #32, when all other players continue playing their file
Before i did this for getting a player(dispatcher) object
if (typeof message.member.voiceChannel !== 'undefined') {
message.member.voiceChannel.join()
.then(connection => { connection.dispatcher.pause();
message.channel.send('Paused.')
});
in djs 11, but now in djs 13 I can't do this, because there is no dispatcher! Only audioplayer.
?
Emm i still try find wait, not to get for djsvoice
okay
If i late respon meant i didnt get it ^^
i'm still waiting
I didnt get :(
k
Djs voice is what ya'll use for music bots?
ye
Again any idea why I keep getting this
if (this.shard.status !== Status.READY) return false;
^
TypeError: Cannot read properties of undefined (reading 'status')```
Could be that "this.shard" is null. Which will cause node to throw you that error
I need help
how to write connection.play() in discord.js 13 cuz it's not viewed as a function any longer
You should read the pinned guide, voice has changed
ahhh lemme check
seems like this needs lot of read through which my weak point currently !! can any1 gimme a quick hint
I don't even know how to read that document
But I’m not running sharping
Ohhh.... I'm just talking about my general knowledge of node that error is caused by attempting to read a property who's value is null or undefined.
Ah
It’s only when trying to do the radio stream
@patent breach try to do a console log reading the shard variable before that stage.
how do i get an AudioPlayer's status without using the statusChange event?
Is there any way to change voice region to the country which they live to fix music bot lag
You're joking?
You don't care about this at all 😂
voice has been moved to the d.js mono-repo
and what about the memory leaks?
Are they going to be fixed?
Good morning ! Right now I want to create a script that displays the number of :
- selfDeaf users
- selfMute users,
- users with selfVideo
- users who streaming
- users serverDeaf
- users serverMute
However, when I enter the voiceinfo command, I get the following error: TypeError: voiceChannel.members.selfDeaf is not a function
I managed to display the total number of people in voice in the server but no more...
Can you help me please ??
The bot is coded in discord.js v12.5.3 with node 14
Thank you
how do i play a mp3 file and not a yt video
what does that mean?
when using entersState function it just timeouts no matter what with the following error https://srcb.in/pY65zx6FQ5
You're iterating over the same stuff way too much which is wasted CPU cycles.
selfDeaf, selfMute, serverDeaf, serverMute, and streaming are booleans. Not Functions.
You can filter over all of the members of a voice channel and check all of the properties you want to accumulate and increment the values you desire.
This is basic JS and not djs-voice related
This is the entersState function I have made which does its job very well.
https://github.com/AmandaDiscord/Volcano/blob/main/src/worker.ts#L77
Use opusscript instead of @discordjs/opus
The djs opus is what's causing memory leaks
Theoretically, no code changes should be necessary
Hi, For some reason I started getting this random error. I wanted to ask and see what the issue is in hopes I can solve it https://sourceb.in/79ECgTqply
Hey @rose helm mind if I dm regarding a few questions on discord js voice
Is there any way to change voice region to the country which they live to fix music bot lag
You have to get the voice region from VOICE_SERVER_UPDATE and strip out the region from the url Discord wants you to connect to
You can map voice nodes to regions and select nodes based off what you strip out
Thanks for helping
Can I get docs too as I can't find docs
Documentation suggestion for @atomic compass:
Client#voice
The voice manager of the client
There are no docs for what I mentioned. That's all on you
Ohk I do it
I did it this works too thanks tho
When i try to queue a stream if the bot is already playing a stream the previous stream just cuts out for a second or so. Is that like a thing that is supposed to happen or hardware issue (but i doubt that), or just my code is trash?
Thank you for your reply.
If I understood correctly, I have to use the method of the filter on the members?
Should I proceed as follows?
(I'm new to discord.js so sorry in advance if this seems obvious to you xD
in this case, members is not defined, You'll need to do
for (const [_, voiceChannel] of voiceChannels) {
count += voiceChannel.members.size;
voiceChannel.members.forEach(member => {
if (somePropertyOnMember) countForThisProperty++; // not literally these variables obviously.
if (someOtherPropertyOnMember) otherCount++;
});
}
thank you very much for your help 
Like I mentioned though, this is basic JS knowledge, so I would highly recommend learning the language's paradigms and such before considering continuing much further and I'm not saying that to discourage you. You will be faced with much resistance if you continue without a comprehensive knowledge of JS
Thank you for your advice. I will learn more about the documentation 
async you know smth about this?
btw by stream i ment a song
Could be a multitude of things such as the process locking for whatever reason. A Queue should just be pushing basic info to an Array and then fetching the data when actually needed instead of fetching it as it's requested as it can be removed by the user at any time.
In my case, I prefetch songs only if they're up next and always check if the songs are fetched or not and fetch if necessary on play
Depending on how many tracks you have queued, queueing more can exhaust system resources if you're fetching as they're being requested. Also quite wasteful on bandwidth and can get you banned from services
Bro you are joking right?
This module is depreacted
I'm not joking. The solution to the memory leak is that simple
Nop. Opusscript has lots of bugs
else i will use it
I'm using it in production and there are no issues. If you're having issues, it's on your end
My most popular example
https://github.com/AmandaDiscord/Volcano
It's with lavalink
Volcano is a lavalink rewrite using Discord.js/voice
Yes, that's good when you have 10k servers
What's your point
You might be thinking of node-opus
ah yes 😆
Il forgot, sorry 😕 i'll try to see with opusscript
Getting same btw
That's due to connection errors
well the problem is that the thread just focuses on downloading the song and just cuts out the rest of the shit the bot does...
and i kinda don't know what to do about that
That is not how to do it. If you absolutely must do it the way you're doing it, offload the work onto a worker_thread
So I followed your syntax like that but when I switch to voice command, there is only the variable count (total users in voice) that works. The other variables remain at 0 😅
Did you enable the guild voice states intent?
plz help
TypeError: Database is not a constructor
full error code = TypeError: Database is not a constructor at Object.<anonymous> (C:\Users\saksh\Desktop\Brandan Final\index.js:21:13) at Module._compile (node:internal/modules/cjs/loader:1097:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10) at Module.load (node:internal/modules/cjs/loader:975:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:17:47
plz help someone
Async said " i can filter over all of the members of a voice channel and check all of the properties i want to accumulate and increment the values i desire , and it is
basic JS and not djs-voice related "
so I don't know if I should use the voicestate as you say or use the method he suggested to me... I guess there are several ways to do it but honestly it's a bit complicated for me XD
database with mongodb ? Did you import mongoose
I've found some type problems between @discordjs/voice - DiscordGatewayAdapterCreator and discord.js - Guild.voiceAdapterCreator
// voiceChannel = Discord.VoiceChannel
joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator, // Type Error
});
Seems like type dismatch between DiscordGatewayAdapterCreator and InternalDiscordGatewayAdapterCreator.
How to deal with this problem?
btw, currently works Guild.voiceAdapterCreator to any type. (but.. I think any type is not good with typescript)
joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator as any,
});
How to map voice nodes to regions
@rose helm opusscript didn't changed anything 👌
Bruh you need to remove discord js opus and only install opusscript.
Installing both will force voice package to use djs-opus over opusscript
I did it
Show me npm ls ??
see
uh
Magic 😂😂
And then how can i remove the package? bc npm uninstall doesn't works
Delete node_modules folder and do npm i again
Unhandled promise rejection: TypeError: channel.join is not a function
iam getting this error
const channel = await interaction.member.guild.channels.cache.get(voiceChannelId);
if (!channel) return console.error("The channel does not exist!");
const connection = await channel.join();
Kinect is saying that you need the guild voice states intent in order to see user's voice data
const receiver = connection.receiver.subscribe(559899420582477847, { });
const writer = receiver.pipe(fs.createWriteStream('./recording.pcm'),);
its not working at all
Pretty sure subscribe doesn't accept an int as the first parameter. Check the docs to see what it does accept
it take user id right

IDs are supposed to be strings. Not ints
I understand better I will try to see that! thanks again
still nothing
That's why I said read the docs
const receiver = connection.receiver.subscribe('559899420582477847', {
mode: "pcm",
end: "silence",
});
const writer = receiver.pipe(fs.createWriteStream('./recording.pcm'));
writer.on('data', (chunk) => {
console.log('hghhhghghj');
writer.write(chunk)
})
can you share link
do you have a link i didnt find anything on doc like nothing
Seems like it does accept an ID first
Since that's the case, I'm not sure how to help you. All I know is IDs are supposed to be strings
@rose helm same issues

🥲 that mean i need to remove discord js and make my on
Why do I keep getting this error?
[
{ status: 'connecting', adapter: [Object], networking: [te] },
{ status: 'ready', adapter: [Object], networking: [te] }
]
} 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 wt(/Users/kavishgulati/Desktop/Github/brainbotdev/node_modules/@discordjs/voice/dist/index.js:9:680)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}
Hi everyone. How can I set volume for bot?
- Create AudioResource with
inlineVolumeoptions. (Docs: https://discord.js.org/#/docs/voice/stable/typedef/CreateAudioResourceOptions)
const resource = createAudioResource(stream, { inlineVolume: true });
- You can set volume by
AudioResource.volume.setVolume
const resource = createAudioResource(stream, { inlineVolume: true });
// Sets volume for created resource
resouce.volume.setVolume(0.3);
why getVoiceConnections().size gives 0 and client.guilds.cache.filter((guild) => guild.me.voice.channel).size gives 1?
Prob didn’t gracefully destroy the connection when you restarted the bot
Discord still thinks ur connected, until it realizes you aren’t
but like yesterday I didn't reboot my bot since some days
hey mates,
is there any way to record all voice from a channel. like subscribe the channel or somethin?
thanks for help 🙂
whats wrong??
You tell us...
Well there you go, you have you answer...
good answer 
I'd suggest following a guide, or watching a few videos to learn basic JS if you don't know how to resolve this error. FYI - you're missing that module 👍
Either install ffmpeg-static package or add ffmpeg to your global path.
Why the hell are you creating a blank resource and not providing the resource in player.play function ??
man i just need to connect the bot to the voice channel for it to be there
Oh then , you can do that with connection only. You don't require player at all for that.
like this?
No need to subscribe also.
how? idk rly man 😅
error:
const channel = ( message | interaction ).member.voice.channel
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
Just this only
ty man!
👍
can you tell me how to remove the muted sound from the bot?
Add this while creating connection
selfDeaf: false
ty very much👌
how to check someone disconnect bot from vc ?
Documentation suggestion for @fiery pond:
(event) Client#voiceStateUpdate
Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
i know tried but not working
if (os.guild.me.voice.channelId && !ns.guild.me.voice.channelId) {
client.updateembed(client, os.guild);
joinVC(client, os.guild.id);
console.log(`done`);
}```
Is this when bot disconnects from VC ??
yes but not working any other way to check bot disconnected from vc or not
Show me your intents
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
// Intents.FLAGS.GUILD_BANS,
Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
//Intents.FLAGS.GUILD_INTEGRATIONS,
//Intents.FLAGS.GUILD_WEBHOOKS,
//Intents.FLAGS.GUILD_INVITES,
Intents.FLAGS.GUILD_VOICE_STATES,
//Intents.FLAGS.GUILD_PRESENCES,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
//Intents.FLAGS.GUILD_MESSAGE_TYPING,
// Intents.FLAGS.DIRECT_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
//Intents.FLAGS.DIRECT_MESSAGE_TYPING,
],```
if (!ns.guild.me.voice.channel?.id) {
client.updateembed(client, os.guild);
joinVC(client, os.guild.id);
console.log(`done`);
}
@fiery pond Try this one
not working i don't know why
might want to console log in the voice state update event unless that's all the code in the voice state update event.
You'll need to find where the code is returning before it reaches the code you're showing
Hello! Why does my bot show it's connected to a voice channel in a server even though it isn't
The voice state events are messed up
do you have the voice states intent?
Yeah, I have every intent
even though it isn't connected to these channels, it shows their ids
That could possibly happen if you restart the bot while it's in a voice channel. GUILD_CREATE data includes a voice_states field which could include your client's. Bots can usually restart completely before Discord auto disconnects them from a voice channel if they don't reconnect before that window.
Well it's after disconnecting the bot from the voice channel manually while the bot's playing something there. It still thinks it's playing
Wdym by "manually" disconnecting the bot?
Did you enable the guild voice states intent?
yeah, i have all enabled
Guys
is there solve for that error?
This error is from ytdl-core, switch to play-dl.
okay i will try
Hey folks, I'm having an issue where after streaming audio with ytdl-core, streaming local files no longer works, even after creating completely fresh players and resources. I've seen similar issues earlier in this chat but couldn't pin down a solution
Queueing and playing of local files and youtube videos work independently just fine. But after playing with ytdl-core, local files are permanently borked until I restart
I've seen the recommendations for play-dl but I can't find any kind of setvolume() function in that library (which i kinda need)
You can set the volume with djs voice
right you are - I got confused as to what lib the createAudioResource function was from, thanks
Does anyone know why my musicbot stops playing music after changing audioressource?
If you send your code perhaps I can find out.
@rugged sky I play music with mp3 streams and with the play-dl libary. It works when switching from mp3 stream to play-dl, but not from play-dl to mp3 it just stops
async function playmusic(streamURL){
var resource;
if(typeof streamURL == 'string'){
resource = createAudioResource(streamURL)
}else{
resource = createAudioResource(await (await playdl.stream(streamURL.url)).stream);
}
try{
player.play(resource);
bot.connection.subscribe(player);
}catch(error){
console.log(error);
}
}
Hmm, that is peculiar. This bit of code looks fine. I would suggest just playing around with logging the player and resource and seeing what's going on. It's possible the player will get stuck on buffering meaning the resource can't be resolved.
Ok, I will try
I checked both player and ressource and both look well any other ideas?
You need to pass stream type along with the stream.
As mentioned in their examples.
Thanks that solved it
What could be the problem when my bot stops playing music for a second while adding a song to the queue?
It’s now <Player>.play(<AudioResource>)
My discord bot wont join a channele
So i have this code:
import * as dc from "discord.js"
const connection = joinVoiceChannel({
channelId: msg.member?.voice.channel.id,
guildId: msg.guildId,
adapterCreator: msg.member?.voice.channel.guild.voiceAdapterCreator,
});
Im working with Typescript so i cant use the require statement what is my way to do it? Its saying: "Cannot find name 'joinVoiceChannel'
show code
tmr
Pls can anyone help me with it
I don't really know typescript but I think you need to write dc.joinVoiceChannel
I am trying to get a voice connection using discordjs/voice but it is always returning undefined even when the bot is in a voice chat and playing audio.
const { getVoiceConnection } = require('@discordjs/voice')
async execute(interaction) {
const connection = getVoiceConnection(interaction.guildId);
console.log(connection) //undefined
connection.destroy(); //errors
return interaction.reply({ content: "Left Voice Chat!" });
}
I have even tried putting the guildID manually
its still undefined
Do you have the GUILD_VOICE_STATES intent?
What's going on here. I am following the information here:
https://discordjs.guide/voice/voice-connections.html#cheat-sheet
However, the following code:
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
Returns the following error:
TypeError: s is not a function
Further debugging shows that value for adapterCreator ends up being undefined 🤔
Seems to work fine if I upgrade to discord.js@13 - no mention that this is required in the docs. Maybe this can be included to save people such hassle in the future 😠
I would rather not upgrade to v13, though. Is there any other option?
Use the regular voice if ur not using d.js v13
Well, guild.voiceAdapterCreator was not added until v13
v12 and lower is deprecated and no longer supported anyways
I can't. I'm explicitly switching to this voice integration due to ongoing issues with the built-in one
To be more specific, the built-in one has issues where the bot would randomly stop broadcasting arbitrary audio stream input after some time. The client voice connection would still show as connected and speaking, even though its not. Just a buggy mess in short. We're hoping discord.js/voice would fix these issues (a couple of github issues say it would)
Is there a changelog or something I can read, so I know which parts of the codebase would need to be modified to be v13 compliant?
Version 13 has released! Please update at your earliest convenience, we will not indefinitely support v12.
• Update: npm rm discord.js npm i discord.js
• Update guide (use CTRL + F to search for the old method or property)
Neat 👍
Just curious, why doesn't the VoiceConnection object (https://discord.js.org/#/docs/voice/stable/class/VoiceConnection) yield any information about the channel it relates to.
i.e. you can use the getVoiceConnection() method to find an existing connection in a server, but it doesnt let us know which channel it's in
you've gotta join a voice channel first with the joinVoiceChannel() function
Error: Cannot perform IP discovery - socket closed
what does this mean?
I know that. That's not what I'm asking.
As per this:
https://discordjs.guide/voice/voice-connections.html#access
It is best practice to not track the voice connections yourself
They therefore recommend using getVoiceConnection if accessing the connection from elsewhere in the codebase, the problem with this, is you dont get any channel info
The lib doesn't receive any packets other than voice state update and voice server update which isn't enough to actually provide any meaningful voice channel info other than guild_id and channel_id
Mapping the channels is up to the main Discord interface you use. Or up to you if you take a lower level approach
getting a connection from the lib requires a guild ID (and a clientID if 1 process manages multiple clients) which is more than sufficient for you to get the guild by ID in your cache and then filter over the voice_states to find the desired client's voice state data
Node js single threaded nature is the main reason behind that.
I'm trying to make a music bot, but it keeps running into this error:
node:events:368
throw er; // Unhandled 'error' event
^
N [Error]: 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:687:12
at TCP.done (node:_tls_wrap:580:7)
Emitted 'error' event on H instance at:
at OggDemuxer.t (/path/to/node_modules/@discordjs/voice/dist/index.js:8:288)
It happens around 45 seconds into the song playing, not at the start or end. How would i fix this?
hmm, playing another song doesn't seem to error. The song erroring is HENNSON - SAHARA
too much bass? ¯_(ツ)_/¯
Do you play with ytdl libary?
yes
it works with all other songs I've tried though lol
Weird, I got the same error and switching to the play-dl library worked for me. https://www.npmjs.com/package/play-dl
Cause ytdl has some stream abort issues
I'll try that, thank you!
.
I have this error with playing songs (around 2nd minute in each song)
https://sourceb.in/Ay59KHbUNW
pls help
what library are you using to get the music ?
im using @discordjs/voice, yt-search and ytdl-core
it's a common issue with ytdl iirc
how I can repair this?
it works like ytdl?
yea more or less
ok thx
thank you very much, my all problems gone 
So I have a music bot that used to be on discord v12 but I upgraded to v13. I have a finish function and I have no clue how to implement that into the new audioPlayer function. Does player.on('finish') still work? How do I know when a song is finished playing?
idle, not finish
Multiple Resolves
reject Promise {
[
{ status: 'connecting', adapter: [Object], networking: [te] },
{ status: 'ready', adapter: [Object], networking: [te] }
]
} AbortError: The operation was aborted
at abortListener (node:events:842:14)
at EventTarget.<anonymous> (node:events:878:47)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:460:20)
at EventTarget.dispatchEvent (node:internal/event_target:405:26)
at abortSignal (node:internal/abort_controller:98:10)
at AbortController.abort (node:internal/abort_controller:123:5)
at wt (C:\Users\MrFluffycloud\Documents\Botto\node_modules\@discordjs\voice\dist\index.js:9:680)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}```
wat does this mean?
reject(new AbortError());
^
AbortError: The operation was aborted```
Any idea when I use voice
Remove any code with entersState function. Ez fix
What causes that error
Hey, how what exactly adapterCreator does?
Also how i can play youtube video? it wont let me use ytdl..
You can try play-dl.
but ytdl wont work in this discordjs version?
ytdl-core has some issues, yes. Play-dl doesn't have those issues with djs.
uh i see, but anyway im getting this error:
const dispatcher = connection.play(ytdl(vid)) how i can update/fix the issue?
That's the error message you get?
Sorry, TypeError: connection.play is not a function
That's the old way of playing audio from v12. That version is no longer supported.
tried subscribe but still getting an error
Pinned messages has a guide, it will explain how to do it now.
any know why?
i'm trying to entersState()
What is the best way to play the same audio in every server (main server auto connects on ready) the rest of the servers use a command to join it
subscribe all connections to 1 player
Possible EventEmitter memory leak detected. 11 closing listeners added to [VoiceConnection]. Use emitter.setMaxListeners() to increase limit
As far as I read on the internet, there is a solution to not show the error message (client.setMaxListeners(30) or process.setMaxListeners(30)), but we need to find the exact solution of the error ourselves, what do you think causes this error?
Hey, for some reason my bot wont play the sound, im not getting any error just "Abort Error" after few seconds..
my code:
const connection = joinVoiceChannel({
channelId: vc.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
})
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
return connection;
} catch (error) {
console.log(error)
connection.destroy()
}
const resource = createAudioResource(vid, {
inputType: StreamType.Arbitrary,
})
player.play(resource)
//resource.volume.setVolume(vol / 5)
return entersState(player, AudioPlayerStatus.Playing, 5e3)```
How can I make a seek command in V13?
So if I have the player in my ready I can use it on another event
Correct
Would that be connection.subscribe(player)
Yeah
each chunk of data the player receives, it pushes that to all of its subscribers to send the packet to their voice channel
After processing is done of course
There is a known bug with entersState function.
Is there a way to get a player from a connection?
Yeah there is
connection.state.subscription.player
If I am correct
Thanks!
How do I define all voice region
How would i go about making a music bot?
I'm getting AbortError: The operation was aborted When i disconnect it manually
why?
help med pls
does anyone know what this error means(more of why its happening), and if so how to fix it? Error happens when using joinVoiceChannel, code below
joinVoiceChannel({
channelId: channelid,
guildId: serverid,
voiceAdapterCreator: voiceAdapterCreator,
}); //exact copy from code, variables are extracted from interaction
I have looked everywhere for a explanation on the error and cant get one.
Myself and my users are currently running into an issue where the lib throws that it cannot probe a readable stream in object mode. Is there a fix for this?
seems like just play-dl is emitting object mode streams, so I'm just avoiding the demuxing from play-dl since it provides voice compatible stream types
Trying to convert old code to the new version. where did go VoiceConnection.dispatcher?
#archive-updating-to-v13 might help
gonna check
You can use discordPlayerCompatibility option. It will emit normal webm streams
Already switched it to use the types the lib provides to avoid useless cpu time spent demuxing
The repo has an example - check out the pins
That's not how you do it in v13. Check out the guide in pins
Make sure the ids are correct and that it is <guild>.voiceAdapterCreator
when the VoiceConnectionState gets destroyed i can't really enter another state after that. Anybody know what is the cause of that
I have checked the server id, channel id, and voiceAdapterCreator(which is extracted from the guild) are all correct
how can I make my bot join VC?
thru the joinVoiceChannel function provided from discordjs/voice
Do you have ffmpeg and opus installed?
Yes ffmpeg-static and @discordjs/opus
Hm maybe show the full code in a bin? Of the interaction and where you try to join
I am not at home rn but I will when I get home(around 3pm cst)
I’ll ping you the when I do
where can i get createDiscordJSAdapter?
its from a package?
Refer to this @still bison
.
guild is my guild right?
yes a guild object that u provide
oh ok
const guild = client.guilds.cache.get(guildID);
this works right?
https://discordjs.guide/voice/voice-connections.html#life-cycle
"Destroyed - the state a voice connection enters when it has been manually been destroyed. This will prevent it from accidentally being reused, and it will be removed from an in-memory tracker of voice connections."
If that is what you mean.
Yeah
if (interaction.commandName === "clem") {
console.log(interaction.member.voice.channel);
const channel = interaction.member?.voice.channel;
if (channel) {
try {
const connection = await connectToChannel(channel,interaction.guild);
connection.subscribe(player);
await interaction.reply("Playing");
} catch (e) {
console.log(e);
}
} else {
await interaction.reply("not in voice");
}
await interaction.reply({ content: "Clem!", empheral: true });
}
i have this error
What is connectToChannel defined as?
async function connectToChannel(channel,guild) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: guild.voiceAdapterCreator(channel),
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
return connection;
} catch (e) {
connection.destroy();
throw e;
}
}
I think it is only <guild>.voiceAdapterCreator 🤔
same error
no i'm very aware of how to handle life cycles but like
when i disconnect it it can't go back in a ready state
AA question, how can we get the resource total duration of connection.state.subscription.player.resource?
And how can I seek in a track in discord.js 13?
That must be done manually with ffmpeg
how then?
what about webm/opus streams?
heres the command code, if more is needed then I will provide.
What is voiceAdapterCreator variable defined as ??
Error says that above variable is not a function.
You might forgot to define all variables in joinVoiceChannel function I think 🤔
that was just that snippet
the vars are defined above
How do I play an audio file with the new joinVoiceChannel function? I can't do connection.play anymore
yeah i figured it out in the guide, thanks regardless :D
Hello everyone, i've got a problem i'm a beginner, and i can't manage to make it work :
if (message.member.voice.channel) {
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
}
);
if (message.content.startsWith("$play")) {
let args = message.content.split(' ')
let live = YoutubeStream(args[1])
const player = createAudioPlayer();
const resource = createAudioResource(live);
async function play() {
await player.play(resource);
connection.subscribe(player);
}
}
}
})```
Does anyone know where did i make an error ?
When the VoiceConnection state gets destroyed, why can't it get in a ready state after that?
Bc it was destroyed
Destroyed means it’s no longer usable
What’s the issue exactly?
but then how i recover from that?
You don’t?
If you destroy it, then you have to make a new connection
aha ok ok ty
I can't manage to make my bot play a youtube audio
Do you get any errors?
Yes sir,
Error: FFmpeg/avconv not found!
You need to install ffmpeg
discordjs.guide results:
• Getting Started: Installation - Barebones
Either ffmpeg from the official site (not an npm package), or ffmpeg-static from npm
Oh thanks a lot let me check
(node:38312) DeprecationWarning: The message event is deprecated. Use messageCreate instead
So we're talking about my let args = message.content.split('') here ?
`client.on('message', message => {
if (message.content == '!report') {
message.author.send('Hello, if you would like to report please say their username and tag')
setTimeout(function() {
var reporteduser = message.lastMessage
console.log(reporteduser)
}, 10000);
}
});`
It keeps returning undefined
not voice related
has anyone else had discordjs's voice randomly go idle and stop playing after some time while playing audio? I've encountered it multiple times now, each time after some amount of minutes
not sure if because I'm using ffmpeg to create the resource with raw stream type
AudioPlayer does not play mp3 files stored in Discord CDN if a stream was played before
any fix for ⬆️?
Make a new resource
@abstract acorn
my code always create new audio resource tho
Are you getting an error?
no
any documentation on discord js recording
it just doesn't play anything, but everything else worked (even now playing message came through)
Show us your code of creating resource
// ... (this handles end of queue)
} else {
serverInfo.playing = true;
if (serverInfo.leaveTimer != undefined) {
try { // clear timer before playing track
clearTimeout(serverInfo.leaveTimer);
serverInfo.leaveTimer = null;
} catch(err) {} // there's no leaveTimer
}
if (!serverInfo.player) createPlayer(client, message, song);
serverInfo.resource = null;
let resource;
if (song.source === "youtube") resource = createAudioResource(ytdl(song.url, { filter:"audioonly", highWaterMark: 1 << 23, type: 'opus' }), {inlineVolume: true});
else if (song.source === "discord") resource = createAudioResource(song.url, {inlineVolume: true});
resource.volume.setVolume(serverInfo.volume);
serverInfo.player.play(resource);
serverInfo.resource = resource;
embed.setColor(message.guild.me.displayHexColor);
embed.setTitle("Now playing");
embed.setDescription(songTitle(song));
return message.channel.send({ embeds: [embed] }).then(msg => {
serverInfo.npMessageID = msg.id;
});
}
song.source === "youtube" means the url is youtube video, where ytdl create streams
song.source === "discord" means the url of audio file from discord CDN
Where do you play this in a player ??
Show me that code also.
function createPlayer(client, message, song) {
const serverInfo = centralInfo.get(message.guild.id);
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
serverInfo.connection.subscribe(player);
serverInfo.player = player;
/* start of many handlers */
/* not really needed here? */
/* end of many handlers */
}```
I see your error.
You need to change the type to something else in ytdl core.
FFmpeg doesn't change raw Opus packets to PCM.
So I think that might be one of the issue.
fyi i just checked the player object, it seems like status is stuck in "buffering" when this bug happens
I know. It is waiting for FFmpeg to emit data but since FFmpeg can't convert raw Opus packets to PCM, stream will never emit data.
So that's why it remains in buffering state.
hmm i tried changing type to vp9 (as others feel like random numbers) and removing all options altogether, but the bug still persists
Then, I recommend you to switch to play-dl.
why is ytdl-core somehow a mess now?
and I tried play-dl but nothing would play after needing to use it, even youtube link is somehow unplayable now
Add discordPlayerCompatibility to true while creating stream. It will get fixed.
i dont use discord-player package tho
just discordjs/voice
I know. Since you are not passing the stream type while creating resource. It is a fix for you.
still doesn't fix this (and still stuck in buffering)
and the changed code is this
if (song.source === "youtube") {
const pain = await playdl.stream(song.url, { discordPlayerCompatibility: true });
resource = createAudioResource(pain.stream, {inlineVolume: true});
}```
Can you console.log(resource.edges) ??
And also log dependencies like
const { generateDependencyReport } = require('@discordjs/voice');
console.log(generateDependencyReport());
should we move to direct message?
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: not found
FFmpeg
- version: 4.3.1
- libopus: yes
wait i uninstalled @discordjs/opus already tho
first time running mp3 (playable)json [ { type: 'ffmpeg pcm', to: Ue { edges: [Array], type: 'raw' }, cost: 2, transformer: [Function: transformer], from: Ue { edges: [Array], type: 'arbitrary' } }, { type: 'volume transformer', to: Ue { edges: [Array], type: 'raw' }, cost: 0.5, transformer: [Function: transformer], from: Ue { edges: [Array], type: 'raw' } }, { type: 'opus encoder', to: Ue { edges: [Array], type: 'opus' }, cost: 1.5, transformer: [Function: transformer], from: Ue { edges: [Array], type: 'raw' } } ]
run yt (play-dl)json [ { type: 'ffmpeg pcm', to: Ue { edges: [Array], type: 'raw' }, cost: 2, transformer: [Function: transformer], from: Ue { edges: [Array], type: 'arbitrary' } }, { type: 'volume transformer', to: Ue { edges: [Array], type: 'raw' }, cost: 0.5, transformer: [Function: transformer], from: Ue { edges: [Array], type: 'raw' } }, { type: 'opus encoder', to: Ue { edges: [Array], type: 'opus' }, cost: 1.5, transformer: [Function: transformer], from: Ue { edges: [Array], type: 'raw' } } ]
second time running mp3 (unplayable)json [ { type: 'ffmpeg pcm', to: Ue { edges: [Array], type: 'raw' }, cost: 2, transformer: [Function: transformer], from: Ue { edges: [Array], type: 'arbitrary' } }, { type: 'volume transformer', to: Ue { edges: [Array], type: 'raw' }, cost: 0.5, transformer: [Function: transformer], from: Ue { edges: [Array], type: 'raw' } }, { type: 'opus encoder', to: Ue { edges: [Array], type: 'opus' }, cost: 1.5, transformer: [Function: transformer], from: Ue { edges: [Array], type: 'raw' } } ]
also this one, using ytdl-core instead of play-dl
[
{
type: 'ffmpeg pcm',
to: Ue { edges: [Array], type: 'raw' },
cost: 2,
transformer: [Function: transformer],
from: Ue { edges: [Array], type: 'arbitrary' }
},
{
type: 'volume transformer',
to: Ue { edges: [Array], type: 'raw' },
cost: 0.5,
transformer: [Function: transformer],
from: Ue { edges: [Array], type: 'raw' }
},
{
type: 'opus encoder',
to: Ue { edges: [Array], type: 'opus' },
cost: 1.5,
transformer: [Function: transformer],
from: Ue { edges: [Array], type: 'raw' }
}
]```
How do I define voiceregion
Hello! I know is a little against the rules of this server but can anyone tell me what should i put. So my bot has an music feature and when the music ends he automatic leaves the voice chat. The thing i want is to stay in. And when all the members leaves the voice channel then the bot can leave it too.
Don't destroy the voiceconnection when there is no songs in ur queue and do so when the voicechannel member size is only 1 and that member is your bot
Does anyone know why @discordjs/voice is archived?
is their any way i can add ogg slient file in the audio recorder
My code seems correct, when i tell it to play outside the vc it gives me the error prompts as it should but if I join a vc and hit play it doesn't react at all. what do I do?
Is there a way to get the current voice channel of a member that creates an interaction from the interaction event? I don't see the property in the member docs. (not sure if this belongs in #archive-interactions or #archive-voice )
interaction.member.voice.channel
Thank you! ❤️
can anyone help?
Are you able to make a music system from multiple files?
How can I cache all voice channel informations on each command run?
What would signify the bot in a voice channel? Would it be <Client>.user.voice.channel?
<Guild>.me.voice.channel
Do you have the GUILD_VOICE_STATES intent?
I... don't think so?
or well since then its gotten different. now the code isn't showing any errors, but it won't play the 'play' command
How do I get my bot to join a VC? No need to unmute, or play anything, just join.
How do I define voiceregion
joining the VC is up to the bot's gateway connection. You'd send an op 4 voice state update packet if you're using raw gateway.
This lib just connects to the url provided in the VOICE_SERVER_UPDATE packet
voice regions are tricky because you can only access a voice channels region after you receive a VOICE_SERVER_UPDATE packet and strip out the region from the endpoint Discord sends you unless the channel has the rtc_region set already and available in the gateway/api.
Was wondering if anyone knows how to seek using ytdl-core? (Discord v13 btw)
begin option apparently doesn't work
I found this on stackoverflow I hope it helps (v12 btw)
// When playing the song:
const stream = ytdl('https://youtu.be/dQw4w9WgXcQ')
// Store the stream somewhere
queue.currentSong = stream
// When seeking:
queue.connection.play(queue.currentSong, {seek: ms / 1000})
sadly thats v12, thnx anyway tho
😦 yes v12
this msg is being sent by the bot even if im in a voice channel
does the bot have access to that channel?
¯_(ツ)_/¯
what intents are you using
thanks but i already fixed my problem
bots know about every channel regardless of permissions
Connection.play() is not a function?
oh ok good to know
That's how you did audio in v12, it's v13 now. Need to use AudioPlayer and AudioResource. In pinned messages is a guide.
ok thanks
Hello, help me, please update the voice status.
But it only increases, it does not decrease
client.on('ready', () => {
const server = client.guilds.cache.get('')
const member_channel = client.channels.cache.get('')
const voiceChannels = server.channels.cache.filter(c => c.type === 'voice');
const alivevoice = client.channels.cache.get('')
let alivecount = 0;
for (const [id, voiceChannel] of voiceChannels) alivecount += voiceChannel.members.size;
setInterval(() => {
member_channel.setName('⦿ Total User: ' + server.memberCount)
alivevoice.setName('⦿ Total Mic: ' + alivecount)
}, 60000)
}) ```
I think it's because the system is looping but the data is always in the same place
setInterval(() => {
let alivecount = 0;
for (const [id, voiceChannel] of voiceChannels) alivecount += voiceChannel.members.size;
member_channel.setName('⦿ Total User: ' + server.memberCount)
alivevoice.setName('⦿ Total Mic: ' + alivecount)
}, 60000)
Note : I'm not sure about this maybe it will work
Hi, do you have a way to fix the issue of voice channels randomly disconnecting in the middle of playback, which can happen after 10 minutes like 6 hours of listening ?
Hey guys anyone know why when I disconnect the oldState returns channelId as null?
the oldState used to show the channel someone left on discord.js v 12
now it shows null
i've been following the discord.js voice recording guide, and the bot joins and tries to start listening. when i'm using prism.opus.OggLogicalBitstream i'm getting an error:
TypeError: failed to downcast any to number
i suspect it has to do with node-crc, because in the OggLogicalBitstream options if i setcrc to false, it makes a recording but it doesn't work
how can i know the status of the audio if it was playing or paused ....
🤝
how do i make a command from which my bot will join the voice channel
Guide suggestion for @subtle granite:
discordjs.guide results:
• Library: Voice Connections
• Library: Cheat sheet
What is message?
const ytdl = require('ytdl-core');
const {
AudioPlayerStatus,
StreamType,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
} = require('@discordjs/voice');
const voice = require('@discordjs/voice');
module.exports = {
category: 'Music',
description: 'Plays music in an voice channel',
slash: true,
minArgs: 1,
testOnly: true,
expectedArgs: '<title>',
callback: async ({ client, message, interaction, args }) => {
const [ title ] = args;
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channelId,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
});
const stream = ytdl(`https://www.youtube.com/watch?v=dQw4w9WgXcQ`, { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
const player = createAudioPlayer();
player.play(resource);
connection.subscribe(player);
interaction.reply(title)
}
}
won't play anything
const { channel } = message.member.voice;
const botchannel = message.guild.me.voice.channel;
if (!channel) {return message.reply({embeds: [new MessageEmbed().setTitle(' You need to join a voice channel').setColor(es.wrongcolor).setFooter(client.getFooter(es))]});}
if(!channel.permissionsFor(message.guild.me).has("CONNECT")){return message.reply({embeds: [new MessageEmbed().setTitle(":x: I'm missing the Permission to join your Voice Channel").setColor(es.wrongcolor).setFooter(client.getFooter(es))]});}
if(!channel.permissionsFor(message.guild.me).has("SPEAK")){return message.reply({embeds: [new MessageEmbed().setTitle(":x: I'm missing the Permission to speak in your Voice Channel").setColor(es.wrongcolor).setFooter(client.getFooter(es))]});}
if(channel.userLimit != 0 && channel.full){return message.reply({embeds: [new MessageEmbed().setTitle(":x: Your Voice Channel is full!").setColor(es.wrongcolor).setFooter(client.getFooter(es))]});}
if (botchannel) {return message.reply({embeds: [new MessageEmbed().setTitle(` I am already connected in: \`${botchannel.name}\``).setFooter(client.getFooter(es))]});}
const e = await message.react('🎙️').catch(e => console.log(String(e).grey))
let VoiceConnection = joinVoiceChannel({channelId: channel.id,guildId: channel.guild.id,adapterCreator: channel.guild.voiceAdapterCreator});
let file = path.join(__dirname + `/audio/${CmdName}.mp3`);
if(!file || !fs.existsSync(file)) file = path.join(__dirname + `/audio/${CmdName}.m4a`);
if(!file || !fs.existsSync(file)) file = path.join(__dirname + `/audio/${CmdName}.mov`);
if(!file || !fs.existsSync(file)){return message.reply({embeds: [new MessageEmbed().setTitle(":x: Could not find the AUDIO").setColor(es.wrongcolor).setFooter(client.getFooter(es))]});}
const resource = createAudioResource(file, {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)}
e.remove().catch(e => console.log(String(e).grey))
});
This is my script
It works just fine, but after 10-12hours of uptime, it won't play any audio... what should i do to fix that?
do you have enabling Intents.FLAGS.GUILD_VOICE_STATES ?
try ^^
how do I convert old v12 voice code to v13
change it
I've been trying to install the dependencies (sodium and opus) and cant get them to install
PS D:\code\spotify-bot> npm install sodium
npm ERR! code 1
npm ERR! path D:\code\spotify-bot\node_modules\sodium
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node install.js --install
npm ERR! MS Version: 2015
npm ERR! Install Mode
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@8.4.1
npm ERR! gyp info using node@17.4.0 | win32 | x64
npm ERR! gyp info find Python using Python version 3.9.5 found at "C:\Users\joel_\AppData\Local\Programs\Python\Python39\python.exe"
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS msvs_version was set from command line or npm config
npm ERR! gyp ERR! find VS - looking for Visual Studio version 2015
npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
npm ERR! gyp ERR! find VS checking VS2017 (15.9.28307.1778) found at:
npm ERR! gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools"
npm ERR! gyp ERR! find VS - found "Visual Studio C++ core features"
npm ERR! gyp ERR! find VS - found VC++ toolset: v141
npm ERR! gyp ERR! find VS - found Windows SDK: 10.0.17763.0
npm ERR! gyp ERR! find VS - msvs_version does not match this version
npm ERR! gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use
npm ERR! gyp ERR! find VS looking for Visual Studio 2015
npm ERR! gyp ERR! find VS - not found
npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS valid versions for msvs_version:
npm ERR! gyp ERR! find VS - "2017"
npm ERR! gyp ERR! find VS - "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools"
npm ERR! gyp ERR! find VS
I've ran npm i windows-build-tools --vs2015 many times already and even when it installs successfully i get the same error message when installing the dependencies
anyone know a fix?
• Run npm i windows-build-tools --production --vs2015 --add-python-to-PATH --global as admin.
• Restart your terminal or machine (if terminal is not sufficient).
Wierd enough, the logs seems to indicate you also have 2017 installed, but ur npm config is currently set to use 2015 (or some version other than 2027)
i set that manually, should i use 2017? i read that sodium only works with build tools 2015 and below
anyways i get error msvs version is not defined if i do iirc
When it tried to use the 2015
find VS VCINSTALLDIR not set, not running in VS Command Prompt
gonna try installing the 2015 build tools manually
You could try using the VS Build Tools installer
i just installed it with that, it worked and the npm install command ran fine 👍
How i can setup the banner of the video as embed. Like for example: .setImage("banner-here")
is there any code for that?
Did you find an alternative to this?
client.on("interactionCreate", interaction => {
if (interaction.commandName === "music") {
const ytdl = require('ytdl-core');
const {
AudioPlayerStatus,
StreamType,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
} = require('@discordjs/voice');
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channelId,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
});
const stream = ytdl('https://youtu.be/3nQNiWdeH2Q', { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
const player = createAudioPlayer();
player.play(resource);
connection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => connection.destroy());
interaction.reply({content: "successfully"})
}
})```
slash command `music` not showing up
Deploying globally?
no, one server
Hi fam do you know why my bot can play radio flux url only if he start with ip+port ? ^^
Hello, please help me how to define this update
client.on('ready', () => {
const server = client.guilds.cache.get('')
const member_channel = client.channels.cache.get('')
const voiceChannels = server.channels.cache.filter(c => c.type === 'voice');
const alivevoice = client.channels.cache.get('')
let alivecount = 0;
for (const [id, voiceChannel] of voiceChannels) alivecount += voiceChannel.members.size;
setInterval(() => {
member_channel.setName('⦿ Total User: ' + server.memberCount)
alivevoice.setName('⦿ Total Mic: ' + alivecount)
}, 60000)
})```
When it is turned on, it saves the status from the moment, if the status changes, it will not receive the new status
How to loop?
**What is code for join vc and play any audio from any file in v13
Like there was a code in v12
message.member.voice.channel.join().then((connection) => {
connection.play(path.join(__dirname + './../../structures/test404.mp3'))
})```**
wh y is my bot not playing music when I've created a resource, created a player, connected to the VC, subscribed to the player?
https://discordjs.guide/voice/ follow the guide
only solution i figured out was:
- after creating a voice connection using
joinVoiceChannel - access the connection's receiver's speaking map:
speakingMap = connection.receiver?.speaking - add event listeners for 'start' and 'stop' to the speakingMap:
speakingMap?.addListener("start", (userId: string) => {
//register that userId started speaking
})
how do i make my bot join the msg.member's vc
v13 btw
alr
If you're still having trouble, tell me i'll try to help
alr ty
**```js
joinVoiceChannel({ channelId: channel.id, guildId: channel.guild.id, adapterCreator: channel.guild.voiceAdapterCreator })
const astra = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
const resource = createAudioResource('./../../structures/Resuming.mp3');
astra.play(resource);
@tepid tulip
I'm not sure that error comes from what you're showing me
if (cmd == prefix + "joinvc") {
let channel = msg.guild.channels.cache.find(
channel => channel.id === 926392547876671511
)
const { joinVoiceChannel } = require('@discordjs/voice');
const { getVoiceConnection } = require('@discordjs/voice');
const connection = getVoiceConnection(msg.channel.guild.id);
const subscription = connection.subscribe(player);
if (subscription) {
setTimeout(() => subscription.unsubscribe(), 5_000);
}
}
doesnt work im very stupid lmao
this is the top:
const { joinVoiceChannel } = require('@discordjs/voice');
const { createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice');
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
new to djs voice
Let me check
alr
Is that the only place you put the joinVoiceChannel ?
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
This is how it should be
realised that i had 2, so i deleted the one in the cmd
alr lemme try
Did you put a resource anywhere ?
Without the resource, the bot won't play anything
bot isn't even joining though
alright nvm i got it working im just mentally special
😂 perf then
i forgor my own command name 💀
ahahahah it happens
why wont my player play
it works on another bot but not with a diffrent token
Awesome, thanks a bunch
nvm i was deafend
why is my bot not playing anything? I've joined the VC, created a player, subscribed, started playing but I can't hear anything
took me forever to realize that to fix "ffmpeg not found" error is to just drag ffmpeg.exe into the folder 😐
Show me the error if there's one
and your code
no error
Show me your code if you're willing to 🙂
make it join undeafened
I did, still no sound
I miss v12 where it was as simple as connection.play(file)
is there any way to download an earlier version of discordjs voice that doesnt require node.js 16.9? I can only install v16.7
Hi everyone. I am trying to make a music bot, but I have an issue. Bot randomly crashes with error that does not make any sense to me. The error itself:
node:events:368
throw er; // Unhandled 'error' event
^
N [Error]: 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:687:12
at TCP.done (node:_tls_wrap:580:7)
Emitted 'error' event on H instance at:
at OggDemuxer.t (/test/musicbot/node_modules/@discordjs/voice/dist/index.js:8:288)
at Object.onceWrapper (node:events:510:26)
at OggDemuxer.emit (node:events:402:35)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
Bot runs off a VPS with Ubuntu 18.04 and Node.js 16.13.1. I am not a professional dev, but can assume, that according to error it have tried to make a HTTP request with default http lib, but got connection reset error(It might be important to add, that I live in Russia, and some websites that are blocked return provider's message saying that this site is blocked or just ERR_CONNECTION_RESET returns). How can I fix this issue?
And also, why it even happens?
my bot doesn't play sound, even though the code looks fine
hello?
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
selfMute: false,
selfDeaf: false
});
const audioPlayer = createAudioPlayer();
connection.subscribe(audioPlayer);
audioPlayer.play(
createAudioResource(
createReadStream(`/home/bot/luibot/data/music/${music}.ogg`)
),
{ inlineVolume: true }```
Hello?
Did you call <Player>.play(resource)?
Oh, I see it
Did you enable the guild voice states intent in the client?
Oh, one moment
Thanks, that worked
var connection = await voiceChannel.join();
const voiceChannel = message.member.voice.channel;```
error:```js
TypeError: voiceChannel.join is not a function
at execute (/home/runner/Marvin/index.js:92:43)
at runMicrotasks (<anonymous>)```
nvm im thinking of discord.js v12
time to reread docs ig
im looking through the documentation and I can't find any info on the function joinVoiceChannel
I see joinVoiceChannel options
but not joinVoiceChannel
I use this to connect to vc:
//top of the file:
const {
AudioPlayerStatus,
StreamType,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
} = require('@discordjs/voice');
// use this part of code in interaction event:
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channel.id,
guildId: interaction.member.guild.id,
adapterCreator:interaction.member.voice.guild.voiceAdapterCreator,
});
did anyone else had the same issue?
ytdl-core issues
i use spotify-it
oh ok
so, i need to create issue on ytdl-core repo?
I think they already had this.
https://github.com/fent/node-ytdl-core/issues/994
But they are not going to fix this anytime soon.
thanks for your reply, but how else can I play spotify songs?? Any other libs didn't worked for some reason.
and youtube
play-dl
play-dl is good, but I did not understood how to authorize
You can ask them in their support server. I can't help here you anymore since this is discordjs voice support.
ok, thanks
Hey guys, im trying to make my bot join a channel but it keeps on giving me this error:
TypeError: Cannot read properties of null (reading 'id')
here's the code i used for the bot to join the vc:
const { joinVoiceChannel } = require('@discordjs/voice') if (message.content === '!voice') { joinVoiceChannel({ channelId: message.member.voice.channel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator }) }
Can someone please help me resolve this issue?
Do you have the GUILD_VOICE_STATES intent?
No
You need that.
Ayt bet lemme try that
It still gives me the same error
For some reason it thinks you're not in a voice channel. Can't figure out why from this, but perhaps that knowledge can help you figure it out.
Ok thanks
how do I get the current vc connection?
client.on("ready", async () => {
// gharar dadn id voice va server
let serverid = "394910662662553600";
let voiceid = "821407901549330432";
//join shodan bot dar voice
if (!client.voice.connections.find(serverid)) {
let channel =
client.channels.cache.find(voiceid) ||
(await client.channels.fetch(voiceid));
if (!channel) return;
const connection = await channel.join();
//slef-deaf
const setSelfDeaf = connection.voice.setSelfDeaf(true);
// slef-mute
const setSelfMeaf = connection.voice.setSelfMute(false);
}
});
update on djs 13 (edited)
Thanks
is there anyway to play a .pls file?
or asx files?
hello like the message right before mine i m here because i dont know how to make my bot join a voice channel and all i try give me an error pls how does it work ?
Hey, client.voice.setChannel(937722527894089807) isnt functioning.
Errorcode:
^
TypeError: client.voice.setChannel is not a function
at Object.cmd_sup [as sup] ```
Can somebody help? 😅
Client is not equal to guildMember. You need to get guildMember class of your bot.
I'm completely struggling to install @discordjs/opus despite having node at the absolute latest version you can install, and npm fully updated
have you tried running with sudo?
That is exactly what I do yes
I managed to find an alternative using normal opusscript for now, which has allowed me to utilize discord's voice feature anyway.
ok nice 🙂
I also think, according to recent bug reports, it's a compatibility issue with linux as a whole
what would be the v13 equivalents of the v11 setVolume(), setVolumeDecibels(), and setVolumeLogarithmic(), if any?
AudioResource.volume#setVolume should be a direct hit
I am using prism-media and attempting to play an audio with play-dl, though I am discovering that it will suddenly stop playing the resource as though it reached the end of its duration. I know other people have utilized ffmpeg and this for the purpose I am trying to use it for, yet don't have this issue. Is there anything I am missing?
newResource = function(Stream,seek){
queue.ffmpeg = new prism.FFmpeg({
args: [
'-analyzeduration', '0',
'-loglevel', '0',
'-ar', '48000',
'-ac', '2',
'-ss', seek || 0
]
})
Stream.pipe(queue.ffmpeg);
queue.resource = djsVoice.createAudioResource(Stream,{
"bitrate":"auto",
"inlineVolume": true,
"inputType": Stream.type
})
queue.player.play(queue.resource);
}```
ask in their support server, maybe they have something special underhood
I'm going to attempt the settings of another individual that I found with the search function you talked to in October, to see if that fixes it
It does not appear that it has, and my ffmpeg settings are now looking quite ridiculous, haha.
newResource = function(Stream,seek){
queue.ffmpeg = new prism.FFmpeg({
args: [
'-ss', seek/1000 || 0,
'-loglevel', '0',
'-acodec', 'libopus',
'-f', 'opus',
'-ar', '48000',
'-ac', '2',
'-reconnect', '1',
'-reconnect_streamed', '1',
'-reconnect_at_eof', '1',
'-reconnect_on_network_error', '1',
'-reconnect_on_http_error', '1',
'-reconnect_delay_max', '30'
]
})
Stream.pipe(queue.ffmpeg);
queue.resource = djsVoice.createAudioResource(Stream,{
"bitrate":"auto",
"inlineVolume": true,
"inputType": djsVoice.StreamType.OggOpus
})
queue.player.play(queue.resource);
}```
I want to move any user, how do I do that?
message.member.voice.setChannel('blah id')
but which member am I moving there?
I dont want to execute it on command such as !move
I have saved the IDs of the people I want to move.
So can I do smth like member.INSERTIDHERE.voice.setChannel('blah id')
` message.member.voice.setChannel('937722527894089804')
^
ReferenceError: message is not defined`
And your code also gives an error
In that case, you need guild id also.
Then do client.guilds.cache.get(guild_id).members.cache.get(memeber_id).voice.setChannel(new_voice_channel_id)
OR you can do with channel ID also.
client.channels.cache.get(voice_channel_id).members.... rest same as above
^
TypeError: Cannot read properties of undefined (reading 'members')
at Object.cmd_sup [as sup] ```
Still not functioning, same error
ids should be strings
how to make bot join a voice channel and play an mp3 in v13?
at Object.execute (C:\Users\User\Documents\EvoBot Reright v13\commands\play.js:143:49)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
C:\Users\User\Documents\EvoBot Reright v13\commands\play.js:149
await channel.leave();
^
TypeError: channel.leave is not a function
at Object.execute (C:\Users\User\Documents\EvoBot Reright v13\commands\play.js:149:21)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
[nodemon] app crashed - waiting for file changes before starting...```
how do i get the voice channel a person is in
follow the guide https://discordjs.guide/voice/
can i get the channel not just id or will i need to fetch the channel
i've been following the discord.js voice recording guide, and the bot joins and tries to start listening. when i'm using prism.opus.OggLogicalBitstream i'm getting an error:
TypeError: failed to downcast any to number
i suspect it has to do with node-crc, because in the OggLogicalBitstream options if i setcrc to false, it makes a recording but it doesn't work
after a few hours my bot just stops playing radio
Debug your dependencies.
Maybe you forgot to do connection.subscribe(player)
Does anyone know how to create a "queue" ? like to prepare the next music our bot will play
How do I turn on the bot's self deafening?
adapterCreator: bot.guilds.cache.get('938447445539577928').voiceAdapterCreator
voiceAdapterCreator is undefined why
HOW DO I GET MY BOT'S TOTAL VOICE CONNECTIONS SIZE?
How can I get the status of the bot's voice stream?
i've tried getting sodium to install via yarn but it keeps saying it can't build it and I require msvs 2015 although I have those build tools
i also have node-gyp installed globally
Is it possible to know why the bot disconnected from the voice channel?(disconnected by someone or error)
i have a problem where when the bot joins the channel its deafened, i tried coding it so it will unmute but it just wont
here is my code: ```js
module.exports.run = async (bot, message, args, guild) => {
const { getVoiceConnections, VoiceConnection, joinVoiceChannel, PlayerSubscription, createAudioPlayer } = require('@discordjs/voice');
const { createReadStream } = require('fs');
const player = createAudioPlayer();
const client_user = message.guild.members.fetch(message.client);
const Member = guild.members.cache.get(message.author.id);
const BotMember = guild.members.cache.get(bot.user.id);
const { join } = require('path');
const { createAudioResource, StreamType } = require('@discordjs/voice');
const connection = joinVoiceChannel({
channelId: Member.voice.channelId,
guildId: message.channel.guildId,
adapterCreator: guild.voiceAdapterCreator,
});
const resource = createAudioResource(createReadStream('./679.ogg'), {
inputType: StreamType.OggOpus,
});
connection.subscribe(player);
player.play(resource);
}
module.exports.help = {
name:"play"
}
I'll check and tell you
anyone know about this
I cant find it how to connect to a vc?
connection = Discord.joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
selfMute: false,
selfDeaf: false
});
How to use new Voice.AudioPlayer(options);
For example if I wanna play the audio of a youtube video
<Player>.play(<AudioResource>)
discordjs.guide results:
• Library: Audio Resources
sm
I'm trying to make my bot play local mp3 files, starting from a certain point, playing for a bit, and then stopping.
I can't find a method anywhere to tell it where to start
The guide explains it
i give up on this, i tried many ways on getting this to work..
const url = googleTTS.getAudioBase64('Hello World', {
lang: 'en',
slow: false,
host: 'https://translate.google.com',
timeout: 10000,
});
const resource = createAudioResource(url);
player.play(resource);
it joins the channel.. i tried local mp3, it worked. but playing a tts is not working...
2nd code:
const url = googleTTS.getAudioUrl('Hello World', {
lang: 'en',
slow: false,
host: 'https://translate.google.com',
});
const resource = createAudioResource(url);
player.play(resource);
3rd code:
const { url } = await request
.get(`http://tts.cyzon.us/tts?text=${speakmsg}`);
const resource = createAudioResource(url);
player.play(resource);
none works
all are giving the above error [ Image ]
$ npm install tweetnacl
doesnt fix the problem
tried it, anyways i will try to figure out something
It says install sodium or libsodium-wrappers, or tweetnacl
i alrdy tried installing those
even did npm install @discordjs/voice libsodium-wrappers
also had a doubt.
in v12 we had events like
const dispatcher = connection.play(url);
dispatcher.once("finish", () => voiceChannel.leave());
is there one to use in v13?
player.on('error', error => {
console.error(error);
});
like rn its this, is there one for finish? instead of error?
ye
Here's a little snippet of my music code, it completely works
The packages possibly needed are: ytdl-core, tweetnacl, ffmpeg-static, @discordjs/voice
ic
thanks!
@coarse summit
so i used this once the play was over
audioPlayer.once(AudioPlayerStatus.Idle, () => voiceConnection.destroy() );
or
audioPlayer.once(AudioPlayerStatus.Idle, () => voiceConnection.disconnect() );
but when i use the command again, all other stuffs work but the bot deosn't join back
nvm got it
Hello. Any tips on preventing my bot from randomly crashing and restarting because of this error when playing audio? I'm using @discordjs/voice v0.8.0 and node v16.13.2 hosted as a background worker on https://render.com/. I'm using ytdl-core v4.10.1 to stream audio from Youtube.
how do i play a direct audio link?
Hey, I am building a discord bot to transcribe voice chats.
Is it possible, and a good idea, to decouple voice streaming and command handling in two different servers?
Like build one server to handle all the user commands and events, and one just to record voice input (and merge the multi-part audio streams and store them in our db)?
Are there any other better ways implemented that I can look at?
Why using 2 servers for that ??
Use Nodejs built in Worker Threads for that
Okay will look into that
thanks!
That's one of main issues of using ytdl for playing music in discord
try discord-player
how would i go about playing a certain mhtz pitch in a vc
make an integration with a website that creates a tone? Or have a couple presets as recordings and play those through the bot
@carmine timber @regal fulcrum Got it. Thank you!
tysm
Anytime! Its why we are here!
no but like how to i play the audio even if i save a recording
Do discord-player uses ytdl-core right ??
Ye, but that dont matter much
Unless youre making a public bot that will get more than 100 servers
But why ytdl-core has that issues and he will face it that there also
which issues?
No, ytdl-core has aborted issues and you can't simply solve using discord-player
theres one issue and thats super easy to fix
this one ^^
Not pretty easy if you play 10 hours song
ive been running my music bot for 6 months without any issues with aborted
you might be playing small videos and of course no live stream support.
who wants live stream audio in a voice channel? Just use youtube for that lol
Many people play lofi songs and wants to create radio bot.
So I think according to your needs, ytdl-core is sufficient but for others it is not.
Lavalink + erela.js is the only other option ive been able to find
and their docs get blocked for being fishy links on my end lol
I think you are new to voice and you have not heard of play-dl.
I mean ive made a full music bot so ive beaten around the bush a bit lol
LOL
play-dl worked horribly for me
but why ??
many issues, now i cant be 100% sure which ones i had but songs just flat out not playing, random skips etc
Looking at play-dl downloads, I think it is pretty successful.
curious: what does play-dl use
It had. New packages have those error. But now it is as fast as Lavalink
is it taking the songs straight from spotify?
ic ic
No youtube search only. But playing youtube is very stable to be honest.
even with yt cracking down on music bots?
It also supports soundcloud for those users
