#archive-voice
30636 messages · Page 23 of 31
So supposing I need to convert it to opus stream, I would need to do more work in order to get the same result, just to proxy live video requests :/
Does anybody tried that before? Proxying youtube live videos from an express.js app rather than ytdl into discord.js directly
But why do you want to proxy videos from express.js ??
Why are you ignoring ytdl-core ??
You can use play-dl [ Great Alternative to ytdl-core ]
I cannot run ytdl from my Vps because its ip would get banned (from experience, multiple times). Instead, i use a homelab server running a dynamic ip. That's why @carmine timber
Then create a proxy at your homelab server and use proxy in ytdl-core. EZ
That's much efficient way to do it, rather than using express.js to send requests.
Ok nevermind
i will ask somewhere else
Hello!, I created a tts command for voice channel but when the command is used once and the bot is used again it crashes and to use it again the bot has to restart
In theory, what is the maximum amount of users a bot could listen to all at once in a single voice channel. 👀
On an unrelated note, why does https://github.com/discordjs/voice/releases not have the most up to date version of djs voice? I believe the most up to date version is 0.7.4 yet the most up to date downloadable version is 0.7.5 
That is limited to discord
can somebody explains why the bot is not reproducing the audio ?
const { joinVoiceChannel, createAudioPlayer, createAudioResource, generateDependencyReport } = require('@discordjs/voice');
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
const player = createAudioPlayer();
const resource = createAudioResource('./assets/test.mp3')
player.play(resource);
console.log(generateDependencyReport());
i already have all the intents
There maybe 2 errors in your code :
-
The path you provided is a relative path, convert it to absolute path.
-
You might be missing
GUILD_VOICE_STATESintent.
Then it is 1st error only.
how can i use absolute path?
like that?
const {resolve} = require("path");
const resource = createAudioResource(resolve('./assets/test.mp3'))
yep that should work.
nothing happens :/
bot join in call
dont reproduces any sound
0 errors on console
I think you forgot to add extension of test file.
already fixed that
Ok so console log this
const fs = require('fs');
filenames = fs.readdirSync('./assets/')
filenames.forEach(file => {
console.log(file);
})
Do you see test.mp3 there ??
yep, all files in assets folder
player.on(AudioPlayerStatus.Playing, () => {
console.log('playing');
});
I put this in the code and the console registered
but nothing plays
Can you do console.log(resource.edges) ??
@carmine timber
It says it is playing.
bot not reproducing
Did you forgot to do connection.subscribe(player) ??
where @carmine timber
const { joinVoiceChannel, createAudioPlayer, createAudioResource, generateDependencyReport, NoSubscriberBehavior, AudioPlayerStatus } = require('@discordjs/voice');
const {resolve} = require("path");
const audio = resolve('./assets/test.mp3')
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
const player = createAudioPlayer()
const resource = createAudioResource(audio)
player.play(resource);
console.log(resource.edges)
//console.log(generateDependencyReport());
player.on(AudioPlayerStatus.Playing, () => {
console.log('playing');
});
const { joinVoiceChannel, createAudioPlayer, createAudioResource, generateDependencyReport, NoSubscriberBehavior, AudioPlayerStatus } = require('@discordjs/voice');
const {resolve} = require("path");
const audio = resolve('./assets/test.mp3')
const conn = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
const player = createAudioPlayer()
conn.subscribe(player)
const resource = createAudioResource(audio)
player.play(resource);
console.log(resource.edges)
//console.log(generateDependencyReport());
player.on(AudioPlayerStatus.Playing, () => {
console.log('playing');
});
that's work, thanks ❤️
👍
Is there any built in functionality for moving the bot between voice channels?
Documentation suggestion for @vocal lion:
VoiceState#setChannel()
Moves the member to a different channel, or disconnects them from the one they're in.
<Guild>.me.voice.setChannel()
Thanks man, apparently i suck at searching through the docs
Can someone help me figure out why my music bot sometimes randomly loses connection and leaves/goes to next song in queue?
Due to attachment of multiple events to AudioPlayer I guess.
hello, can i anyone help with html website add discord server total members count?
Documentation suggestion for @red totem:
Client#guilds
All of the guilds the client is currently handling, mapped by their ids - as long as sharding isn't being used, this will be every guild the bot is a member of
<Client>.guilds.cache.size
Can we do it in dms? or in a private server that the bot itself is in?
private server is better option.
Great, I'll send you the invite
ok
can you create an hls audio resource from .m3u8?
how to do filters? i do not know much do you do them with ffmpeg static
Now what’s this👀
Is it the same?
Because it happens only at night when i go to sleep, and the rest of the day it works normally
Cant say anything abt that
Anyhow its not related to djs so you should ask somewhere else
How can I catch this error?
for (let i in qu) {
let roomid = qu[i].roomID;
let room = client.channels.cache.get(roomid);
let connection = joinVoiceChannel({
channelId: room.id,
guildId: room.guild.id,
adapterCreator: room.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
let rand = audio[Math.floor(Math.random() * audio.length)]
let resource = rand...
connection.subscribe(player);
player.play(resource);
// ...
}``` I did this to play the same audio in all rooms but it's not working
client.on('voiceStateUpdate', (oldMember, newMember) => {
console.log("Someone joined one channel")
let newUserChannel = newMember.channel.id
let oldUserChannel = oldMember.channel.id
if(newUserChannel === "916075568766804008") {
// Benutzer joint dem Move channel
console.log("Joined the Move channel!")
}
});
Does anyone know what is wrong here? The event is not getting triggered (its in index.js)
Do you have guildVoiceStates intent?
To follow up on this. The solution to my problem was that I needed to ensure that the stream I was passing to createAudioResource was in object-mode. It also helps if the highwatermark is set to something like 12 which is what was used by default in v12. Hope it helps for anyone.
You are creating a new player for every room.
how to make bot join voice channel using id
Documentation suggestion for @lament sail:
ChannelManager#cache
The cache of Channels
client.channels.cache
Is there any way to seek audio ? Bcs the seek option was removed after v13. And ffmpeg's -ss option don't seem to be doing anything.
Show me your ffmpeg -ss code. I think you have some issues there.
Well I disabled it but I just used ffmpeg as this: "ffmpeg -ss <time to seek> -i <input url> ..some other options" than I piped it to stdout and into discord.js
some other options is just options that discord.js is and was using
I lyterally copied the seek option from v12
You can try this. I think this should work fine.
Well, there is only one option I am not using -accurate_seek
Maybe that could help you.
I am gonna try that
because it’s inside for loop?
So it will create different player and choose random string in audio array.
So you can't play same audio like this
const player = createAudioPlayer();
let rand = audio[Math.floor(Math.random() * audio.length)]
let resource = rand...
player.play(resource);
for (let i in qu) {
let roomid = qu[i].roomID;
let room = client.channels.cache.get(roomid);
let connection = joinVoiceChannel({
channelId: room.id,
guildId: room.guild.id,
adapterCreator: room.guild.voiceAdapterCreator,
});
connection.subscribe(player);
// ...
}
@subtle granite
hmmm
but it will play before it connect 🤔
I’ll try it
You can play it after it is done doing for loop also.
Yes I’ll try ty
Thanks a lot it works !
👍
one question @carmine timber
Ask
It will create an audio player for every channel and play the same audio, or it will only create one player?
because i don't want to get banned because of sending requests to yt
It will create only one player and play it across all connections.
Great
Ty!
Well, I have another problem, when I try to join 2nd bot to a channel and 1st bot is alredy joined somewhere in the guild, it will join the 1st bot instead and remove it from the 1st channel.
Are you running the bots in the same project?
yes
I tryed to remove discord.js modules from require.cache and for each bot use new required module but that didn't work
You have to specify the group when joining the channel
nah ?
I need to specify a group for each bot ?
Else the voice package assumes it’s the same bot
The adaptercreator should be different according to client running.
oh okey I'll try that
e.g. joinVoiceChannel({ …, group: client.user.id })
group ID are only used for storing purposes only. You need separate adapterCreator for connection from different client ID.
You might be wrong about group ID.
thx works
nah It was coused by the groups, I set each group to be username of bot and it works
Error: Initial Player Response Data is undefined.```
Ask play-dl support server, this is discord.js voice support server.
they have a server?👀
Yup in their README, there is a link for their server.
client.on('ready',async () => {
//...
const player = createAudioPlayer();
for (let i in qu) {
//...
let room = client.channels.cache.get(roomid);
let connection = joinVoiceChannel({
channelId: room.id,
guildId: room.guild.id,
adapterCreator: room.guild.voiceAdapterCreator,
});
connection.subscribe(player);
}
///////
player.on(AudioPlayerStatus.Idle , async() => {
let resource = ...
player.play(resource);
});
/////////
let resource = ...
player.play(resource);
});``` I'm doing this to play an audio in all channels with one audio player ...
client.on('messageCreate',async message => {
if (message.content.startsWith('Vc')) {
let qu = JSON.parse(fs.readFileSync('./qu.json'));
let m = message.member.voice.channel;
const player = createAudioPlayer();
/////////
let connection = joinVoiceChannel({
channelId: m.id,
guildId: m.guild.id,
adapterCreator: m.guild.voiceAdapterCreator,
});
/////
let resource = ...
connection.subscribe(player);
player.play(resource);
qu[message.guild.id] = {
roomID: m.id,
serverID: m.guild.id
};
////////////
player.on(AudioPlayerStatus.Idle , async() => {
let resource = ...
player.play(resource);
});
}
})```
and if I want to add a room to json, I'll have to create a new audio player to play the audio
Is there any way to add it to json and listin to the audio without creating new audio?
Does someone know how to fix that
^
Error: Cannot destroy VoiceConnection - it has already been destroyed```
Does anyone know how to play a internet radio stream/mp3/icecast?
can anyone help me with disconnecting my bot from a voice channel?
<VoiceConnection>.destroy() to disconnect.
that doesn't work for me
Can you show code?
I'm a bit confused by <VoiceConnection>
That's where you insert your VoiceConnection object. You can store it as the return value of your joinVoiceChannel() function.
could I have an example?
const connection = joinVoiceChannel({
channelId: <Channel>.id,
guildId: <Channel>.guild.id,
adapterCreator: <Channel>.guild.voiceAdapterCreator,
})
connection.destroy()
That's joining and leaving.
okay thank you so much! I got it working
connection.disconnect() also works
also if you don't mind me asking how I can check if the bot is currently in a vc?
You can check if connection.state.status is equal to 'ready'. That means it's in a channel and ready.
thank you, I'm using this to check if my bot is connected to a vc to disconnect it, but when I use my disconnect command again it makes the bot join the vc again
Are you sure you're not calling joinVoiceChannel() again after you have disconnected?
this is my code if you need to see it
else if (message.content == (cmd + 'disconnect'))
{
const voiceChannel = message.member.voice.channel;
if(voiceChannel)
{
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
if (connection.state.status == 'ready')
{
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
connection.destroy();
return message.channel.send("*Left VC*")
}
else if (!connection.state.status == 'ready')
{
return message.channel.send("I'm not in a VC")
}
}```
Yeah, so the joinVoiceChannel() function makes the bot join. You only need the connection.destroy() part to make it leave. That's why it's rejoining.
alright, so where would I put this in my code?
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
i used the example "Music Bot" and changed it a bit to play audio files from local folder. However, sometimes the song just stops and it skips to the other one. is there a way to prevent sudden breaks?
I'm having a lil issue with my bot not being able to play live music.
It works fine playing non-live music but when i try to play a live video, it plays like 2 seconds and then gets stress (leaves the voice channel)
Code: https://www.toptal.com/developers/hastebin/uhinibagoj.typescript
- pls ping me if someone replies
Issues with ytdl-core
I recommend switching to play-dl
Code?
What’s the difference between ytdl-core and play-dl
Play dl was specifically created to fix the shortcomings in ytdl and for making discord bots
Also supports mutiple sites not just only YouTube
Does it support Spotify?
Yea
Do you know how i can make it play a spotify link with play-dl?
Join the play-dl support server, lets not discuss it here anymore
how to make my bot join a voice channel
joinVoiceChannel
const { joinVoiceChannel } = require('@discordjs/voice');
const connection = joinVoiceChannel({
channelId: //channel id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator
});
ty
Does anyone have an example of how to use ffmpeg audio filters?
I am having a hard time trying to figure out how to install discord voice
am i using the right command?
i wrote that command but it still didnt install
someone help
Delete node modules folder and type npm i
anyone have a idea how to send the current user voice channel id from backend to frontend
What do you mean by from backend to frontend ??
im making a music dashboard and im stuck at this problem
i can't figure out to send user voice state to frontend
Oh I see.
So just get guild class from anywhere and do <Guild>.members.fetch('userID')
You will now get a guild member Class
Then you can simply do <GuildMember>.voice.channel.id
OR
if you have GUILD_VOICE_STATES intent, then you don't require to fetch it.
You can simply do [guild.members.cache.get('ID').voice.channel.id]
to be honest i don't even know how to make this work
i fell in a bunch of loop hole that i need to solve
??
hmm i already fixed it my friend 👍
my bot joins the vc, its pfp has the green ring, leaves after one second. https://sourceb.in/TZwtSoOMsh
the audio file is 3 minutes long, here it is
please ping me so I can guarantee i can see the response, i have to log off now
I'm having some issues with my bot not playing music all the way. https://github.com/OliverAThunes/Jukebox-Boy-V2/blob/main/commands/play.js
For some reason on some songs it will play about a second of it and then stop
I think it might be that it's experiencing some packet loss and instantly giving up but I don't know how to configure that, could anyone help?
Anyone know how to fix ?

Ytdl core issue
is there a way for me to fix it?
Maybe use play-dl
My livestream stop playing after few seconds
const stream = await ytdl(this.songs[0].url, this.songs[0].live ? { isHLS: true, dlChunkSize: 0 } : { filter: 'audioonly', quality: 'highestaudio', dlChunkSize: 0, highWaterMark: 1 << 25 });
fixed with play-dl
is there a way to prevent 403 errors
403 = forbidden
dont play private videos
I have an issue: my bot joins the vc, its pfp has the green ring, leaves after one second. https://sourceb.in/TZwtSoOMsh
the audio file is 3 minutes long
please help
heres a recording of the error
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: server.id,
adapterCreator: server.voiceAdapterCreator
});
```With this, how do i send a reply only if the bot actually joins the voice channel (meaning it wasn't in it before)?
err?
no visible error in the console @manic vault
is it playing an audio?
its supposed to
i sent a video of what happened @manic vault
it didn't play the audio
it did not
that's why
wym? how fix
@manic vault
https://sourceb.in/TZwtSoOMsh this is whats supposed to happen (this is the play command)
r u sure the audio module is '../halloween.mp3'
Pretty sure the path is in relation to the working directory, not the file it’s called from
If you want a path relative to the file, use path.join(__dirname, relativePath)
ohhhh ok i guess it liked ./halloween.mp3 better than ../
thank you
it does sound staticy though, how can i fix that?
I have 2 issues:
- Whenever I use my play command while a song is currently playing, the bot will crash.
- It sounds a little staticy
Second one I can't help, but if you show code perhaps I could help with the first.
@rugged sky Thank you! Here is my play command: https://sourceb.in/aGZXd0Cr1E
What error message do you get when the bot crashes?
@rugged sky my bad, i don't get an error, but it just switches the song. i want it to play the song after the song that is currently playing is done. kind of like a queue
Well the code you currently run is designed to create a new connection and AudioPlayer every time you run the command so that will just discard whatever you had. If you want it to queue just check if the bot is already playing and, if so, create a only a new audio resource for the next song and put it into an array that you can access. Then in your player's .on('idle', () => {}) function just make it play the next song in the queue if there is one.
hi, is there a way to detect the green circle lighting up for voice chat?
does anyone know how to solve this problem?
I'm installing sodium package, suddenly this error appears
Install libsodium-wrappers instead of sodium. Sodium is tough to install on windows.
https://github.com/discordjs/voice/releases/tag/v0.6.0
voiceConnection.receiver.speaking.on('start', userId => console.log(`User ${userId} started speaking`));
voiceConnection.receiver.speaking.on('end', userId => console.log(`User ${userId} stopped speaking`));
Okey thanks, for helping me
ty
Not sure but you could maybe use try, catch or check if it actually Returns a connection
I found a solution, thank you though
How to make bot join vc user is in?
How can I fix this error?
I have it every times 🤔
So the problem is from this package 😕 . Using lavalink will fix it
Hey guys, I am new to Discord.js Voice and trying to figure out if I can use 2 AudioPlayers at the sametime. Since, I am not sure how to describe what I want to do, here is an illustration of it :
I also am not sure about the logic of using 2 AudioPlayers, there may be an easiyer way to do this.
For example: The Bot plays a song and it has to play a sound effect for X reason (interrupt the song) and then it has to unpause (continue) the song
I think it should work 100%. What is the error that you are facing ??
How do I change the volume of the music playing in a voiceChannel, provided I have the voiceChannelID
how did you do it?
I`m new Into Discord JS and I wanted to ask something:
I want the Bot to join the voice channel, if the message.member is in a channel, but when the member isn't I want him to write a message
Does the "node-crc" package need to be installed?, I can't install it because of an error
The Bot joins my Voice Channel, but if i change my channel and type my command again, he's joining the channel where I was before
Why would you need that package?
Show code
I think he isn't updating the state "message.member.voice.channel"
Try logging it
https://github.com/discordjs/voice/tree/main/examples/recorder
I want to use it for voice recorder like this on github
What error are you getting?
in package.json it says "node-crc" but when I try to install an error occurs
Did you enable the guild voice states intent?
What error?
ok i will try
I didn't, now it works thank you 🙂
It doesnt play the audio when I unpause the AudioPlayer 1
hello
I have made tts bot for about 3 hours.
When I install @discord.js/voice and import them, tsc started returning below errors.
#11 13.34 node_modules/@discordjs/voice/dist/index.d.ts(2,8): error TS1192: Module '"/usr/src/app/node_modules/prism-media/typings/index"' has no
default export.
#11 13.34 node_modules/@discordjs/voice/dist/index.d.ts(5,8): error TS1259: Module '"/usr/src/app/node_modules/@types/ws/index"' can only be default-imported using the 'esModuleInterop' flag
(I've aimed to package the bot with Docker. So the errors was displayed when I built docker image)
How can I resolve the errors?
The codes what I had written is here (partial):
import { joinVoiceChannel, getVoiceConnection, createAudioPlayer, VoiceConnection } from "@discordjs/voice";
client.once("ready", async () => {
const channel = client.guilds.cache.get("")?.channels.cache.get("");
if (!channel) return;
joinVoiceChannel({
channelId: "",
guildId: "",
adapterCreator: channel.guild.voiceAdapterCreator
});
connection = getVoiceConnection(channel.guildId) ?? null;
});
the dependencies in packages.json are:
"dependencies": {
"@discordjs/voice": "^0.7.5",
"@types/ffi-napi": "^4.0.4", /* not related to this problem */
"discord.js": "^13.3.1",
"ffi-napi": "^4.0.3", /* not related to this problem */
"libsodium-wrappers": "^0.7.9",
"typescript": "^4.5.2"
}
I installed the packages following discord.js guide.
https://discordjs.guide/voice/#installation
npm install @discordjs/voice libsodium-wrappers
sorry
I solved
I should use require() instead of import
Hey.. if i want to play music on my bot this error occurs
That's my code
I can’t find any fix
I've created an audioPlayer but now i've got a new problem:
The error tells you that whatever you're attempting to call play on is null, so I'm guessing your AudioPlayer isn't initialized correctly.
Is it just me or this was working earlier but now the bot wont join my voice channel after this is executed?
this code is working for me:
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
})```
I see. I figured it out. I did <Interaction>.channel.id, which is the textChannel, not voice. Thanks!
Do you know how i can use AudioPlayer to play music from an YouTube - URL?
👀?
Use ytdl , play-dl
Anyone have any stats on the performance decrease with inlineVolume? I want to change the volume on creation because it always starts too loud for people
Very rare server side issues
Does any knows the name for the listeners for the audioplayer class? like ```
<AudioPlayer>.on('finish', () => {console.log('song finished!')})
idle
The only events are the names of the AudioPlayerStatus and stateChange
I see, so if a song starts it would be AudioPlayerStatus.Playing?
Yea
thanks!
Hey guys, sorry to bother with such a dumb question but can someone tell me how can I move client from X voice channel to Y voice channel ?
Currently, trying with setChannel function but if I understand it correctly, it is used for users and not for the client
I think, u would just use the joinVoiceChannel(channel) again with a different channel
That is what I was doing but I am trying to make a low-level voice recognition bot and for some reason it doubles the connection when I use joinVoiceChannel()
For example: When I say "hello world", It prints it on console. If I move the client on my own manually, it works fine else if I use joinVoicechannel for second time it will print whatever I say twice
you may be attaching a event twice to voice channel.
When you run joinVoiceChannel again, instead of destroying old connection, it converts your old connection to a new connection with same events attached. So you might be attaching same events to a connection.
I was thinking the same thing yet struggling with it for a while now.
Apparently it is caused by a function that I found on internet to connect a voice channel. I do not know at all why I did look for a function on internet when there is already a function that is very simple (joinVoiceChannel) provided by Discord...
async function connectToChannel(channel) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false,
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
return connection;
} catch (error) {
connection.destroy();
console.log(error)
}
}
But I would be glad if someone explains me why this function caused such a problem
ty tho
What is the issue you are facing right now ??
It works fine know. I just replaced the above function with a simple joinVoiceChannel()
Can anyone help me, this is the problem I found while trying to voice record according to github : https://github.com/discordjs/voice/tree/main/examples/recorder
but I changed to JS file
Remove entersState function from your code
TypeError: Cannot read properties of undefined (reading 'getSubcommand')
What does that mean?
case "play": {
client.distube.playVoiceChannel(
VoiceChannel,
options.getString("query"),
{ textChannel: channel, member: member }
);
return interaction.reply({ content: "🎼 Anfrage eingeganen." });
}```
That's my getSubcommand
Hello, is the @discordjs/voice package are TypeScript ready ?
I just installed it with NPM, along side with @discordjs/opus and sodium.
So, the currently installed version is :
@discordjs/voice v0.7.5, @discordjs/opus v0.5.3 and sodium v3.0.2
I try to check if there , now all of my builds are failing with these error :
Module '"${ProjectPath}/node_modules/prism-media/typings/index"' has no default export.
- From : ${ProjectPath}/node_modules/@discordjs/voice/dist/index.d.ts, Line 2
Module '"${ProjectPath}/node_modules/@types/ws/index"' can only be default-imported using the 'esModuleInterop' flag
- From : ${ProjectPath}/node_modules/@discordjs/voice/dist/index.d.ts, Line 5
I didn't even import anything from the @discordjs/voice package yet, as adding voice support to my bot was still only a plan.
Should I just forcefully silence the above TypeScript errors ?
I'm on TypeScript v4.4.4
If you want to remove all those errors, switch to discordjs/voice@0.6.0
I quickly switched my environment to use TypeScript v.4.5.2, the issue still appears.
Well I do can apply a hot patch by changing those lines (that throws the compilation errors) to not use default export, or importing with wildcards.
But well, it is not a good way as NPM is configured to check and install for available updates every 24hours
So just create a issue at repository.
Hmmm that is a good idea, hope it is a valid issue
Issue posted :
#858851078534987776 message
at Socket.<anonymous> (/home/runner/Beta/node_modules/@discordjs/voice/dist/networking/VoiceUDPSocket.js:120:52)```what is that
how can i get a list of users playing a discord activity? Eg Poker Night
You should ask that in #djs-help-v14
I get "error: The Operation was aborted" when i disconnect bot manually
is there a way to fix?
Is there a way to pipe the audio input that is received from discordjs/voice back into the bots output? Essentially creating a bot that echos the audio of a user?
I've made a couple of attempts but am not super familiar with handling audio streams
Remove entersState function from your code. EZ Fix
Yep
// You can re-use the Opus stream, e.g. to play in another channel as an echo
const resource = createAudioResource(opusStream, { inputType: StreamType.Opus });
this is just what im looking for!
Is joinChannel still a function? or is is joinVoiceChannel now?
So i'm getting the "User user_id started/stopped speaking" in my console, but i dont hear any playback through the bot
here's the basic setup
const voiceConnection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
selfDeaf: false,
selfMute: false,
adapterCreator: channel.guild.voiceAdapterCreator,
});
console.log(voiceConnection)
voiceConnection.receiver.speaking.on('start', userId => console.log(`User ${userId} started speaking`));
voiceConnection.receiver.speaking.on('end', userId => console.log(`User ${userId} stopped speaking`));
// A Readable object mode stream of Opus packets
// Will only end when the voice connection is destroyed
voiceConnection.receiver.subscribe(userId);
// A Readable object mode stream of Opus packets
// Will end when the voice connection is destroyed, or the user has not said anything for 100ms
const opusStream = voiceConnection.receiver.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
// -------------------------
// You can re-use the Opus stream, e.g. to play in another channel as an echo
const resource = player.play(createAudioResource(opusStream, { inputType: StreamType.Opus }));
I've tried with/without the player.play() at the end
You are subscribing twice
Remove This line
voiceConnection.receiver.subscribe(userId);
how can I request the bot in a call?
You can't discord's limitation.
like this? this is on the developer site
Show me
?
I have no entersState function
Show me your code
I’m using the package discord-player
I posted my problem here and they redirected to here
discord-player is using entersState function. Tell them to remove it.
And also tell them to make their own entersState function.
Tell discord-player developer to remove entersState function. Otherwise make your own discord music bot without discord-player.
Hmmm 🤔
It’s so hard?
no it is easy
Ok I’ll create my own
at Object.run (C:\Users\55849\Desktop\botds\commands\play.js:17:33)
at Client.<anonymous> (C:\Users\55849\Desktop\botds\index.js:26:21)
at Client.emit (node:events:402:35)
at MessageCreateAction.handle (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\actions\MessageCreate.js:25:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\websocket\WebSocketManager.js:350:31)
at WebSocketShard.onPacket (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
at WebSocketShard.onMessage (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
at WebSocket.onMessage (C:\Users\55849\Desktop\botds\node_modules\ws\lib\event-target.js:199:18)
at WebSocket.emit (node:events:390:28)
Is it just installing the dependencies that I will be able to run the command?
No read guide completely
Thank you very much
Hi, I wanted to make sure that when a player joins a voice room it creates a new voice room and moves him into it but I get an error message
client.on("ready", () => {
const channel = client.channels.cache.get("918037148635136010");
if (!channel) return console.error("The channel does not exist!");
channel.join().then(connection => {
// Yay, it worked!
console.log("Successfully connected.");
}).catch(e => {
// Oh no, it errored! Let's log it to console :)
console.error(e);
});
});
error message :
Uncaught TypeError: channel.join is not a function
I'm probably just overlooking something, but Is it possible to get the JoinConfig properties from a VoiceConnection after it's been created? I absolutely was.
channelId: interaction.member.voice.channel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
})
const player = createAudioPlayer()
const resource = createAudioResource('../../music/FunkyMusic.mp3')
const subscription = connection.subscribe(player)
player.play(resource)
player.on('error', err => {
console.error(err.message)
})```
Absolutely nothing happens
Well it does connect
Do you have the GUILD_VOICE_STATES intent?
I have all intents enabled so ig yes
I'd suggest you make the path to your resource absolute, I don't think it does relative paths.
Oki ill try that
Ok that worked ty
Are there ways to boost audio quality
Hey! So I am having this odd issue with the voice lib, I can obtain packets of audio from a internet stream via axios, and pipe them into a buffer to be read, but at random times, the voice lib will just, stop playing audio. As in, I am still sending packets to the stream buffer to be read, but d.js just, stops handling them. It doesn't emit an event, doesn't close, just hangs there
My current theory is that when I have silence while switching tracks (the stream I pipe in does a crossfade, but some tracks have a little silence) that it stops playback
From what I can tell, there is zero option or configuration for this behaviour, but I'm hoping I'm wrong, because this is annoying
you should be piping audio data to a stream.Passthrough since using only a Buffer is not efficient. If a track ends and you intend to continue, you should pipe silence packets until the track finishes loading.
I am
And as for the silence packets, a little hard to do that- because the audio server is on a different machine, streaming via libshout, to icecast
I suppose I could write a small script to check for a lack of lengthy bytes in the packets and do it that way
a shoutcast/icecast server should be sending audio constantly. Once a stream.Readable ends, then it emits the end event which is what causes the AudioResource to be destroyed.
See, that's the thing
It is sending it constantly. That's what doesn't make any sense with the lib
I have literally logged the chunks being read, and it'll just suddenly stop sending the audio out to discord
if I completely reset the audio player, ie: new AudioPlayer() and do it again, works fine
Are you logging end events and such
Yep.
I personally have no issues with frisky.fm which is icecast
The only difference with the stream I have is it uses an adaptive bitrate, which I think may be breaking the lib

that could be possible since it expects a bitrate of 48000. You could pipe through ffmpeg constantly with the args
aresample=48000
At least, I think thats how you resample in ffmpeg
The reason I don't do that from the stream side is because some of the tracks are quite old, like 1988 old- and sound horrid upscaled
I'll see what I can do though

It may be one of those things where I write a custom lib for it, just wanted to try avoiding that to not reinvent the wheel lol
Shouldn't really be necessary. ffmpeg probably has some args to preserve as much as possible, but just offer compatibility
I'll take a look into it- it has some args I've tried, but it ends up stretching out the audio in funny ways- I'll message a friend of mine who is far more knowledgeable on ffmpeg
I would also recommend taking a peek at some other projects to see if they face the same issue as you. I wrote a little something you can look at AmandaDiscord/Volcano on github. Assuming you want to. I'm curious myself because as far as icecast goes, I've only tested frisky.fm
For sure, I'll take a look tomorrow, I've gotta get back to studying for a redhat cert exam; It's probably one of those things that is simple, but not immediately thought of fix wise - thanks for the help/pointers!
👍
Hey guys, a question for who uses ytdl-core to play music from Youtube. Did you ever encounter this error ? Apparently it is a very common issue and I kind a feel stack. I am open to any workarounds or alternatives or any other solutions
Does anyone know why the audio player isn't firing off any events? There are no errors reported in console but nothing is firing
I attached the code
This segment of code is initialized upon bot startup
I'm working on a bot that can take my audio input and echo it. This is what I have.
channelId: channel.id,
guildId: channel.guild.id,
selfDeaf: false,
selfMute: false,
adapterCreator: channel.guild.voiceAdapterCreator,
});
voiceConnection.receiver.speaking.on('start', userId => console.log(`User ${userId} started speaking`));
voiceConnection.receiver.speaking.on('end', userId => console.log(`User ${userId} stopped speaking`));
voiceConnection.receiver.subscribe(userId)
const opusStream = voiceConnection.receiver.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
const resource = createAudioResource(opusStream, { inputType: StreamType.Opus });
It logs User x started speaking and User x stopped speaking but still no audio is coming from the bot. Anyone have an idea why?
It may be a dumb question but did you subscribe to your AudioPlayer ?
I did
Did you played anything in audio Player ??
Yes we did encounter those errors and we shifted to play-dl
Hello I'm playing a local mp3 file with @discordjs/voice but couldn't figure out the way to implement seek feature, can anyone help?
how do i make the bot leave the voice channel it is currently in?
nevermind..
.
Just use ffmpeg
I do
Hi guys, do anyone have issues with AudioPlayer constantly firing Idle, Buffering, Playing event ?
It only happens randomly at me, but it hangs the whole bot, as it keeps looping and taking 25% CPU usage (All available for the NodeJS instance).
The error occurs when the current song is ended, I then create a new AudioResource and then assign it to the existing AudioPlayer.
When it works, the bot starts playing the new song.
When it fails, the bot starts going from Idle -> Buffering -> Playing -> Idle -> Buffering -> Playing -> ....... (it's a constant loop)
My audio source is a localfile, I used my own youtube management API as YTDL wasn't reliable, and fetching details from the YouTube Data v3 API is costing quotas, I had make sure the local audio source file are not corrupted, infact, it plays just fine atleast, until at some point the AudioPlayer goes crazy
I noticed the issue as I was subscribed to the debug event.
My queue system listens for Idle and Playing events, so when the AudioPlayer went weird, it can flush all song in the queue in less then a second 😄
Or when the queue is on loop, it'll loop forever !
In the meantime, I had implemented a rate limit, so the bot will not try to load a new song if the olderSong was not completed yet.
Well, it helps a bit, but the audio player still loops there.
For my curiosity, I put a :
ConnectionInfo.AudioManager.player.on('debug', (messagess: string) => {
globalThis.Debug.Debug.Debug.log('AudioPlayer Debug : ', messagess);
});
and this is what is logged, when the bot is on loop for 1 second :
from {"status":"playing","missedFrames":0,"playbackDuration":100,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}
AudioPlayer Debug : state change:
from {"status":"buffering","resource":true,"stepTimeout":false}
to {"status":"playing","missedFrames":0,"playbackDuration":0,"resource":true,"stepTimeout":false}
AudioPlayer Debug : state change:
from {"status":"idle","resource":false,"stepTimeout":false}
to {"status":"buffering","resource":true,"stepTimeout":false}
AudioPlayer Debug : state change:
from {"status":"playing","missedFrames":0,"playbackDuration":100,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}
AudioPlayer Debug : state change:
from {"status":"buffering","resource":true,"stepTimeout":false}
to {"status":"playing","missedFrames":0,"playbackDuration":0,"resource":true,"stepTimeout":false}
AudioPlayer Debug : state change:
from {"status":"idle","resource":false,"stepTimeout":false}
to {"status":"buffering","resource":true,"stepTimeout":false}
AudioPlayer Debug : state change:
from {"status":"playing","missedFrames":0,"playbackDuration":100,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}
AudioPlayer Debug : state change:
from {"status":"buffering","resource":true,"stepTimeout":false}
to {"status":"playing","missedFrames":0,"playbackDuration":0,"resource":true,"stepTimeout":false}
AudioPlayer Debug : state change:
from {"status":"idle","resource":false,"stepTimeout":false}
to {"status":"buffering","resource":true,"stepTimeout":false}
....
Sadly discord do not allow longer messages.
It doesn't have any kind of issues if it wasn't randomly looping when on song switch
Can we see the code that you use when you assign new audio Resource to existing AudioPlayer ??
Yep sure !
// Since there is still another song in the queue, start playing again.
// Load the music data object for that song
let SongData : PlaylistItem = ConnectionInfo.Queue[0];
if (SongData.sourcetype !== "local" && !SongData.localsource) {
// Song is not from local, and it was not cached yet.
message.channel.send(`Please refill the TirtaAPI wallet again, the song is not decrypted successfully !!!!!`)
return;
}
// It was a local song, load it !
const RawSongData : AudioResource = createAudioResource(SongData.localsource);
// Use the duration of the song and store it in the song data object
SongData.duration = RawSongData.playbackDuration;
// Update the ConnectionInfo queue with the SongData
ConnectionInfo.Queue[0] = SongData;
ConnectionInfo.CurrentState = "PREPARING"
// Update the ConnectionInfo
MusicModuleData.ActiveNodes.set(ConnectionInfo.GuildID, ConnectionInfo);
// Play the song
ConnectionInfo.AudioManager.player.play(RawSongData);
So the ConnectionInfo.AudioManager is a variable that holds PlayerSubscription object, the code :
ConnectionInfo.AudioManager = connection.subscribe(createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play
}
}));
In normal behaviour this happens on the AudioPlayer's debug listener :
AudioPlayer Debug : state change:
from {"status":"idle","resource":false,"stepTimeout":false}
to {"status":"buffering","resource":true,"stepTimeout":false}
AudioPlayer Debug : state change:
from {"status":"playing","missedFrames":0,"playbackDuration":192640,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}
Which seems to be perfectly normal, since when the song ends, it switches into Idle, and when the new song is loading, it's at buffering, less than 1 second, it was on playing.
However, when the random loop occurs, after it was on playing state, it just quickly go into Idle and the whole state cycle repeats
One thing that I noticed, when the AudioPlayer's is somehow goes into infinite loop when I assign a new AudioResource, this happens on the debug listener:
from {"status":"playing","missedFrames":0,"playbackDuration":100,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}
That's playing the exact same song (Yes, I use the bot to repeat the same song for a lot of hours, and it's kind of annoying when at random times it just goes into infinite loop)
Currently it's playing I put gas gas gas over a police chase which is around 3minutes ish (which seems to be correct: "playbackDuration":192640.
When the looping starts, that playback went weird : "playbackDuration":100, my 3 minute song is now 100ms ? 😄
I was not sure if my current way is the best way to re-assign a AudioResource over to an existing AudioPlayer
I'm open to any suggestions 🙂
In the meanwhile, the bot is correctly looping the queue.
hi i need to detect when a bot has finished reproducing: ```js
const player = createAudioPlayer();
const resource = createAudioResource(Readable.from(await tts.get({ text: message.content, lang: row.lang || 'en-us', limit_bypass: true })))
player.play(resource);
connectionVoice.subscribe(player);```
I closed my issue, resolved by deleting all of my project node_modules and then running npm install again, it never happened to me before that the node_modules was somehow corrupted (?), but it resolves my issue !
How to kick a user from voice channel
That is possible with discordjs package, not discordjs-voice :
https://discord.js.org/#/docs/main/13.3.1/class/VoiceState?scrollTo=disconnect
I want to have a really big duration parameter here, so that long silences are also filled in the stream. but can't have due to interger overflow, also can't use BigInt here
end: {
behavior: EndBehaviorType.AfterSilence,
duration:10000000000,
},
});
is there any workaround that
a little context here: I want to build a bot that can record the VC audio,
i tried using EndBehaviourType.Manual , but then, silences are automatically clipped in stream and i dont want that
How can i make a queue with @discordjs/voice
is there a permission or something that wouldn't allow my bot to play audio in a channel?
how do i make the bot to connect to a channel
const voiceConnection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
selfDeaf: false,
selfMute: false,
adapterCreator: channel.guild.voiceAdapterCreator,
});
whats a good lavalink client as of now? I feel like erela.js isnt gonna work for me?
Error TypeError: Cannot read properties of undefined (reading 'adapterCreator')```
Can you send your joinVoiceChannel function?
use shoukaku
No bugs & good audio
how do you play a youtube livestream (using ytdl-core) in discord.js/voice?
using createAudioResource(ytdl(.... )) does not work, audio stops in few seconds
anybody?
if (!serverQueue) {
const queueConstruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 100,
playing: true,
loop: false
};
queue.set(message.guild.id, queueConstruct);
queueConstruct.songs.push(song);
try {
var connection = await joinVoiceChannel();
queueConstruct.connection = connection;
play(message.guild, queueConstruct.songs[0]);
} catch (error) {
console.error(`Error ${error}`);
queue.delete(message.guild.id);
const errorvoice = new MessageEmbed()
.setColor("RED")
.setDescription(`Error **\`${error}\`**`)
return message.channel.send({ embeds: [errorvoice] });
}
} else {
serverQueue.songs.push(song);
if (playlist) return;
else return message.channel.send(`✅ **|** **\`${song.title}\`** Queued`);
}
return;
}
function chunk(array, chunkSize) {
const temp = [];
for (let i = 0; i < array.length; i += chunkSize) {
temp.push(array.slice(i, i + chunkSize));
}
return temp;
return;
}
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
return queue.delete(guild.id);
}
const dispatcher = serverQueue.connection.play(ytdl(song.url))
.on("finish", () => {
const shiffed = serverQueue.songs.shift();
if (serverQueue.loop === true) {
serverQueue.songs.push(shiffed);
};
play(guild, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolume(serverQueue.volume / 100);```
The joinVoiceChannel requires an options parameter which has a guildId, channelId and an adapterCreator which are required in the options parameter, also it won't return a Promise so the await won't do something. Replace your joinVoiceChannel function with
const guild = client.guilds.cache.get(`Your Guild ID`);
const vc = guilds.channels.cache.get(`Your Voice Channel ID`);
joinVoiceChannel({
guildId: guild.id,
channelId: vc.id,
adapterCreator: guild.voiceAdapterCreator
});
Ok
What should i do ?? how can i check that user connect to any voice or connect to specified voice
(i know the give role system...)
TypeError: serverQueue.connection.play is not a function
Hey guys so i have a question about the voice basic example, im getting an error at this line "const connection = await connectToChannel(channel);" specifically on channel, even tho channel is constructed above.
The error message is ** "Argument of type 'VoiceChannel | StageChannel' is not assignable to parameter of type 'VoiceChannel'.**
"Argument of type 'VoiceChannel | StageChannel' is not assignable to parameter of type 'VoiceChannel'."
I have tried to assign proper parameters according to docs to the "channel" but couldn't get it work what am i missing?
Change the parameter of the function to also accept a Stage Channel
There should be a typedef for that, smth like VoiceBasedChannels
Thank you! I will look into that asap
If anything, just use the same return type as VoiceState.channel
What's the variable to check if a user is already in a voice channel, or to grab the channel ID? I've tried message.author.voice.channel and message.author.voice.channelId but both return an error
voice is a property of GuildMembers, not Users
message.member?.voice.channel
thanks i'll try that
so it isn't a property of message.author?
correct, that's a User
i can't find anything in user
ah nevermind, I was being stupid
Ugh now i have fixed the errs but i can't play the audio eventhough i have the correct intents set....
Bot joins the channel also checks if anyone in the channel correctly but i can't play the audio..
also the intents
This is the error im getting, when i initiate -join command bot joins but doesnt play audio
got the dependencies like stated in the https://github.com/discordjs/voice
show us the code where you try to play the audio
anyone around to help me with a sttreaming audio issue?
How can i make a queue with @discordjs/voice
Any eta for the memory leak?
Hello! Anyone can help me? I'm trying to stablish a voice connection based in the discord.js documentation guide, but got the following error:
at Object.sendPayload (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\structures\Guild.js:1320:26)
at Ie (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\@discordjs\voice\dist\index.js:8:12615)
at gt (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\@discordjs\voice\dist\index.js:8:12763)
at Object.execute (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\commands\musicSystem\play.js:25:22)
at Object.execute (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\events\interactionCreate.js:29:19)
at Client.<anonymous> (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\functions\handleEvents.js:8:58)
at Client.emit (node:events:390:28)
at InteractionCreateAction.handle (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\client\actions\InteractionCreate.js:70:12)
at Object.module.exports [as INTERACTION_CREATE] (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\client\websocket\WebSocketManager.js:350:31)
Intents:
👀?
How can i fix it?
.then(connection => {
require('http').get(language.radio.flux[radio].flux, (res) => {
connection.play(res);
How to do that in v13 ?
You should make a Readable Stream and play that in the audio player
have u an example plz....
......
How is this message.guild.me.voice.channel.leave(); in V13?
<Connection>.destroy()
@left nymph
const vc = interaction.member.voice
const channel = vc.channel
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const resource = createAudioResource(language.radio.flux[radio].flux, {inlineVolume: true});
resource.volume.setVolume(100);
const player = createAudioPlayer();
connection.subscribe(player);
player.play(resource);```
No error, but the bot didnt play anything...
Hi, I'm sure this is probably an easy problem; but I can't find any sort of solution online--
I just need my bot to connect to a voice channel at the moment, its long term goal is for it to be able to read the volume of all the users in channel-- but I don't need to get into that rn.
const { joinVoiceChannel, AudioPlayer } = require("@discordjs/voice");
const { Client } = require("discord.js");
module.exports = {
name: 'join',
description: 'Joins the chat',
execute(message, args)
{
const voiceChannel = message.member.voice.channel;
if(!voiceChannel) {return message.channel.send("get in a channel ");}
joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
// adapterCreator: message.guild.voiceAdapterCreator
});
joinVoiceChannel();
}
}
this is all that I have in my join.js but it's not working-- it gives me a crash log so large that I can't fit it in one discord message
Hi, can someone give me some insight? I'm getting this error:
TypeError: Cannot read properties of undefined (reading 'status')
at Object.sendPayload (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\structures\Guild.js:1320:26)
at Ie (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\@discordjs\voice\dist\index.js:8:12615)
at Object.gt (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\@discordjs\voice\dist\index.js:8:12763)
at Object.execute (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\commands\musicSystem\play.js:39:34)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.execute (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\events\interactionCreate.js:29:5)
I am not sure but I think you should also precise guldId parameter when you call joinVoiceChannel
also tried that same error xd
It is hard to tell without seeing the actual code. Are you 100% sure that it is caused by these lines of your code ? + I haven't done anything with interactions yet but if your interaction is an object, all of the properties are already defined right? So why would you use "await" ?
I just copy pasted what discord.js documentation said, kinda wnted to see how it works, it was just a desesperate attempt the await thing. It did works once or twice out of ten attempts
Ignoring your question I want to say something : you will get in trouble with ytdl-core. Go with play-dl if you want to play audio from youtube because it has less bugs, problems and much more easier to use
I can't see the problem on your code but I think it is a better idea to use a single source to retrieve information for channelId & guildId & adapterCreator
Example : If a user sends !join message. You can get the user's voice channel by
const voiceChannel = message.member?.voice.channel
connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false,
});
If this doesn't solve your problem neither, maybe someone else with more experience then me can help you ^^
Preferably, you should also use the entersState function to make sure the connection actually becomes ready
Also gotta do permission checks bc Discord doesn’t emit an error if the bot is missing permissions to connect
?👀
Tell me if you did
any solutions to this silence problem
This is v13 discordjs voice help. We no longer provide help with v12.
anyways, how are you people capturing the audio, as discord sends the audio clipping the silence. how do you insert silences ?
As mentioned in the forum answer, Use Silence Frames and just write it into audioStream whenever user is not speaking.
audioStream.write(SILENCE_FRAMES)
ur running the joinvoicechannel function twice, once without saving it in a variable and once again without passing any information
it has less bugs
I never faced any bug with play-dl. Did you faced any ??
I never faced any ^^ but that probably doesn't mean there are any. If you aren't doing something extreme, you probably won't get any. And you are the guy who suggested me to use it, right? If yes, thanks again lol
If there would be any issues, then everyone would have created issue at the repository.
Looking at repo, I think there is no issues in play dl.
Idk, Am I the one who suggested play dl??
But yes I am the creator of play dl.
are you the creator of play-dl 😮
guys he is speaking language of the gods, careful xd
XD
why does <Guild>.me.voice.channelId still points to channel that was deleted?
bot was connected to it before it was deleted
So the bot connected to a voice channel, then the voice channel got deleted and the <Guild>.me.voice.channelId still returns the channel id of the deleted voice channel?
yea
anyways i sorted it out
turns out voice.channel is null after channel is deleted to im using this way now lol
ah ok
is there a way for me to track if a user in the voice channel a bot is in is speaking?
var volume = voiceManager.GetLocalVolume(404360475757903882);
Console.WriteLine("User is at volume level {0}", volume);```
this thing I found on the documentation straight up does not work; as in it crashes cause "discord" isn't a thing
How can I get the currently playing player?
In my case, I use a shared variable that I store in a module.exports. Whenever, I need it, I just require the module and reach the player variable. There mightbe a better way to do this but it just works fine for now
I just need to be able to resume the song but it won't unpause.
Anyway to create one?
Use getVoiceConnection() from the voice library to get your current VoiceConnection. Then use <VoiceConnection>.state.subscription.player to get your player.
hello, my bot joins the channel and instantly leaves, I've checked that the stateChange event is emitted and that the newState is idle
Like this? const voiceConnection = getVoiceConnection(message.guild?.id)
Yeah
I seem to get this error Property 'subscription' does not exist on type 'VoiceConnectionState'.
Did I do something wrong? const player = voiceConnection?.state.subscription.player
Hello, could someone help me? I made a music bot perfectly, I checked that everything was fine and I installed all the following modules:
npm i @discordjs/opus
npm i opusscript
npm i ffmpeg-static
npm i ytdl-core
npm install discord.js
and by the way I am in v13
here are the screenshots of my code and the error :
I changed my token
npm i ytdl-core-discord
Oh my bad, should be voiceConnection.state.status.subscription.player i think
thanks !!!
when I go to voice and I put a music, I do not hear the music and it puts me this error
What's your code?
Is your connection already subscribed to the player? Because it should have that property.
as a result?
Where are you getting video from?
youtube
It should be subscribed first, and the property is called subscription not subscribe.
Then I get Block-scoped variable 'player' used before its declaration. on the line voiceConnection?.subscribe(player)
I have to replace it here?
No
or ?
Before that line try doing const video = args[0]
Or js connection.play( await ytdl(args[0], { filters: 'audioonly' }), {type: 'opus'}
I'm only showing you a way of getting your player at any point in your code like you asked for. You need to make the player and subscribe it yourself first, otherwise there is nothing to retrieve.
All I need is a way to get the currently playing music, then resume the player.
args is not defined
@exotic haven
Define args
async run (message, args, { query })```
It gives me this error code after changing the connection.play and also after defining args
Show me the new code.
And what's the full error?
this
That's everything? Does it not give you a line?
no it only gives me that :/
Okay, remove args from the first aync run
And try putting it in the last one so js async runVideo(message, args, connection, video) { connection.play( await ytdl(args[0], { filters: 'audioonly' }), {type: 'opus'}
I copied what you told me, but I still get the same error
I mean what I told you works for me.
oh but how do I do that?
Try doing async run instead of async runVideo.
like this?
Yes
It always gives me the same mistake
Maybe the error comes from my index.
I have no more ideas sorry
Like I said what works for me doesn’t seem to work for you.
it doesn't matter xD
yes it is unfortunate
but maybe if you give me some of your, it will work?
Good night! I'm using @discordjs/voice to make my bot play music on a voice channel. Everything seems to be working out, the bot plays the songs correctly. But in some situations, such as when there is more than one person in the voice channel, the robot simply stops playing and goes into AutoPaused state. I'm very frustrated with this, I've read the documentation a few times and I haven't been able to solve the problem. I installed all necessary libraries for this task. Can someone help me?
https://discordjs.guide/voice/audio-player.html#creation
Change no subscriber behaviour to play. EZ Fix
Is anyone else getting this error when installing @discordjs/voice
npm WARN tarball tarball data for prism-media@https://codeload.github.com/distubejs/prism-media/tar.gz/main (sha512-lkEYKsA09+XkKqQHHK96cpmzJE3rlIoMHYww0gfS4Vodz/ZS2p/4Bt09xAqRoHpUEihbO+KdaOFGOypBdBaz7Q==) seems to be corrupted. Trying again.```
nvm I removed package-lock and it seems to be installing correctly
Thanks. Surely that's the problem, thanks for the help!
Hello! I have a error message in djs voice. I was opened an questions in stackoverflow. This is the link: https://stackoverflow.com/questions/70344810/discord-js-voice-connection-destroy-error
Thankyou for answering my questions!
This is not a issue in your code.
It has something to do with discord IP discovery system.
hi how to make a leave command for a radio bot
<Guild>.me.voice.disconnect()
how do I get the bot to speak as soon as it connects to a course?
how do I do that if my bot is already launched in a stage it puts me a message for example: already used, I already have for guild_voice?
but it's for a another chanel
Hey, do you guys know what cause the Voice Connection to never reach the "ready" state, without printing an error?
My code WAS working, but now it decided to refuse connection with discord
(or something, i am pretty confused yk)
If the onStateChange function of the voice library isn't broken, the connection is stuck at the SIGNALLING stage
ok
i'm stupid
can someone help me code a music bot for my school that has 300+ people in it
dm me whenever
I doubt anyone has that much time to spare, helping to code an entire bot
However, there is an example linked in the documentation that you can try and use as a reference:
https://github.com/discordjs/voice/tree/main/examples/music-bot
But gl anyway
Can anyone help me? How can i do .setVoiceChannel(null) if i got the users ${executor.id} ?
ty
seriously ????
Hey
I'm trying to update my music bot code to v13
Nice well and good only. What's the issue ??
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
description: 'Joins and plays a video from youtube',
async run(client, message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
if (!args.length) return message.channel.send('You need to send the second argument!');
const validURL = (str) =>{
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex.test(str)){
return false;
} else {
return true;
}
}
if(validURL(args[0])){
const connection = await voiceChannel.join();
const stream = ytdl(args[0], {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
message.channel.send('leaving channel');
});
await message.reply(`:thumbsup: Now Playing ***Your Link!***`)
return
}
const connection = await voiceChannel.join();
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
const stream = ytdl(video.url, {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
});
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
} else {
message.channel.send('No video results found');
}
}
}
``` im getting this error: ```:\Users\Patron\Documents\GitHub\Hydration-Homie\commands\play.js:42
const connection = await voiceChannel.join();
^
TypeError: voiceChannel.join is not a function```
that... does not explain youtube music bots
connection.join were old methods.
New methods are in given guide.
You need to follow the guide.
oh thanks o7
soo i change it to joinVoiceChannel?
Yes, moreover you need to change connection.play commands also
what do i change connection.play to
player.play ? sorry this guide is slightly difficult for me to follow
You need to create a audio Player first and then attach it to voice connection [ That you get from joinVoiceChannel function. ]
Now for playing audio part, just create a Audio Resource and then play the Audio Resource by player.play(resource). Player here is AudioPlayer that you created in previous step.
okay. idk to me it seems like they made everything more complicated with all this player stuff
Yup probably.
yeah same with messageCreate, etc. like im a fan of slashies but most of what they did seems to complicate sh*t
doesn't that work? oops
That was for v12 and this is v13
That is my bad, then! Noted 
hello, did anyone know if we can get the audioPlayer from a VoiceConnection ?
<VoiceConnection>.state.status.subscription.player If I'm not mistaken
not that, <VoiceConnection>.state.status refer to a <String>
but i found it, you get it by the <VoiceConnection>.subscibe(audioPlayer) and that will return a PlayerSubscription
How can I solve this connection error? (It is related to Discord.js / Voice)
N [Error]: aborted
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:407:19)
at TLSSocket.emit (node:events:406:35)
at node:net:672:12
at TCP.done (node:_tls_wrap:580:7)
Oh it's without the .status part then.
yep it work, thx
Where can I find the voice Documentation?
The documentation button on the GitHub page no longer seems to direct to the voice Documentation, and there is no voice option on the documentation site/doc settings
Client#voice
The voice manager of the client
Thank you for the response.
I should have specified I am looking for the voice library, and that appears to be a voice object
you can look at the guide: https://discordjs.guide/voice/
or docs: https://discordjs.github.io/voice/
Thank you, that second link was exactly what I was looking for 😃
hey i'm looking at the basic example from the discordjs/voice repo, and it does not look basic
is the adapter stuff boilerplate code? i'm a bit rusty on my nodejs and this looks so intimidating
TypeError: Cannot create property 'audioPlayer' on string 'C:/Users/personal/Downloads/yH7Xg9cjyfkF6JCVBHdoGjlDPyJAOxMt.mp3'
Can anyone please tell me how to check if the user is in the same vc as the bot.
please
only just saw this channel, kinda crossposting ig?
try{
await user.voice.setChannel(null);
}catch(err){
message.channel.send("Failed to disconnect user");
return;
}
user is a user object, this throws an error and goes into the catch. user.voice is undefined when I log it out. I am not sure how to achieve disconnecting people from voice channels.
i assume this is the right channel for it, correct me if not
User objects do not have a voice property, I think what you're trying to use is a GuildMember object. That has a voice property which can be used to disconnect them from a channel.
PS: this is fine for this channel
yeah I am struggling to get the guild member right now. I want my bot to work anywhere and get messaged anywhere so I want to be able to give the bot !disconnect [user id] in dms and it will disconnect that user no matter which guild they are in. I am still trying to find an elegant way to do that so if you have any ideas throw them at me.
I know I could manually get the guild by ID, or I could run a loop for every guild my bot is in and check each one, but none of these solutions sound all that great
hey i'm currently struggling with something: js bot.channels.cache.forEach(channel => { if (channel.type == "GUILD_VOICE" && channel.members.size > 0) { let played = false; const conn = joinVoiceChannel({ channelId: channel.id, guildId: channel.guild.id, adapterCreator: channel.guild.voiceAdapterCreator }); conn.subscribe(player); const resource = createAudioResource("./resources/waterphone.mp3", { inputType: StreamType.Arbitrary }); player.play(resource); played = true; entersState(player, AudioPlayerStatus.Playing, 5e3); player.on('stateChange', (oldState, newState) => { console.log(newState.status); if (newState.status == 'idle' && played) { conn.disconnect(); played = false; } }); //channel.members.forEach(m => console.log(m.id)) } }); how would i do something when the file has finished playing? i'm trying to disconnect it once it has finished playing, but when there's two channels to use, it will join the first one, disconnect immediately and then do the next channel perfectly
This may be not the answer but why do you use "entersState" when player already handles it ? and for the stateChange you can simply use
player.on(AudioPlayerStatus.Idle, () => {
//DO SOMETHING
});
i don't know, the guide i was using did it and i asked myself the same thing; i just assumed that it didn't change the state for some reason
i have since resolved this problem btw
my solution was to use the async package
Anyone able to help me? I'm getting an error after playing couple of seconds of a song
Pictures of Code + Error:
the player.on error prints this:
Hi there, im using the discord.js/voice library to just create an audio player; how do I make it so my bot joins the voice channel undeafend?
what is voice.getNextResource() ?
honestly, i have no clue. some vid told me to put it in apparently it should ge the next song in the queue
but the main problem really is the error aborted thing
idk even why it gives the error "aborted" and the resource is "null" lol, it plays the song for about 30 seconds to 1 minute then it just stops the music and gives the error: aborted with resource null
@haughty maple Ty, it seems my bot joins the vc and is playing but for some reason I don't hear the audio
Could I post the code maybe and somebody could identify something? I installed all the dependecies for the discord.js voice
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false
})
let resource = createAudioResource(("C:\Users\jk076\OneDrive\Desktop\DiscordProject\images\wedem.mp3"), {inlineVolume: true})
resource.volume.setVolume(1)
const player = createAudioPlayer();
connection.subscribe(player);
player.play(resource)
console.log("done");
Do you have the GUILD_VOICE_STATES intent?
Yes and I can see the little green highlight so I know it's trying to play something
Yesterday, I had a similar problem. It was caused by the source file (.mp3). It may be same for you
@haughty maple any idea further for me?
What file type would be best? @haughty maple
I don't know I think mp3 is okay. My problem was related to fs. I tried to make my bot speak with google text to speech api and I was trying to use my file before I wasn't done with writing
Are you trying to play some audio from youtube ? if yes, which library do you use ?
I tried with different files didnt work... in terms of the code does everything seem okay?
Core Dependencies
- @discordjs/voice: 0.6.0
- prism-media: 1.3.2
Opus Libraries
- @discordjs/opus: 0.5.3
- opusscript: not found
Encryption Libraries
- sodium: not found
- libsodium-wrappers: 0.7.9
- tweetnacl: not found
FFmpeg
- version: 4.4-essentials_build-www.gyan.dev
- libopus: yes
Yes, I'm using ytdl-core & yt-search and discordjs/voice ofc
This is also thedependency report
Try, play-dl. It s a common problem
It seems okay. The only thing that may cause problem is your path to the mp3 file. It is better to store them in the project's file and avoid using global paths such as reaching C: etc.
But this is only my opinion. This may not even be related. I would check if it actually finds the mp3 file
I think I read that only global paths but yes I can try that
How would I go about testing to see if it finds it?
You can use "fs" : https://flaviocopes.com/how-to-check-if-file-exists-node/
@haughty maple I was using backslashes for the path....
Oh :P, shit happens bro.
I thought it was backslash for windows though? I know mac is forward slash
Will try this, thank you
Hi there, for the setVolume
What are the inputs for that? 0 to 1 scaling?
0 is none, .5 is half, 1 is no change, and 2 is double
Thank you and i was wondering what the default disconnect timer is for a bot and how would i go about manually disconnecting after a specified time?
Default time i have no idea howere you can disconnect the bot by using connection.disconnect() this will allow to rejoin the channel if needed and connection.destroy() is to remove the bot from the channel, with this the bot cant rejoin the channel unless you call the joinchannel thing again.
Connection is the variable you gave the joinchannel thing
Hello there. Once I have a voice connection, is it possible to receive events for that connection? Specifically am interested in:
- Someone started speaking
- Someone stopped speaking
How do i solve this the error is in the descripton https://sourceb.in/7zqg1woeAm
Looks like if I create a new VoiceReceiver with the connection, in theory I have access to the SpeakingMap. I think this should tell me what I want to know, but I can't seem to wire up any events in a way that they get called. Would love any help with this.
you have to join the channel through joinVoiceChannel method that you import from @discordjs/voice
<voiceChannel>.join() does not exist anymore afaik
How do I error check if joinVoiceChannel worked or not?
I've had instances where the bot will not join but the function works without an error. All the promise based checking of the old voice implementation in v12 seems to be gone...
For example, I have no idea how to check if the bot could not connect to a voice channel for some reason. The only other workaround I can think of is to manually check the permissions of the channel before attempting to connect.
Store the output of the function in a variable like connection and you can check connection.state.status.
I am getting this weird error
https://sourceb.in/M7fRRJPSH7
works fine
but after sometimes this error shows up...
someone please help
const player = createAudioPlayer();
const resource = createAudioResource('../mp3/track.mp3', {
inlineVolume: true
});
connection?.subscribe(player);
player.play(resource);
I'm trying to play some audio, but it's not playing anything (it does show the talking indicator on the bot)
is it something with volume that I'm missing?
I can't seem to set the volume anywhere
I used the wrong path
Can bots also go live in a stage channel?
how would i do so?
how do i use streamlink
I'm getting a very weird bug when running my bot on ubuntu, it can join and play audio in voice channels just fine, just not when it's done with an OPUS stream. Has anybody else run into this issue?
all streams are pipelined to opus. I personally encode to ogg opus when using ffmpeg and have no issues
is it possible to join another channel with same VoiceConnection?
No
Well, i guess if the bot gets moved by another member, the connection will temporarily go out
So I got my bot working in vc and stuff and audio file, but says it's not playing audio, when there is a green circle around the bot
want my code?
**I fixed it I didn't need the file extension only the start of it
So if moved by GuildMember it can continue playing but we can't move it programmatically?
You could use joinVoiceChannel again and subscribe it to the player
I can play a mp3 file (local or remote) fine with ffmpeg tho
How do you encode to ogg opus? I'm using @discordjs/opus with ytdl-core-discord
How can I deploy a bot efficiently to multiple guilds?
Currently, I have a list of all channeIDs and I iterating through it and create a new connection in every channel...
for(var i = 0; i < list.length; i++) {
const channel = bot.channels.cache.get(list[i]);
channel.join().then(connection => {
player = connection.play(streamURL, {bitrate: 320000});
});
}
...but after connecting to 20-30 channels, the music is very lagging
Is there any more efficient way?
Voice will encode to opus automatically if the track isn't opus. If you're already using ffmpeg, then your base args should look like https://github.com/AmandaDiscord/Volcano/blob/864153f31ce2eac2ec471d2ab8605ad51eee7ab9/src/worker.ts#L192
You can subscribe multiple connections to 1 player playing a track.
what happens to connection when bot gets disconnected by a user ?
how to get bot deaf itself on join?
can you help me to solve the problem with the acolade please?
How do i pause a connection
Thank you very much! I've changed it now to a subscription:
for(var i = 0; i < list.length; i++) {
const channel = bot.channels.cache.get(list[i]);
channel.join().then(connection => {
connection.subscribe(player);
});
}
...but the music is still lagging 😦
your network upload is bottlenecked by streaming to every guild
Mhh, I have an upload of 924.46Mbps and unlimited traffic 🙄
To 36 guilds, everything is fine... After the 37th guild, it's start to lag
Then it's possible that the cpu is struggling to keep up since you're putting this all on a single core
if the track isn't opus, then it needs to pipe through ffmpeg as well which is more cpu strain
Ahhh, yeah this is 24/7 mp3 stream
Welp. Good luck multithreading. You'd be best off making an audio service independent from your bot similar to LavaLink, but with the assumption that it's all gonna be the same track. You can have a main thread requesting the stream for download and transcoding to opus and then pipe the data to worker threads
Alright, Async - Thank you very much for the great support!! 

@rose helm A little question to the subscription thing...
So I try to stop the sub when the channel is empty and when someone joins, I want to start the sub again
So in the event listener if someone joins the channel, I had something like this to get all "existing" voice connections:
bot.voice.connections.forEach(conn => {
}
...but I can't use conn.subscribe for this - Do you have an idea how can I manage this?
You can't pause playback on a per connection basis when using 1 player since the audio playback is linked to the player
Mhh, it makes sense...
how to recover the audio stream of a discord conversation ? I can't find anything on the subject in the doc
is there a way to temp pause a connection?
!join
Hi, I want to make an discord music bot I have the following code
const {videos} = await yts(message.content);
if (!videos.length) return message.reply("No songs were found!");
const song = {
title: videos[0].title,
stream: ytdl(videos[0].url, {filter: "audioonly"}),
url: videos[0].url
};
const resource = createAudioResource(song.stream)
player.play(resource);
bot.connection.subscribe(player);
Everything works, but after a short time I get the following error:
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)
Anyone knows how to fix that?
Every time i do ```javascript
player.pause()
it returns ```false```
why is it doing this?
heres my code -- https://sourceb.in/dZ2cGVnMKF
please explain this https://sourceb.in/s0ddXzWjJq the error is in the source bin title
const connect = joinVoiceChannel({
channelId: voicec.id,
guildId: voicec.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const dispatcher = connect.play('./Warm Summit.mp3');
``` Everything working until I try and play audio...
```js
Uncaught TypeError: connect.play is not a function
``` If you could help me that would be great, thanks!
Guide suggestion for @hallow lynx:
discordjs.guide results:
• Library: Audio Player
• Library: Cheat sheet
You need to look into how audio players and audio resources work bc that’s not how the voice package works
is there a way for me to check how long an audio resource has been playing for?
E.g. if I played it for 2 seconds, paused it for 5 seconds. Is there a way for me to know it's played for 2 seconds?
I'm trying to implement rewind/fast forward functionality
Is there anything can I do to avoid this issue 
Hey, I want to play an audio like the documentation said it but I get the Error:
Error: Cannot play audio as no valid encryption package is installed.
This is my code:
const connection = joinVoiceChannel({
channelId: channel_id.id,
guildId: guild_id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const resource = createAudioResource('home/FART.mp3')
player.play(resource)
connection.subscribe(player)
You need to install an encryption package.
But I installed sodium with npm
still not working
Try a different one.
thank you with libsodium its working
Is ist possible that the createAudioResource resoucre is a URL so an internet radio?
yes
Can you tell me how to do that?
Different one but thats an example streams.ilovemusic.de/iloveradio10.mp3
I use the same just pass the string url to createAudioResource
But then i Hear no Audio i only get the green cricle
Check if you have this intent added ```
Intents.FLAGS.GUILD_VOICE_STATES
I think I have enabeled all intents with one line. Or do i need to activate them in the dev portal?
I think I have enabeled all intents with one line. Or do i need to activate them in the dev portal?
Your intents should look like this:
const bot = new Client({ intents: [Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_VOICE_STATES] });
Thank you but how do I know when to enable wich intent?
Thank you but how do I know when to enable wich intent?
(static) Intents.FLAGS
Numeric WebSocket intents. All available properties: (more...)
Here you have a list of the Intents
for some reason, player.stop() throws error
here are my dependencies
"dependencies": { "@discordjs/voice": "^0.7.5", "discord-buttons": "^4.0.0", "discord.js": "^13.3.1", "express": "^4.17.2", "ffmpeg": "0.0.4", "ffmpeg-static": "^4.4.0", "@discordjs/opus": "^0.5.0", "libsodium-wrappers": "0.7.9" }, "devDependencies": { "node": "^16.6.1" }
what is data ? I mean where do you get/initialise it ?
i found in v12 its possible to receiving audio from user https://v12.discordjs.guide/voice/receiving-audio.html#basic-usage
i try the method but i have the error connectionA.receiver.createStream is not a function
its v13 who broke this ? or have way for repair that ?
let user = message.author;
let channel1 = client.channels.cache.get('864633308797337611');
let channel2 = client.channels.cache.get('571718353652285444');
const connectionA = joinVoiceChannel({
channelId: channel1.id,
guildId: channel1.guild.id,
adapterCreator: channel1.guild.voiceAdapterCreator,
selfDeaf: false,
});
const connectionB = joinVoiceChannel({
channelId: channel2.id,
guildId: channel2.guild.id,
adapterCreator: channel2.guild.voiceAdapterCreator,
selfDeaf: false,
});
const audio = connectionA.receiver.createStream(message.author.id);
connectionB.play(audio, { type: 'opus' });
hello how do i make join vc to create a new channel
// voiceStateUpdate
/* Emitted whenever a user changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
PARAMETER TYPE DESCRIPTION
oldMember GuildMember The member before the voice state update
newMember GuildMember The member after the voice state update */
client.on("voiceStateUpdate", function(oldMember, newMember){
console.log(`a user changes voice state`);
});```
ill make like this but its create after i leave
if (newState.channelId === '922185381095559219') {
newState.guild.channels.create(`〔🔒〕ʜᴜʙ - ${newState.member.user.discriminator}`, {
type: 'GUILD_VOICE',
parent: '904743415978262591',
permissionOverwrites: [
{
id: newState.member.id,
allow: [Permissions.FLAGS.MANAGE_CHANNELS]
}
],
userLimit: 5
}).then(async (voice) => {
await newState.setChannel(voice);
}).catch((err) => {
console.error(err);
});
} if (oldState.channel?.name === `〔🔒〕ʜᴜʙ - ${newState.member.user.discriminator}`) {
oldState.channel?.delete();
}
also why its return null ?
Trying to record audio from a user, it connects and doesn't crash but every time I try to record the file size ia always 0 bytes.
const stream = receiver.subscribe(userId, {
end: {
behavior: EndBehaviorType.Manual
},
});
stream.pipe(fs.createWriteStream('test.pcm'))```
can anyone provide me with the code from which the bot willl join a vc
thx i'll try it
can you try to help me with
Provide full code?
hello why is this code doesnt work, when i change the mute or defean status its show the error
if (oldState.channel?.name === `〔🔒〕ʜᴜʙ - ${oldMember.user.discriminator}`) {
await oldState.channel?.delete();
}
Errors
DiscordAPIError: Unknown Channel
at RequestHandler.execute (C:\Users\haziq\Desktop\Projects\JavaScript\one-venture\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\haziq\Desktop\Projects\JavaScript\one-venture\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async VoiceChannel.delete (C:\Users\haziq\Desktop\Projects\JavaScript\one-venture\node_modules\discord.js\src\structures\GuildChannel.js:535:5)
at async VoiceStateEvent.run (C:\Users\haziq\Desktop\Projects\JavaScript\one-venture\src\events\voice\VoiceStateEvent.js:38:13)
{
method: 'delete',
path: '/channels/922322676041805885',
code: 10003,
httpStatus: 404,
requestData: { json: undefined, files: [] }
}
the message constructor is used internally.
follow the guide on how to setup a listener and create commands, etc.
Does anyone have an example of recording multiple users in a VC?
How would one get a discord bot to just simply join a voice channel
I am far too tired to make sense of discordjs.guide/voice right now im sorry
not even to play music
just like to go into a voice channel and be ther
You just need to look at the installation section and voice connections section
discordjs.guide results:
• Library: Voice Connections
so id do smth like:
if (message.channel.send === '!join vc') {
connection.joinVoiceChannel
};
});```
(yes ik it looks bad, i havent added anything fancy yet, like prefix etc, im justtrying to get it to join vc
joinVoiceChannel is an export from the voice package
Also a function that takes an options object, as shown in the guide
ohhhhh i reread it
lemme try smth
if (message.channel.send === '!join vc') {
const connection = joinVoiceChannel({
channelId: 922142097983799396,
guildId: 770641536626589696,
});
};
});```
this would be it then (this make s sense to me)
Ids have to be string
Ur also missing the voice adapter
Also, channel.send is a method, not a string
Prob meant message.content
yes
i am tired man sorry
Nw
adapterCreator: channel.guild.voiceAdapterCreator
"adapterCreator: channel.guild.voiceAdapterCreator,"
i saw thisi beforehand but i just ignored it
what would i use for it ig?
channel.guild I can do
voiceAdapterCreator however?
Yes, you can do guild.voiceAdapterCreator
oh i literally just have to add underneath guildId: whatever it was
adapterCreator: (the channel id).guild.voiceAdapterCreator
Channel id is not valid here
It has to be the channel object
const channel = client.channels.cache.get("922142097983799396");
i added that
im gonna try it all out later
anyone having issues with discordjs/opus package? it seems like the package is broken or something...
What are the differences between shoukaku and erela.js? Is one better to use than the other? Also in terms of which one is more maintained
Hey, my code doest work can you help me?
I get the green circle and when i try to play audio from an Internet stream and when I enable the intents I get the error:
"TypeError: Cannot read properties of undefined (reading 'Client')"
Heres my code:
const { Discord, Intents } = require('discord.js');
const { joinVoiceChannel, getVoiceConnection, createAudioResource } = require('@discordjs/voice');
const { createAudioPlayer } = require('@discordjs/voice');
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_VOICE_STATES] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", async message => {
var channel_id = message.guild.channels.cache.get("922193458767216641");
var guild_id = message.guild.id
if (message.content === "test") {
const connection = joinVoiceChannel({
channelId: channel_id.id,
guildId: guild_id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const resource = createAudioResource('streams.ilovemusic.de/iloveradio2.mp3')
player.play(resource)
connection.subscribe(player)
}
})
client.login("TOKEN");
Would appreciate if you could help me
Discord isn't on the same level as Intents in 'discord.js', you probably mean:
const { Client, Intents } = require('discord.js');
//...
const client = new Client();
Thanks thats working now do you have an idea about the other thing?
What other thing?
Streaming muisc from an internet radio
No idea how that works lol
Wait for someone else
Nobodys answering 😦
But thank you
It's only been 2 hours, not that bad for something not-so-popular/easy like djs voice;)
Yea your right but I already asked yesterday xD
Got it working xD
Ok, congrats xD
Why does connection.dispatcher.pause() work but connection.dispatcher.resume() isn't?
Hello, I'm making a discord bot with music features just like rythm. I'm brand new to js but have experience with discord.py. That said, I've ecountered issues apparently due to discord.js v13 update. Here's my code : https://pastebin.com/TDnU1xPa
i am making a music bot which plays local mp3s
when i pause the mp3 file, it throws typerror
btw i am using v13
Can you please help me ? How did you make ur bot join a vc
you need to include @discordjs/voice and FFPMEG-Static and libsodium wrappers
you can make your dependencies in package.json this:
"dependencies": { "@discordjs/voice": "^0.7.5", "discord-buttons": "^4.0.0", "discord.js": "^13.3.1", "express": "^4.17.2", "ffmpeg": "0.0.4", "ffmpeg-static": "^4.4.0", "@discordjs/opus": "^0.5.0", "libsodium-wrappers": "0.7.9" }
then, you need to insert this->
`player = createAudioPlayer();
let resource = createAudioResource('Eastside.mp3');
connection = joinVoiceChannel({
channelId: msg.member.voice.channel.id,
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator
});
subscription = connection.subscribe(player);
player.play(resource)`
you need to create a audio player, initialize a resource and subscribe the connection that youve created to the player then have the player play the resource
also you need to add const { joinVoiceChannel, createAudioPlayer, createAudioResource, NoSubscriberBehavior } = require('@discordjs/voice'); at the start
dont forget to add "GUILD_VOICE_STATES" to your intents
thx
Hi guys, I am trying to make a discord bot that plays music for my first time and I have been struggling for the past week with it crashing when playing songs from YouTube. I don't know why it crashes and after 2 days of stackoverflow I couldn't figure it out. I pasted my relevant code related to music and also the error bellow. If anyone has any idea I would appreciate it a lot.
code: https://pastebin.com/D4CS8dn5
error: https://pastebin.com/A1bzfFKj
Hey, I have a question about a music (private) bot, if I add it to my server where I have some people, this bot becomes public even if it is only on my server?
Lemme guess, you use youtube-dl ?
I use ytdl-core indeed
Try play-dl. I never had any problems with it.
It is a common problem with ytdl-core and youtube-dl, If I remember correctly.
Alright, will try it right now. thanks!
Hey! So is there NOT a way to destroy an audio resource
I can find nothing in the docs about it. I switch from a live radio stream to a file stream, and that works fine, but if I try and create another/new audio resource of the same live stream, it just doesn't work- AND the previous audio resource still runs even after a call to stop the player.
There's seriously 0 documentation about this and it's driving me nuts. If I can't kill a resource after making it, and it's a live stream, it just drains memory till it crashes
I suppose I could in theory just not use the built in function and make my own with axios but I'd rather not reinvent the wheel
Ended up re-inventing the wheel because if you destroy it, it doesn't kill the edge cases, which you can't actually kill either without destroying the process pid's
Could prob just do resource.playStream.destroy()
That doesn't actually work either. I tried that first given the docs. It destroys the object, and stream to discord, but not the edge cases such as ffmpeg, and does a bunch of other weird nonsense I don't have time to look into
Half this library doesn't actually work it seems, or is poorly documented in the cases where it does work
Greetings, fellow human people friends, I'm in dire need of assistance
I'm trying to write a podcast bot where people from different servers can have a bot join their channel and relay audio from one source
The source is another person sitting in a voice channel in some private server, with the bot receiving the audio from the voice channel and relaying it to all the other voice channels
This is my approach:
- Creating an audio player
- Everyone who wants to listen to the podcast (from different servers) types
-join, the bot joins the channel and the audio connection is subscribed to the audio player - One person types
-streamin a different server, the bot joins the channel and the audio receiver is subscribed to, and the opus stream is passed to the audio player - ...
- profit??
Here's my code, as well:
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
maxMissedFrames: Math.round(config.maxTransmissionGap / 20),
},
});
async function connectToChannel(channel) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30_000);
return connection;
} catch (error) {
connection.destroy();
throw error;
}
}
const client = new Client({ intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_VOICE_STATES'] });
function createListeningStream(receiver, userId, user) {
const opusStream = receiver.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterInactivity,
duration: 1000,
},
});
player.play(createAudioResource(opusStream,
{
inputType: StreamType.Opus,
},
));
}
client.on('messageCreate', async (message) => {
if (!message.guild) return;
if (message.content === '-stream') {
const channel = message.member?.voice.channel;
const connection = await connectToChannel(channel);
if (connection) {
const userId = message.author.id;
const receiver = connection.receiver;
receiver.speaking.on('start', (userId) => {
console.log("You're speaking");
createListeningStream(receiver, userId, client.users.cache.get(userId));
});
await message.reply('Listening!');
} else {
await message.reply('Join a voice channel and then try that again!');
}
}
if (message.content === '-join') {
const channel = message.member?.voice.channel;
if (channel) {
try {
const connection = await connectToChannel(channel);
connection.subscribe(player);
await message.reply('Playing now!');
} catch (error) {
console.error(error);
}
} else {
await message.reply('Join a voice channel then try again!');
}
}
});
Please let me know if I have the right idea or if I'm doing this terribly wrong
And if I'm not already doing something terribly wrong - is this going to scale at all?
can someone modify this code and make it work?
pls.
Resources can’t be reused
Error is straightforward
I'm not sure how to work those packages
Those are all npm packages
I’m assuming you know how to install an npm package
Yes which one do you pefer tho?
First one for best performance
Second one if you have trouble installing the first one and just want to test
how would I use sodium?
Just install it
I did same error
Did the install succeed?
You didn’t see any red messages after it finished?
its just sodium right?
Yea
yes it's installed
Run node -p require("@discordjs/voice").generateDependencyReport()
Do I need to require it?
No
hold on I need to put it on my computer its on peble host rn
Oops, wrap the thing in quotes
Also, it’s a node command, not npm
ik i tried both put what in quotes
Run node -p 'require("@discordjs/voice").generateDependencyReport()'
@icy maple
Is this a PS thing?
PS?
PowerShell
no vs Terminal
No, ur using PS
It says so at the beginning of the line
I’m talking about the quotes disappearing
Mb swap the single and double quotes
node -p "require('@discordjs/voice').generateDependencyReport()"
Yea
"VS Terminal" is just any terminal on ur computer in the app
Yea, it says sodium isn’t installed
i did install it
Can also check with npm ls sodium
it errored
What was the error?
@icy maple
Run the command shown
Then try to install again
Are you running on ur computer, or on ur host?
computer
Got confused bc you said you installed sodium, but showed a webpage, which I assume is ur host
correct
errored out once again
What’s the error?
you wanted to run npm config set msvs_version 2015 right?
Yea
it ran that fine when I ran NPm install again the=is was the error
You need to install python v3
why python?
can i do that in the terminal?
I think you can if you have chocolatey
i do i just downloaded it from the website one moment
Yea
If there’s an option to add it to path, make sure to enable it
Restart the terminal
Click on the trash icon in VSC, then the plus sign to create a new terminal
retrying
sanme error
Run python3 --version
hold on python didn't install properly
Wait yes It did
all the right boxes are check marked in the install
@icy maple
Where did it install to?
C:\Users\mikeo\Appdata\Local\Programs
You can use method 2 to check if it was added to ur path
its there tho
Try python --version
Try installing sodium
Should I just try the other ones?
Oh, it’s a different error
You need to install the latest version of Visual Studio including the "Desktop development with C++" workload. For more information consult the documentation at: https://github.com/nodejs/node-gyp#on-windows
Install the vs build tools
i ran npm install -g node-gyp
Still need to install the visual studio build tools
installed I believe
I got it to work that you for your help
why is the problem
TypeError: channel.join is not a function
at Client.<anonymous> (D:\0SYSTEM\Desktop\Helper\index.js:19:40)
at Client.emit (node:events:402:35)
at WebSocketManager.triggerClientReady (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketManager.js:383:17)
at WebSocketManager.checkShardsReady (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketManager.js:366:10)
at WebSocketShard.<anonymous> (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketManager.js:188:14)
at WebSocketShard.emit (node:events:390:28)
at WebSocketShard.checkReady (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketShard.js:474:12)
at WebSocketShard.onPacket (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketShard.js:446:16)
at WebSocketShard.onMessage (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
at WebSocket.onMessage (D:\0SYSTEM\Desktop\Helper\node_modules\ws\lib\event-target.js:199:18)```
help please
@subtle granite
@icy maple
VoiceChannel (extends BaseGuildVoiceChannel)
Represents a guild voice channel on Discord.
@spark marsh
read the guide for v13 voice
v12 voice is not supported anymore
why do i get the error cannot read property of undefined updateOverwrite
vcChannel.updateOverwrite(message.author.id, {
CONNECT: true
})
vcChannel.permissionOverwrites.edit()
thanks
ah shit
what is it then?
channelId:channel.id,
^
ReferenceError: channel is not defined
channel isnt defined? maybe show ur code
put a space, but idk for sure
also channel is not defined so either you put
message.channel.idor you define channel withlet channel = "id of your channel"
didnt fixed
read up
can i see your whole code?
wait lemme send you the code
madeby-codelyon
put the const part inside then execute code
ok
@radiant ridge this is the code now no errors
but when i use .play song nothing happenes
thats then up to your code you can log it with try { ...code... } catch (e) { console.log(e) }
stilll no errors
you got any kind of music bot code?
Uh
Why is everything null
Do u have guild voice states intent?
of course
Who coded this fck package??
there are 3+ memory leaks
Better to use lavalink
How did you manage to create that many listeners multiple times?
I’ve never had that issue, and I don’t change the max listeners
Here is my code:
I don't see what's wrong
Is this ts transpiled code?
I'd prefer to see the ts code
hm no
You manually wrote all of that by hand?
ah no
I want to see the code before it got transpiled into this
Anyone know what this error means?
[
{
status: 'connecting',
adapter: [Object],
subscription: [W],
networking: [te]
},
{
status: 'ready',
adapter: [Object],
subscription: [W],
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 (C:\Users\vadle\OneDrive\Documentos\DISCORD\TESTING\PASSION-TESTING\node_modules\@discordjs\voice\dist\index.js:9:680)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async DisTubeVoice.join (C:\Users\vadle\OneDrive\Documentos\DISCORD\TESTING\PASSION-TESTING\node_modules\distube\dist\core\voice\DisTubeVoice.js:103:13)
at async QueueManager.create (C:\Users\vadle\OneDrive\Documentos\DISCORD\TESTING\PASSION-TESTING\node_modules\distube\dist\core\manager\QueueManager.js:25:13) {
code: 'ABORT_ERR'
}```
hi, help please
what i can do with this?
i guess they're either
- forgot to stop the player
- forgot to remove the player reference
- forgot to remove the resource reference
at least this is what I know about my bot because it was always leaking things lol
How can I reuse an AudioPlayer. What I'm currently doing is to destroy every AudioPlayer and AudioResource and removing them from reference, which maybe is not good?
another one, how can I make the bot disconnect after a given time of inactivity without using this settimeout mess
(please mention me when anyone answers)
another one, how can I fix this memory leak? (this part is from the example code so ...)
Only create the disconnected listener once
oh
Error says it’s getting created
of times
i see, i put this in the play function, which will just recreating this listener a bunch of times
should've put this at the connection creation zone
Yea, that sounds more reasonable
what about this and the one below this?
Players are reusable, just keep a reference to it
so, when the resource ends, just .stop() the player, remove resource reference, then .play() a new resource into the AudioPlayer?
Help
After v13 i got eror
const connection = await channel.join().catch((err) => {
^
TypeError: channel.join is not a function
Is a connection seeing how many places your bot is connected into different server vcs?
Nevermind
Did you figure this out? I'm having the same problem
nope