#archive-voice
30636 messages · Page 29 of 31
const { joinVoiceChannel } = require("@discordjs/voice");
const fs = require("fs");
var voiceChannel = message.member.voice.channel;
var writeStream = fs.createWriteStream("test.pcm");
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});```
Hello why i have this error please :
```\node_modules\@discordjs\voice\dist\index.js:1377
const adapter = adapterCreator({
^
TypeError: adapterCreator is not a function```
honestly that should be it
what version of discord.js are you on?
Isn’t voiceAdapterCreator on VoiceChannel?
Nvm
not getting any errors but the bot goes through my function all the way down to sending the embed but never joins the channel
it even gives the confirmation log that its playing music but it never joined the channel at all
Nvm fixed it, had ID capatilized
does anyone know how i can fetch a connection with the guild id?
mainChannel = ....channels.cache.get(...)
-TypeError: Cannot read properties of undefined (reading 'permissionOverwrites')
Because <Channel>.channel doesn’t exist
um i fixed thx
players.set(interaction.guildId, player);
players.get(interaction.guildId).play(resource);```
Why do the players still share the same audio in different guild?
Because you put the same player object with different keys. You‘d need to actually create seperate player objects
So i must create new player?
If you want to have seperate players playing different Audio, yes
well... i'll figure it out, thank you
that doesn't work, I've already tried it
What exactly do you try to do and how doesn’t it work?
i tried const connection = getVoiceConnection(message.guild.id)
And what happened?
undefined
Then you didn’t joinVoiceChannel on that guild yet
what if the bot is already in a channel in that guild
How did it get in there if not by joinVoiceChannel?
i made it join a voice channel and then i restarted it
after that the client.voice.adapters returns 0 entries in the map
You‘d need to call joinVoiceChannel again then, because the VoiceConnection object doesn’t exist anymore
hmm alright thanks
but what if i use the command if the bot is not in the voice channel
then it will just join and then leave
Okay, where’s the problem?
how can you set the timestamp of an audio resource/stream
How would I listen for a resource having finished playing?
I made so the bot to leave the voice channel when there is nobody in it, but if you have joined and the person that has been in it when the bot has joined leave, the bot does not detect you as a member and it leaves too, any ideas how to make it to continue being in the voice channel, this is the code that I have made:
client.on('voiceStateUpdate', (oldState, newState) => {
const { getVoiceConnection } = require('@discordjs/voice')
const connection = getVoiceConnection(oldState.guild.id)
// if nobody left the channel in question, return.
if (oldState.channelId !== oldState.guild.me.voice.channelId || newState.channel)
return;
// otherwise, check how many people are in the channel now
if (oldState.channel == null) return;
if (!oldState.channel.members.size - 1)
setTimeout(() => {
try {
if (connection) connection.destroy()
} catch (error) {
console.log(error);
}
}, 1000); // (1 sec in ms)
});
Hey! Im having an issuse, i try to take interaction.member.voice.channel and it returns me undefined. member.voice exists and its with my id, also have GUILD_VOICE_STATES in my flags.
And is that member in any VoiceChannel at the moment? If not channel is undefined for a good reason
Yep, im on a vc
Then the channel isn’t in the bots cache. Try channelId if that’s defined and fetch with it
Does someone have an example for receiving an opus stream from a vc using @discordjs/voice?
guys i need is this bot to remove the thing where the bot stop plays when im leaving the VC . can you help how to remove it? https://github.com/SudhanPlayz/Discord-MusicBot
u want it to keep playing music that no one can hear, using bandwidth and cpu resources for no reason.. ?
yes!
discord.js v12 is unsupported and will stop working btw
voice 0.6.0 release shows how to
The player.on('idle' event should fire
I havent really seen anything online about this, so I guess Ill ask it here.
How am I able to ask if there is no one in the voice channel then say to disconnect upon having 0 people in the channel.
listen to voiceStateUpdate and check for voice members size
if oldState.channel.members.size === 0?
are channel.members.size valid? check docs if that doesnt valid
Will do
and also filter to user only. exclude bot
or just set it to 1
- 1 to exlude your bot and allow other bot
If I try
if (voiceConnection.channel.members.size === -1) {
voiceConnection.disconnect()
}
``` I get the error of members is not defined
if I do
```js
if (voiceConnection.members.size === -1) {
voiceConnection.disconnect()
}
``` I get size is not defined
not like that
oh, what did I do wrong?
if(!(VoiceChannel.members.size - 1)) {
}```
VoiceChannel here is an instance of VoiceChannel
as i said before. it should placed at voiceStateUpdate event
Even with that, I get the error of size is not defined
can you log voiceConnection?
why dont use oldState.channel.members.size ? if you on voiceStateUpdate event. (use optional chaining if you didnt catch the error properly)
(node:3061) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 disconnected listeners added to [VoiceConnection]. Use emitter.setMaxListeners() to increase limit```👀
you have nested listeners
members.cache.size
Eh no, channel.members returns a collection
uhh
Check if the connection exists before you try to destroy it
Does ssomeone know why node-gyp fails when installing discordjs/opus? Using yarn pnp and node 17.9.0
You can use opusscript instead
Results in prism not finding opus
prism supports opusscript
Yeah i fixed it, it was an opusscript issue because of typescript
Name: Best Music Mix ♫ No Copyright EDM ♫ Gaming Music Trap, House, Dubstep
at Function.getInfo (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\prism-media\src\core\FFmpeg.js:143:11)
at Function.create (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\prism-media\src\core\FFmpeg.js:156:38)
at new FFmpeg (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\prism-media\src\core\FFmpeg.js:45:27)
at new DisTubeStream (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\DisTubeStream.js:70:23)
at Function.YouTube (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\DisTubeStream.js:88:16)
at DisTubeHandler.createStream (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\DisTubeHandler.js:335:37)
at QueueManager.playSong (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\manager\QueueManager.js:83:41)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async QueueManager.create (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\manager\QueueManager.js:45:25)
This is logged because <Queue>.textChannel is undefined
————————————————————————————————
Anti-Crash System
————————————————————————————————
reject
[object Promise]
Error: Cannot perform IP discovery - socket closed
————————————————————————————————
What is the problem?
Ask distube support, not djs related
why is discordjs/voice repo archived?
Because it got integrated in monorepository of discord.js (as well as collection, builders, rest)
Hey guys, how can i make my bot enter in a voice channel? I'm trying to use message.member.voice.channel.join but it's not the correct way (the error say that is not a function)
Read the guide linked in the topic
anyone have a youtube tutorial or a website guide on how to have my bot join a vc and play a local mp3 file then disconnect once finished?
Is there a way to check what someone is saying in a voice chat without a third party package
Like a speech recognition system for discord
Use ytdl-core package
Speech recognition isn’t a simple task, so no, you‘d need something to do that for you
AudioPlayerError: Audio Codec is not OPUS ```
Ok thank you
so, my bot joins the vc but isn't playing anything
const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
const resource = createAudioResource('/waiting.mp3')
const connection = joinVoiceChannel({
channelId: '964076671898644491',
guildId: '903564467323932712',
adapterCreator: client.channels.cache.get("964076671898644491").guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
player.play(resource);
connection.subscribe(player);
no errors are showing at all
You didn’t provide the directory correctly
createAudioResource(“./file”);
alr thanks
so guys have a nice day. I want to raise a question to y'all. When i have two different clients in one node app tries to connect in a server inside to two different channels. They cannot connect because of this
https://stackoverflow.com/questions/68784950/discord-js-13-channel-join-is-not-a-function
do you have any experience about this?
pass two different values for the group property in joinVoiceChannel for your two different clients and you should be able to have two different concurrent VoiceConnections for the same channel
how can My bot join au stage vocal in speaker ?
@pearl iron help this guy please

sup
Error [ERR_STREAM_WRITE_AFTER_END]: write after end ```
What’s this err 
Does @discordjs/opus require Visual Studio to work?
Because I am getting a problem that says that Visual Studio not found
it uses node-gyp to build, which requires various things depending on OS
see the following for details: https://www.npmjs.com/package/node-gyp#installation
ok
Do I just install node-gyp?
you don't have to, I've just linked the prerequisites to use node-gyp
I don't understand; how can I fix the problem?
are you on windows?
yes I am using windows 11 home
then look at the section "On Windows" on the node-gyp installation page
ok
this is a solution to connect every bot in a same channel but i still can't connect my bots to different channels in same guild
i tried it can connect to different channels with group option only. But in discord player i need to fork and apply that fix i think.
Umm, every discord user can only be in one VoiceChannel at a time, that applies to bots as well…
You need one player per VoiceConnection if that’s what you mean. A player can’t be used by several bots at the same time
Does discord.js use ffmpeg for anything related with voice receiving?
It shouldn't as it should just be emitting opus packets
can i destroy player like connection?
How do I make bot leave vc after 5 mins of inactivity ?
setTimeout + connection.destroy()
No, you can only stop the player
no that first solution was enough to let me underestimate the situation. thank you 🙏
okay
Has anyone ever experienced a bug where playing audio from a local file works amazing but remote url playback doesn't always work?
Playing from a remote url with content type audio/mpeg works for a few hours! But after few hours of playback it stops on a few shards?
I see that it goes to ready, and starts buffering, but never starts playing?
vs the shards or local file that works it goes to ready, buffering, playing?
it's weird because its the same code running but on some servers it doesn't work and some servers work, also playing grom local files always works on all servers
not working
Connection transitioned from ready to ready
Audio player transitioned from idle to buffering
The audio player has started buffering!
working example
Audio player transitioned from idle to buffering
The audio player has started buffering!
Audio player transitioned from buffering to playing
The audio player has started playing!
const discordPlayer = createAudioPlayer();
const voiceChannelConnection =
getVoiceConnection(voiceChannel.guild.id) ||
initConnection({ voiceChannel });
await entersState(
voiceChannelConnection,
VoiceConnectionStatus.Ready,
30e3,
);
const voiceChannelConnectionSubscription =
voiceChannelConnection.subscribe(discordPlayer);
discordPlayer.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
discordPlayer.on(AudioPlayerStatus.Buffering, () => {
console.log('The audio player has started buffering!');
});
discordPlayer.on("stateChange", (oldState, newState) => {
// TODO: check if we need this
if (newState.status === "idle") {
voiceChannelConnectionSubscription.unsubscribe();
// voiceChannelConnection.destroy()
}
console.log(
`Audio player transitioned from ${oldState.status} to ${newState.status}`,
);
});
discordPlayer.play(audioResource);
};``` code example
how do I listen into a voice channel with my bot?
the reason for this is because I wanna make a bot to make a transcript of every admin meeting in my server
<VoiceConnection>.receiver.subscribe(<UserId>)
returns an opus stream
thanks
Hello,
I am making a 24/7 command but the bot keep stopping without any errors, and I should rerun the command to proceed with the music.
const connection = await joinVoiceChannel({
channelId: channel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator
})
var stream = await ytdl(`https://www.youtube.com/watch?v=36YnV9STBqc`, {
highWaterMark: 1 << 5,
})
const player = createAudioPlayer();
const resource = createAudioResource(stream, { inputType: StreamType.Opus })
connection.subscribe(player);
player.play(resource);
player.on('error', error => {
console.error(error);
});
client.on("voiceStateUpdate", async (oldState, newState) => {
if (newState.channelId && newState.channel.type == "GUILD_STAGE_VOICE" && newState.guild.me.voice.suppress) {
try {
await newState.guild.me.voice.setSuppressed(false);
} catch (e) {
console.log(e)
}
}
})
Anyone got an idea why this is happening?
is it possible to encode / embed an mp3 file within a JS file? i'm making a very simple bot that joins a voice channel and plays a sound when a certain condition, but is it possible to include the mp3 file within my singular js file so that i don't have two files?
and yes, i am fully aware that this is very stupid
also, i'd like to avoid just having an array of bytes and dumping it into a temp file and then opening that
the answer is yes, it's entirely possible
but the answer is also do that last thing you said (except instead of dumping into a temp file, you hard code it as a buffer in your js file)
all in all, it's a terrible idea, don't do it
does anyone know what I should search up on the docs on creating a music bot?
Ah I made it, but now I changed my mind I want the bot to know if there's someone in vc if not then leave it if anyone then stay in
BTW this is timer
check VoiceChannel.members.size
You can refer to the pinned guide or switch the type of doc from stable to voice on the docs page in the sidebar
This seems to be either a ytdl or YouTube issue. You can ask on the ytdl support server.
Thank you for your answer mate, I'll check it out there!
how can u play a audio mp3 file uploaded by a person in vc without having audio file saved in local folder?
it's supposed to be like this ```const playSoundUrl = async ({ voiceChannel, audioUrl }) => {
const audioResource = createAudioResource(audioUrl, {
inputType: StreamType.Arbitrary,
});
console.log("Playback_sound", audioUrl)
try {
await playSound({ voiceChannel, audioResource });
console.log('Played_successfully!', audioUrl);
} catch (error) {
/**
* The song isn't ready to play for some reason :(
*/
console.error("Failed_to_play ", audioUrl, error);
}
};``` plus this #archive-voice message but sometimes it stops working for me
you want to host the audio file somewhere though
If the music crashes in the middle, it comes from the connection, you must host the bot on a vps and it will work perfectly
How do I find out the name of the channel, and not the mention via ${oldChannel}
By not doing ${oldChannel} but instead using oldChannel.name
I have the code https://sourceb.in/dZyhS5VqAk
How do I make another check for empty channels in the category?
function play(){
const player = voiceDiscord.createAudioPlayer();
const resource = voiceDiscord.createAudioResource('https://cdn.discordapp.com/attachments/879189880259870763/973195346941448262/bf1d69a1e5edf061.mp3');
const connection = voiceDiscord.joinVoiceChannel({
channelId : voice_channel.id,
guildId : message.guild.id,
adapterCreator : message.guild.voiceAdapterCreator,
});
player.play(resource);
connection.subscribe(player);
player.on(voiceDiscord.AudioPlayerStatus.Idle, () => {
connection.destroy();
});
};
play();
The bot join to the channel but I can't hear any sound
Why do you make a function out of it, don’t pass any arguments and use variables defined outside of it? Looks like unnecessary function here…
put some console.log in your code to find out if the connection gets destroyed prematurely or the player does start playing but you can’t hear it, or if it doesn’t find the resource, all the stuff you do when debugging
How do I check the category for empty voice channels?
If the channel is empty, then delete it.
this is not related to @discordjs/voice
i am trying to get data from one user (one vc) and send it to another vc (on another guild) till know i created only how i can get the stream, but what do i do with it next?
how can i send the stream? is this even possible? please ping me
No, bots can’t stream
so, the only way i can do it is to take the voice (record it) and send the record?
:c
Is it possible to change the volume of an createAudioPlayer()?
or maybe with https://discord.js.org/#/docs/voice/stable/typedef/CreateAudioResourceOptions but they only say : "If enabled, you will be able to change the volume of the stream on-the-fly." but how 
Only if you use ffmpeg and not opus
With ffmpeg we can edit the volume 
Well, djs-Voice will automatically use ffmpeg prism-media to do that when you pass true to the option you mentioned. (Edit: Mixed some stuff up here)
We can do something like resource.setVolume(0-100) or
?
resource.volume.setVolume(…)
Im gonna try, thanks!
It doesn't work pas @waxen wedge 
What doesn’t?
10 would mean 10 times as loud in this case, so you probably want 0.1
The function doesn't exist x)
Says the bot while running or your IDE?
ide only
Oh it's work xD
thanks !
TypeError: Cannot read properties of null (reading 'voice')
I am using v13 functions, by the way
is this <GuildMember>.voice?
hey sorry to bring this back after over a week but i fetched the channel with the other client and then used that for the adapter but the bots still wont play simultaneously
if i start it on one bot, then start the next, the initial one disconnects, even though i am creating a new player and connection each time
can you show the code where you connect?
after some testing I've found you need to declare separate groups for each connection
How does one do that
it's just the group option in joinVoiceChannel
it's a string
Noted thanks
We can't play a "resource" that has already been played, we have to duplicate it before starting to play it the first time?
I think so
can't hurt to do some testing on your own
I test and it's crash so I think we need to do that (for loop music)
thanks
is there a "debug" mode for djs voice? I got some weird issue sometimes the bot join VC but not playing anything
Okay so a resource is not "unique"
when I create the resource, I add it 2x to my map and when I do /skip and log, I see that it uses the same resource at the same time wtf
Okay so the solution is to create 2 AudioRessource xd
But when I do that, the audio crash after 3s lmao
Hey, how could I make my bot join (already done) and disconnect after some seconds with a wait function?
how to I check if my bot failed to join a vc? it just forces my bot offline and the console doesnt show an error despite no error handling.
even if I error handle it just forces the bot offline
Thats odd
very
I can get connection status with getconnection and see it signalling but after it doesn't tell me if it failed just sits there
;-;
you execute the cmd and it just crashes without log?
yup
Send your code
it goes offline before the while loop which seems to be right as it runs joinvoicechannel
while loop still runs despite that but after counting to 3 and sending sorry couldnt join the bot is dead.
console tells me nothing and I cant ping pong the bot
const connection = ...
.catch((e) => {
console.log(e)
}
```We will have the error
I get catch is not a function
is this catch correct?
Im so stupid oops
kinda hard to catch an error when there isnt one
from the moment you define joinVoiceChannel, the bot is supposed to join directly so the problem comes from there (except if it can't pass the tests, a console.log(true) to check just above the connection can be interesting)
I might have to check the ID provided instead then
And what's vcID & guildID ?
purposes is to simply join vc I tell it to
Are you sure to give the right ids x) ?
i'm intentionally not as to error check, it works as expected when real IDs are provided
now im wondering if I can crash someones bot by deleting the vc 10ms after sending a ;;play command
timing would be close but i'm betting its possible
welp i'm gonna try
You can add entersState checks to make sure the connection is successful
Hello, I'm new in making discord bots and I have issue with voice connection.
I used discord.js v13 and discordjs/voice 0.9, code is on typescript. So I'm trying to make connection method, but I can't get what I have to put in adaptorCreator.
Also I would be glad if you can advice me some good guides to make musical bot.
@frigid wedge ^
It works, thank you
Is there a way to destroy a connection but keep the bot in VC?
no
That wouldn’t make any sense. How can it be in the channel but not connected to the channel
Can I have help please?
Network issue, not DJs related
Something like when u close discord while being in VC
I want to recreate that for the bot but have no idea how
Set status to invisible (appear offline)
Not the online status. Just the connection
Hey guys, i am trying to connect my bot to a voice channel but i am having some issues.
i keep getting this error:
node:internal/modules/cjs/loader:488
throw e;
^
Error: Cannot find module '**path**/node_modules/@discordjs/voice/dist/index.js'
at createEsmNotFoundErr (node:internal/modules/cjs/loader:954:15)
at finalizeEsmResolution (node:internal/modules/cjs/loader:947:15)
at resolveExports (node:internal/modules/cjs/loader:482:14)
at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (**path**/bot_voice.js:21:15)
at Module._compile (node:internal/modules/cjs/loader:1099:14) {
code: 'MODULE_NOT_FOUND',
path: '**path**/node_modules/@discordjs/voice/package.json'
}
I think there is an issue with the discordjs/voice package, but i cant understand whats wrong 😦
Has anyone ever been through this problem? Or, does anyone know how i can solve this?
Prob need to reinstall the voice package
i got it. the package-lock.json file had some wierd issues. i simply deleted it and reinstalled it
When connection to a voice channel, i wait for the connection to be created using await entersState(connection, VoiceConnectionStatus.Ready, 30e3); but the connections never gets ready, and ends up aborting and crashing my bot dispite this being inside a try catch:
connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 10e3);
return connection;
} catch (error) {
connection.destroy();
throw error;
}
After the time runs off, i get this message:
node:events:970
reject(new AbortError(undefined, { cause: signal?.reason }));
^
AbortError: The operation was aborted
for the record, the reason it would crash is because you're rethrowing the error in your catch block
Oh, ye, thanks. Didn't know it would break it. All the programs i've used it before weren't "threaded" so it made sense to stop on those 🙃
Hello guys! Maybe someone met the same problem of switching between two players on one connection. I'm developing a bot that plays music from a URL (via .play <URL> command) and handles voice state changes (like join, leav, mute, etc.) with playing sound. I use two player for music and sounds. If voice change handled while music is playing I try to paused music player, then creating new player for sound and subscribe connection for that. When sound layer become idle I try to subscribe connection for music player and unpaused that.
Separately, these two parts work fine. But if I try to play sound while music is playing, my temporary sound player heangs in buffering state. However if i try to play music (by .play command) during the sound is playing, it's work fine.
You can find my code here:
For .play command https://github.com/rofl3228/discord-voice-bot/blob/main/src/actions/play.js
For handling voice state changes https://github.com/rofl3228/discord-voice-bot/blob/8e3134ff65a0df4f6e44fff5c8e82739a115c775/src/core/bot.js#L81
Thanks for your attention and sory for my english)
How do I control a resource. I want to change the volume while it's playing but when I create the resource and write .volume.setVolume(1) at the end then it tells me that the resources has already been ended. Also I want to somehow loop songs/queues
There is not way to replay a resource. You will have to create a new resource to play it again
hello, i wanted to add a pause command to my bot using .pause() but it dont work :/ can someone help me pls ?
const { joinVoiceChannel, createAudioPlayer, createAudioResource} = require('@discordjs/voice');
const player = createAudioPlayer();
if(message.content.startsWith(prefix + 'pause')){
player.pause(true);
}
if thats all of your code im not surprised. You arent playing anything on that player
Can i send you my code by private msg please ?
send it here
there is a lot
a resource cant be paused
how exactly didnt it work for u?
when i use the !skip or !pause command the song dont stop or pause
without pausing the ressource it dont work to
const audio = discordTts.getVoiceStream("Hallo")
const audioResource = createAudioResource(audio, {inputType: StreamType.Arbitrary, inlineVolume: true})
if(!voiceConnection || voiceConnection?.status === VoiceConnectionStatus.Disconnected) {
const channel = client.channels.cache.get("906641697507774515")
voiceConnection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator
})
voiceConnection = await entersState(voiceConnection, VoiceConnectionStatus.Connecting, 5_000)
}
if(voiceConnection.status === VoiceConnectionStatus.Connected) {
voiceConnection.subscribe(audioPlayer)
audioPlayer.play(audioResource)
}
reject
[object Promise]
AbortError: The operation was aborted
What is the problem?
Might help to see the full error or tell us what line the rejection occurs
This is the whole error
No stack trace?
Then you have your own error handler somewhere and it doesn’t log the full error
Anti-Crash System in this case also is a Anti-Debugging System
What should I do now?
Find out where the error exactly occurs.
How to do it?
Not djs related
But how do I set the volume?
I know that it is possible to set it while it is playing
did u enable volume when creating the resource?
yes
it always tells me: This resource has already ended. Even if I set the volume instant at the creation of the resource
🤔
is the resource being played at that time?
like I said. Directly at the creation it gives me an error. Also it wouldn't be a problem when it is playing
No
id assume thats the reason
the resource needs to be played in order to change volume
It works now
Thanks
👍
Hi mates, does anyone know how to fix this? I'm using typescript@4.6.4 and @discordjs/voice@0.9.0
by adding
// @ts-ignore
on top of it
Edit: Client resolved [at symbol]ts to a user. Sorry for ping
The error is on djs voice's end
also, that error doesn't stop tsc from working. It's just ignored.
can i do anything
Looks like you do something wrong when sharding, adding more than one listener to your shard childprocesses

I'm trying to get the decibel level (or some measurement of loudness) of any given member in a voice channel. My bot already joins voice channels, and is able to read the raw data from other users with this test code
let connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator as DiscordGatewayAdapterCreator,
});
for(const member of channel.members) {
let sub = connection.receiver.subscribe(member[1].id)
sub.on('data', data => {
console.log(data)
})
}
How can I convert this data into something I can use?
the sub is an opus packet stream
I imagine ffmpeg can handle this
if not, the prism-media package that djs/voice uses can convert opus streams to raw pcm (which ffmpeg does handle)
const joinchat = client.channels.cache.get("976225179090944050");
joinchat.join();
});```
Why is joinchat.join() not a function?
VoiceConnection (extends VoiceConnectionEvents)
A connection to the voice server of a Guild, can be used to play audio in voice channels.
VoiceChannel.join() isn't a thing anymore
does anyway know why im getting FFmpeg not found even thought i have it installed
npm i ffmpeg-static@latest
ye i have that but it doesnt work
just had to restart my pc and manually installing it worked
const connection = getVoiceConnection(myVoiceChannel.guild.id);
What do i need to put for myVoiceChannel since it is giving me the error that it is not defined
const { joinVoiceChannel } = require('@discordjs/voice');
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
I guess its this connection, or just interaction.guild.id i guess ?
how can i pass on channel here since it is saying channel is not defined
``` if (commandName === 'join') {
await joinVc();
} else if (commandName === 'stop') {
await LeaveVc();
}
});
function joinVc() {
connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
let resource = createAudioResource(createReadStream(join(__dirname, '.mp3')), {
inlineVolume : true
});
resource.volume.setVolume(0.2);
console.log(join(__dirname, '.mp3'));
const player = createAudioPlayer();
connection.subscribe(player);
player.play(resource)
console.log("done");
}
function LeaveVc() {
}```
how do I check if a file link can be played?
Fetch the link and check response content type
How can i fetch the player for the guild?
How can I use ffmpeg (with fluent-ffmpeg)'s volumedetect filter on an AudioRecieveStream from a person in a voice channel? My goal is to get the mean_volume value returned from ffmpeg
how do I make a bot automatically become a speaker when joining a stage channel assuming it has permission to do so?
guild.me.voice.setSuppressed(false)
That does not work on a Stage Channel
VoiceState#setSuppressed()
Suppress/unsuppress the user. Only applicable for stage channels.
it's made for them
Error [VOICE_NOT_STAGE_CHANNEL]: You are only allowed to do this in stage channels.
That´s the error I get
then whatever channel you have there isnt a stage channel
dude did you ever bother reading the error
xD
I didn´t sleep much today, still having issues that I don´t know how to solve
if (channel.type == 'GUILD_STAGE_VOICE') {
let stageName = message.guild.members.cache.get(client.user.id).nickname;
if (stageName == null) stageName = client.user.username;
message.guild.stageInstances.create(channel.id, {
topic: `🎶 ${stageName}`,
privacyLevel: 'GUILD_ONLY'
});
message.guild.me.voice.setSuppressed(false);
}
what are they?
well, did you even join the stage at that point
Yes
at what point did you do that
GuildMember#displayName
The nickname of this member, or their username if they don't have one
const channel = message.guild.channels.cache.get(args[0]);
const connection = voiceDiscord.joinVoiceChannel({
channelId: channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
selfDeaf: true,
});
const player = voiceDiscord.createAudioPlayer();
const resource = voiceDiscord.createAudioResource(radio[args[1]]);
player.play(resource);
connection.subscribe(player);
player.on(voiceDiscord.AudioPlayerStatus.Idle, () => {
connection.destroy();
message.reply(`:x:**¡La estación de radio no funciona!**`)
});
if (channel.type == 'GUILD_STAGE_VOICE') {
let stageName = message.guild.members.cache.get(client.user.id).nickname;
if (stageName == null) stageName = client.user.username;
message.guild.stageInstances.create(channel.id, {
topic: `🎶 ${stageName}`,
privacyLevel: 'GUILD_ONLY'
});
message.guild.me.voice.setSuppressed(false);
}
Probably here are very important mistakes 🤷
use this instead of nickname
okey
my guess would be you didnt wait til the bot actually connected and is ready to be unsuppressed
also why do you destroy the connection when the audioplayerstatus is idle
the audioconnection literally starts in idle
Idle - the initial state of an audio player.
why you listening in a command and why you are unsuppressing in idle
I saw that in radio bot in github, the radio works perfect btw, only issue I have is that the bot doesn´t join as speaker. It is supposed to destroy the connection when there no signal on the radio URL
in the Ready state, set suppressed to false
on connection that is
https://discordjs.guide/voice/life-cycles.html#subscribing-to-individual-events
Okey, ty 4 ur help
something like what,
There’s alooot of there’s warns,
And sometimes the bot disconnect from all rooms in one time
Share a bin link of your sharding code in #archive-sharding and I‘ll take a look
The last question (this help was perfect ❤️ ), how can I know if already exists an stage instance on the channel?
check stagechannel.stageInstance I suppse?
Okey, I should learn how to read the docs xD, very thankful for ur time
how do make my bot stay in voice channel like 24/7 , for ex
bot will join the defined channel when its on
idk much about voiceStateUpdate so anyone / docs can help me ?
Don’t you get kicked from VC for being inactive?
not me
and its not music bot
is there a way to make the bot leave vc once a sound has finished playing? when i set a timeout, it leaves after about under a second or a second idk....
but when the timeout isn't there, it plays the sound like normal
(question originally posted in #djs-help-v14 because i'm dumb
)
connection.on(VoiceConnectionStatus.Ready, () => {
canSpeak = false
console.log('The connection has entered the Ready state - ready to play audio!');
setTimeout(() => {
canSpeak = true
player.stop(true)
connection.disconnect()
}, 2.6)
});
Well, you tell it to stop playing and disconnect after 2.6 Milliseconds. What did you expect it to do?
it's about the same length as the sound it plays, of course i want it to disconnect after 2.6 MS
You have a sound that only lasts 2.6 ms?
wait i see the problem now
damn it i needed * 1000
is it possible to recieve audio with a bot, or is that not an option right now?
i see that it was possible previously, but also that it's not supported, so i assume it's prone to breakage.
It's possible
thank you very much, but i've run into another issue. it says that it cannot find module 'node-crc' here, and when i try to install it, it says that it can't find the rust executable (even though i just installed rust and restarted my computer)
ok, that works now, i just had to restart again. i blame windows updates.
now, though, i'm getting this error on the same line
I'm trying to get the relative volume of a given user in a voice channel, and I'm having some issues (I've tried ffmpeg, it can distinguish between whispering and talking, but not talking and screaming). I'm trying to use AudioContext now, by interpreting the first answer from this post https://stackoverflow.com/questions/33322681/checking-microphone-volume-in-javascript
Is there a way to somehow convert/cast from an AudioRecieveStream/Readable to a MediaStream? (which is required to use AudioContext#createMediaStreamSource())
Hey, I'm lost to how to use the discordjs voice stuff. I'm trying to migrate from v12 to v13 on discordjs. But what connection should I use?
I tried following this: https://discordjs.guide/voice/life-cycles.html#subscribing-to-individual-events, but I'm lost to where the connection is coming from. Could anyone help me out here? 😅
Look at the next section of that guide and your questions get answered😉
Well, that's what I tried: ```ts
client.guilds.cache.map(guild => {
const vcConnection = getVoiceConnection(guild.id);
console.log(guild.id, vcConnection);
for(const vcListenerConfig of vcListenerConfigs) {
vcConnection?.on(vcListenerConfig.name as VoiceConnectionStatus, vcListenerConfig.execute as any);
}
console.log(`Loaded ${vcListenerConfigs.length} voice listeners for guild ${guild.id} `)
})
But, `vcConnection` is always empty 🤔
Suggestion for @pulsar dew:
Library: Cheat sheet - Creation
If you try to call joinVoiceChannel on another channel in the same guild in which there is already an active voice connection, the existing voice connection switches over to the new channel.
read more
But, I don't want the bot to join a channel. I want to track member join/leave events etc. Or am I looking in the wrong place then? 😅
Yes you are…
Documentation suggestion for @pulsar dew:
(event) Client#voiceStateUpdate
Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
oh, thanks a lot 😊
hi
in my music bot i have a error
can you help me?
Error: aborted
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:402:19)
at TLSSocket.emit (node:events:538:35)
at node:net:687:12
at TCP.done (node:_tls_wrap:580:7) {
code: 'ECONNRESET'
}```
v16.14.2
What is difference between <VoiceConnection>.destroy() and guild.me.voice.disconnect()?
The first is you leaving the channel, the second is you kicking yourself out of it
Thanks!
I have a command to join a voice channel and play an audio file (attached to a slash command); TypeScript is giving me this error, but otherwise it works if it is ignored
You can safely ignore it. I believe it’s fixed in v14
Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist
Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist
Last metadata expiration check: 0:12:41 ago on Sun 22 May 2022 10:27:48 AM GMT.
No match for argument: ffmpeg
Error: Unable to find a match: ffmpeg
then anyone know how to install ffmpeg on oracle linux?
doesn't work because I tried
Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist
Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist
Last metadata expiration check: 0:17:54 ago on Sun 22 May 2022 10:27:48 AM GMT.
epel-release-latest-8.noarch.rpm 29 kB/s | 23 kB 00:00
Package epel-release-8-15.el8.noarch is already installed.
Dependencies resolved.
Nothing to do.
Complete!
[opc@rais-bot ~]$ sudo yum-config-manager --enable powertools
Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist
Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist
Error: No matching repo to modify: powertools.
[opc@rais-bot ~]$```
Error: No matching repo to modify: powertools.
- nothing provides libSDL2-2.0.so.0()(64bit) needed by ffmpeg-4.2.6-1.el8.aarch64
(try to add '--skip-broken' to skip uninstallable packages or '--nobest' to use not only best candidate packages)```
how to install libSDL2-2.0.so()(64bit)
Fix the mentioned repo files
Pretty much just comment out all failovermethod
thanks
Problem: conflicting requests
- nothing provides libSDL2-2.0.so.0()(64bit) needed by ffmpeg-4.2.6-1.el8.aarch64
(try to add '--skip-broken' to skip uninstallable packages or '--nobest' to use not only best candidate packages)```
that's the only other thing I have a problem with
then anyone know how to fix it?
Hello, when I try to stop my bot from playing using player.stop it does not stop it but it dont give me an error
It's like nothing happen
I'm 100% player.stop is executed by my code and i try different things without succes
If someone could help me that would be great
Here my code
Client.on("messageCreate", message => {
try {
const { createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice');
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
if (message.content.startsWith(prefix + "joue")){
if(!message.member.voice.channel){
message.reply("Vous n'êtes pas dans un channel vocal");
return;
}
var lien = message.content.substring('!joue '.length);
if(message.member.voice.channel){
if(lien.startsWith('https://www.youtube.com/watch?')){
const ytdl = require("ytdl-core");
const { joinVoiceChannel, createAudioResource } = require('@discordjs/voice');
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
message.channel.send('Lecture en cours');
const stream = ytdl(lien);
const ressource = createAudioResource(stream);
const { AudioPlayerStatus } = require('@discordjs/voice')
player.on(AudioPlayerStatus.Playing, () => {
console.log('Lecture en cours');
});
player.play(ressource);
connection.subscribe(player);
player.on(Discord.AudioPlayerStatus, () => {
connection.destroy();
});
};
};
if(message.content.startsWith(prefix + 'pause')){
player.pause();
message.channel.send("Vidéo mise en pause");
}
if(message.content.startsWith(prefix + 'unpause')){
player.unpause();
message.channel.send("Vidéo relancé");
}
if(message.content.startsWith(prefix + 'skip')){
player.stop();
message.channel.send("Vidéo skip");
}
};
} catch (error) {
console.log('Erreur : ' + error);
return
};
});
The player is only declared in the messageCreate event; I think you have to put
let player
before this part and then use the variable.
And you are lucky mine doesn't want to play audio at all. I tried everything
thx bro
but i dont work, it return me an error
What's the error?
and it doesnt play the youtube link
Check your brackets... you might be closing them at the wrong place or so because you didn't initiate player before you call player.stop()
okay bro thx i'll try
You make a new player every message created, must reference the one you used for player.play() when you run player.stop().
how can i do that ?
Just save it somewhere globally. Like in your client object.
hi
in my music bot i have a error
can you help me?
Error: aborted
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:402:19)
at TLSSocket.emit (node:events:538:35)
at node:net:687:12
at TCP.done (node:_tls_wrap:580:7) {
code: 'ECONNRESET'
}```
v16.14.2
Hi ! I came here to ask for advice from people who already tried to play local sounds with @discordjs/voice. I am trying to do that with my bot but no sound is coming out. I debugged a bit and found out the AudioPlayer's state kept being in buffering after loading the resource. I tried a lot of things I found in the doc or SO, but nothing worked so far. :/
My code:
const { createAudioPlayer, NoSubscriberBehavior, createAudioResource } = require("@discordjs/voice");
const { createReadStream } = require("fs");
const voicePlayer = createAudioPlayer({
behaviors: {
"noSubscriber": NoSubscriberBehavior.Pause
}
});
function addAudioRessource(ressource) {
voicePlayer.play(createAudioResource(createReadStream("./assets/sounds/" + ressource)));
console.log(voicePlayer.state.status) // buffering after playing the resource
}
function stopVoicePlayer() {
voicePlayer.pause();
}
module.exports = { voicePlayer, addAudioRessource, stopVoicePlayer };
const { joinVoiceChannel } = require("@discordjs/voice");
const { ButtonInteraction } = require("discord.js");
const { bot } = require("..");
const { GUILD_ID, VOICE_CHANNEL } = require("../../config");
const { voicePlayer } = require("../core/voice");
/**
*
* @param {ButtonInteraction} interaction
*/
function joinVocal(interaction) {
const guild = bot.guilds.cache.get(GUILD_ID);
let voiceConnection = joinVoiceChannel({
guildId: GUILD_ID,
channelId: VOICE_CHANNEL,
adapterCreator: guild.voiceAdapterCreator
});
voiceConnection.subscribe(voicePlayer);
bot.voiceConnection = voiceConnection;
interaction.reply({ content: "J'ai rejoint le salon vocal !", ephemeral: true });
}
module.exports = { joinVocal };
Not best practices, but it's only a small bot not designed for public use.
If someone has a fix or a working code snippet, I'd be glad to hear it ^^
Also my dependencies:
{
"dependencies": {
"@discordjs/opus": "^0.5.3",
"@discordjs/voice": "^0.9.0",
"discord.js": "^13.7.0",
"ffmpeg-static": "^4.4.1"
}
}
One thing I found that often helps is to use absolute paths for local resources…
I tried the __dirname variable
Didn't change much, I can still try again though
https://i.discord.fr/OCAf.png still buffering, even with the absolute path for the file
You can pass the filename directly into createAudioResource afaik, no need for the readStream
I tried first, didn't work, so I tried the readStream
Tried again, same result
Which of the optional packages do you have installed?
sodium, discordjs/opus and ffmpeg-static?
Here
No sodium?
Nope, I should try and install it then ?
Yeah
This one ? https://www.npmjs.com/package/sodium
npm i libsodium-wrappers@latest
Thank you, I'm going to try that
Nope, not working either. It is still buffering.
Why not sodium? It’s the recommended one from the guide
Tried the regular sodium too, still buffering
Any idea ?
Gosh, I'm having absolutely no luck converting the voice stream to a different format. Is anybody free who could potentially help?
ah yeah you’re right
Doesn't seem to work even with sodium installed
Do you get any errors?
Is your VOICE_CHANNEL variable a channelId?
Also your log only logs the state at that specific moment.. you might wanna listen to the statechange event and log the player's state
No error, aside from the fact that the AudioPlayer's state is always buffering. i'm going to log the statechange event, see if that works, but one thing is sure, so sound is played at all
Hey, so I'm not too sure where to ask this so I apologise if this is in the wrong place. I have a youtube dl downloader from a URL, taken I think, from one of the discord js examples. But how would I change this into an AudioResource with a URL with just an audio file on it. Say url.com/song.mp3
return new Promise((resolve, reject) => {
const process = ytdl.exec(video_url, {
o: '-',
q: '',
f: 'bestaudio[ext=webm+acodec=opus+asr=48000]/bestaudio',
r: '100K',
}, {
stdio: [
'ignore',
'pipe',
'ignore'
]
});
......
process.once('spawn', () => {
demuxProbe(stream).then((probe) =>
resolve(createAudioResource(probe.stream, {
metadata: this,
inputType: probe.type
}))
).catch(onError);
}).catch(onError);
});```
Thank you for any help!
Okay so it seems the AudioPlayer goes through the playing state but no sound is actually played, it instantly goes autopaused
https://i.discord.fr/86pI.png
Could that be because of the nosubscriberbehaviour?
Removed the behavior but still the same
Guide says
AutoPaused - the state a voice connection will enter when the player has paused itself because there are no active voice connections to play to. This is only possible with the noSubscriber behavior set to Pause. It will automatically transition back to Playing once at least one connection becomes available again.
Make sure your bot actually enters the voice channel so it can play sound there
It is
I make it join first and then play the sound manually https://i.discord.fr/vCcW.png
I put these lines to debug the states of the AudioPlayer
voicePlayer.on("subscribe", () => console.log("subscribe"))
voicePlayer.on("unsubscribe", () => console.log("unsubscribe"))
voicePlayer.on("stateChange", (oldState, newState)=> console.log(oldState.status + " " + newState.status))
There is a subscriber so nothing coming from here
Log the statechange event for the connection as well and see if it becomes ready
Dependency Report:
Core Dependencies
- @discordjs/voice: 0.9.0
- prism-media: 1.3.2
Opus Libraries
- @discordjs/opus: not found
- opusscript: 0.0.8
Encryption Libraries
- sodium-native: not found
- sodium: not found
- libsodium-wrappers: 0.7.10
- tweetnacl: not found
FFmpeg
- version: 3.4.10
- libopus: yes
--------------------------------------------------```
Relevant Code:
```const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_VOICE_STATES] });
const { createAudioPlayer, createAudioResource, joinVoiceChannel, getVoiceConnection } = require('@discordjs/voice');
const audioPlayer = createAudioPlayer();
client.guilds.fetch(guildId).then(guild => {
joinVoiceChannel({
channelId: channelId,
guildId: guildId,
adapterCreator: guild.voiceAdapterCreator
});
const audioConnection = getVoiceConnection(guildId);
const audioSubscription = audioConnection.subscribe(audioPlayer);
});
if(...) audioPlayer.play(createAudioResource('sound.mp3'));```
Basically I'm trying to play a simple 3 second mp3 file in a voice channel. When I was hosting off glitch.me, everything worked fine. But I recently upgraded to VPS hosting and transferred everything over. Now no sound plays, but AudioPlayerStatus.Playing does trigger without any errors. I've tried to include the full filepath to the file. And I'm on CentOS which seems to be unable to install @discordjs/opus and sodium. Any idea what the problem could be?
Does not go into the AutoPause state either.
I have a slight problem with one of the codes, that if I tell the bot to play a song, it won't stop repeating it
Now I look dumb. I didn't know I had to select the GUILD_VOICE_STATES intents in the Client constructor, now it's working just fine !
Thank you for the advice
I know this is v12 code but I'm really stuck
why doesn't message.guild.voice.connection.dispatcher.resume() work?
We don’t support v12. Update if you want our help
So, i'm developing a music bot, how do i do the bot detect that it been kicked out of the voice channel and then destroy the queue?
Personnaly i use this for disconnect my bot
const { getVoiceConnection } = require('@discordjs/voice');
const connection = getVoiceConnection(message.guild.id)
connection.destroy();
Continuation on this
Immediately goes to Idle state after Playing state
Most likely an invalid path
CentOS 7 on a VPS
Tried using the mp3 as a local file with relative/absolute paths, uploading it, and also posting it on discord and using the cdn.discord link
Did you use path.join(__dirname, relativePath)?
tried that too, yes
directly and with createReadStream
Could you log fs.existsSync(path.join(…))?
sure give me a second
I’m not sure how you managed to fetch a guild before even logging in
Can you also move the code into the ready event?
i logged in, just didn't include that code since discord character limit
Is the code in a client event?
the fetch + declaring connection/subscription happen in the client ready event
play happens elsewhere
Use pastebin next time
btw it logs true
Are you sure the audio isn't 1 second long?
Or said it was 3 seconds
its ~3 seconds long, but goes idle in like 0.1 seconds
it worked perfectly with the same code (changed paths ofc) when i was hosting on glitch
problem only started once i migrated to a vps
I’m assuming ur testing on ur host rn?
correct
bot is joining the channel just fine, and the event to play the sound is triggering (tested through logging + player enters playing state)
Did more testing
path.resolve didn't fix anything
When I split audioPlayer.play(createAudioResource('sound.mp3')); into two lines var audioResource = createAudioResource('sound.mp3'); and audioPlayer.play(audioResource);, it immediately errors Cannot play a resource that has already ended. even on the first time playing
Can you add a log to make sure that createAudioResource and .play is only called once?
Use const instead of var for good measure too
sure
also its seeming like the resource is ending as soon as it's created
i assume that just means error loading it so it's read as 0s length, therefore already ended?
more information: i split it and globally declared the AudioResource, which causes the errors
logging shows that it errors on first call of .play
if i revert it back to the single line i had before, everything is only called once (no error)
could it not error out because the resource played so soon after it's created?
Could it be because I’m using opusscript instead of @discordjs/opus and libsodium-wrappers instead of sodium?
probably not
How about a CentOS 7 issue?
Yea, don’t globally declare resources
It’s not reusable
Yeah it was only for testing purposes
Was trying everything since I have no idea what’s causing it
so it goes buffering -> playing -> idle, never paused/autopaused
Audio Resource logs
also ran ffmpeg as ffmpeg -i ping.mp3 2>&1|grep Duration to verify that the mp3 file is 2.59s long, not 0s
just tried with a ~4 min webm in case it was the format or short duration messing with it, same result
What error do you get when installing @discordjs/opus?
Gonna try that one first bc opus is deprecated
tried using python3 and python3.10 + upgrading a few other things i forget
i think i found someone saying its broken on CentOS
Oh great, g++ issue
npm ERR! g++: error: unrecognized command line option '-std=gnu++14'
Can you run g++ -v?
4.8.5
unless you want the whole thing
Nah, that’s good
very last resort i can swap OSes
I believe there’s a way to update gcc/g++
alright imma try that
I believe you need at least v5, but the latest is v12
that worked
had to retry it a few times but i got it
seems the sound is still not playing though
time to try to install sodium?
replaced opusscript with @discordjs/opus and tweetnacl/libsodium-wrappers with sodium
not working yet but i feel it's a step in the right direction
well now im extra confused
here's the output for the working version hosted on glitch
same exact as my vsp
New here: is the voice guildMemberSpeaking event reliable or still experimental (or basically fighting whatever support Discord may have dropped for speaking bits)?
How to run the voice basic-example.ts? I clone the repo, cd to voice\examples\basic, and then ts-node basic-example.ts but get lots of tsc errors.
That solution is actually independent of py or js. Did you try doing what they suggest?
How do I fetch an Audio Stream (online radio station. It's outputting an mp3) and then play it back through a Discord bot
This is assuming it's at all possible
That is somewhat related to what I am trying to do.
Sounds like a mashup of the examples at https://github.com/discordjs/discord.js/tree/main/packages/voice/examples, which I cannot get the basic one working. :/
There is even a https://github.com/discordjs/discord.js/blob/main/packages/voice/examples/music-bot mentioned in the readme.md, but that does not exist.
The examples seem a little neglected.
I dunno yet why music-bot is missing from main https://github.com/discordjs/discord.js/tree/a0a4a2258a2ff5c306494dc929468b67eb601c39/packages/voice/examples/music-bot
It was deleted 6 days ago in https://github.com/discordjs/discord.js/commit/993eb74475727301c6b5282633610191d606afe0 with no comment why.
Maybe it was an accident?
The demo could have stayed in a skunkworks type of deprecated folder for reference and future revival
Tell me the module to search for tracks on spotify. I suspect my module is out of date
kekw 😄
I figured out my issue was I wasn't requesting the intent for voice
Some body know why I have this error with my music bot ?
R [Error]: aborted
The Error stop the current music and skip some music after
The full error :
Part one
R [Error]: aborted
at connResetException (node:internal/errors:692:14)
at TLSSocket.socketCloseListener (node:_http_client:414:19)
at TLSSocket.emit (node:events:539:35)
at node:net:709:12
at TCP.done (node:_tls_wrap:582:7) {
resource: T {
playStream: Encoder {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
encoder: null,
_options: [Object],
_required: 3840,
_buffer: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: [Function: bound onwrite]
},
edges: [ [Object], [Object], [Object] ],
metadata: null,
volume: VolumeTransformer {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_readInt: [Function (anonymous)],
_writeInt: [Function (anonymous)],
_bits: 16,
_bytes: 2,
_extremum: 32768,
volume: 1,
_chunk: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: [Function: bound onwrite]
},
Part two
encoder: Encoder {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
encoder: null,
_options: [Object],
_required: 3840,
_buffer: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: [Function: bound onwrite]
},
audioPlayer: B {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_state: [Object],
subscribers: [Array],
behaviors: [Object],
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
},
playbackDuration: 69120,
started: true,
silencePaddingFrames: 5,
silenceRemaining: -1
}
}
And here the function play :
async function play(guild, song) {
var serverQueue = queue.get(guild.id); // On récupère la queue de lecture
if (!song) { // Si la musique que l'utilisateur veux lancer n'existe pas on annule tout et on supprime la queue de lecture
setTimeout(function() {
var serverQueue = queue.get(guild.id);
if(serverQueue.songs < 1) {
var connection = getVoiceConnection(serverQueue.guildID);
queue.delete(guild.id);
connection.destroy();
}
}, 300000)
return;
}
if(serverQueue.loop === true) {
serverQueue.songs.push(song);
}
// On lance la musique
var connection = await getVoiceConnection(serverQueue.guildID);
if(serverQueue.connection === null) {
serverQueue.connection = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
}
});
}
serverQueue.ressource = new createAudioResource(await ytdl(song.url),{
inlineVolume: true,
inputType: StreamType.WebmOpus
});
serverQueue.ressource.volume.setVolume(serverQueue.volume); // On définie le volume
await serverQueue.connection.play(serverQueue.ressource);
await connection.subscribe(serverQueue.connection);
serverQueue.connection.on(AudioPlayerStatus.Idle, () => { // On écoute l'événement de fin de musique
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
});
serverQueue.connection.on("error", error => console.error(error));
serverQueue.textChannel.send({ content: `Démarrage de la musique: **${song.title}**`});
}
@icy maple i found the solution
ffmpeg installation doesn't matter, it needs ffmpeg-static
will using worker threads stop random audio lag spikes/stutters and is there any examples
Someone known what is this error?
Install sodium
well the solution on stackoverflow looks pretty universal and unrelated to discord.py or any code for that matter
but also I imagine this issue could be solved with different dependencies
the issue could also lie elsewhere ¯_(ツ)_/¯
I've personally had no issues like this on heroku (though I will say heroku isn't the best for bot hosting)
Can anyone help me with what the minimum steps are needed to get the discord.js/packages/voice/examples/basic/basic-example.ts example to work?
I'm running in to all kinds of tsc errors.
It's designed for hosting websites. For small bot applications there's no real issues, but it's not designed to handle more complex bots
You can use the events of connection.reciever.speaking instead.
Somebody ? please ?
So it's fixed, just need to pass in node v14 cause of Ytdl and add node-abort-controller
Wow! That's it! I have searched for 3 days for how to detect a user in a voice channel speaking started and stopped!
Discord.js itself needs node v16.6 or higher
👍
I have djs v13.0.0
May be it's for that it work
The djs dev version of v13 worked with node v14... I'm not sure about v13.0.0 itself although the guide says v16 is needed... just try it then lol
Also v13.3 is the at least recommend version of djs currently I think
better to have the latest (13.7.0)
I have "discord.js": "^13.0.0" in my package.json so yes the 13.0.0 is compatible with node v14.x.x
What major changes between 13.0.0 and 13.7.0 ?
none
my bot wont join my voice channel. https://pastebin.com/ABFusnMk
x_id => xId
TypeError: message.member.voice.channel.join is not a function
at execute (/home/runner/NodeDisBot/index.js:83:56)
at runMicrotasks (<anonymous>)
/home/runner/NodeDisBot/node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/runner/NodeDisBot/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/NodeDisBot/node_modules/discord.js/src/rest/RequestHandler.js:51:14) {
method: 'post',
path: '/channels/964318578650279979/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
This is what I'm getting can anyone help me with it?
when I do -play
- Voice system completely changed
- Don’t send an empty message
Documentation suggestion for @granite python:
AudioPlayer (extends AudioPlayerEvents)
Used to play audio resources (i.e. tracks, streams) to voice connections.
How would I define channel
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
?
ReferenceError: channel is not defined
…
message.channel
not that...
const channel = message.channel;
thats the wrong snippit its supposed to have the whole thing
?
nvm
what has play in serverQueue.connection
.play(ytdl(song.url)) changed to?
consider reading the guide for djs/voice 🙂
Suggestion for @granite python:
Library: Cheat sheet - Playing audio
read more
thank you very much
can I do player.onfinish
player.on("finish", () => {
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
play(a,b); is a custom method
nvm I can just do this
player.on(AudioPlayerStatus.Idle, () => {
player.play(getNextResource());
});
My bot dosnt play the resource i gave it. It just joins the channel and thats it. But for some reason it still logs the Audio player is in the Playing state! message. Code: https://pastebin.com/00tVBW0R
You need the GUILD_VOICE_STATES intent
Also you don't need to get the guild and member from the cache... just interaction.guild and interaction.member would just work fine
when i put the intent in the list, it returns this: RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number: undefined. Intent line: const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.GUILD_VOICE_STATES] });
You miss the FLAGS
oh yea. oops. thx
thx it works now :)
is there a way to stream live stream audio to the voice channel?
async joinVoice(channelId, guildId) {
try {
console.log('channel', channelId)
const { voiceAdapterCreator: adapterCreator } = await this.client.guilds.fetch(guildId);
console.log('attempting connection')
const connection = joinVoiceChannel({
adapterCreator,
channelId,
guildId,
});
console.log('connection success')
const player = createAudioPlayer();
await connection.subscribe(player);
console.log('player subscribed')
return {
connection,
player,
}
} catch (err) {
console.log('joinVoice error', err);
}
}
async playAudio(player, stream) {
try {
const resource = createAudioResource(stream);
await player.play(resource);
console.log('playing music');
} catch (err) {
console.log('playAudio error', err);
}
}
So ive been debugging, and everything works fine, except that the bot wont actually play the audio? what could be the probable cause?
could i get some more code? seeing this its prob something when calling the functions
async exec(msg, args) {
console.log('init play');
const results = await this.youtube.search(args);
const result = results.pop();
console.log('result', result.title);
const voiceChannel = msg.member.voice.channel;
const { connection, player } = await this.music.joinVoice(
voiceChannel.id,
voiceChannel.guild.id
);
const stream = await this.youtube.stream(result.id);
await this.music.playAudio(player, stream);
}
heres the main execution, and the youtube is basically just a ytdl stream
is the args an array or a string?
from the exec() its an array, but it gets formatted to a string when going thru the search(). then the result is a basicInfo from ytdl
hmm. then i dont know
i found an npm package called discord-audio. It has the basics and uses ytld. you only have to put in a yt url. https://zyno-studio.gitbook.io/discord-audio/
cheers mate ill check it out
so i checked it out, and apparently i just needed to add a inputType...but without this i wouldnt have found it so thank u!
Is the voice recording reliable? I have read it's quite unstable
A parameter to check would be somewhat like a conversation bot, where you can speak to it, and it can reciprocate with context
ah np. sometimes you find the solution on a place where you try to find an alternative.
Is it possible to run multiple JoinVoiceChannel() on 1 process? That is, so that 3 bots enter the voice from 1 code, for example
what is the "voiceAdapterCreator"?
Hi! need help with my bot... after a few minutes it disconnect without reason (let's call it "ghost disconnect")... I verified and doesn't throw any error... Some days ago I just updated all the resources of the project (due I needed to implement modals and just in case)...
Also, I tried adding to verify with voicestateupdate for reconnect but, this only works if you (or someone) disconnect the bot, if was the ghost disconnect, it doesn't do anything
the dependencies, the script of events/ready.js and events/voiceStateUpdate.js are here (for avoid a looooong message):
https://gist.github.com/imkuroneko/755388f87da54f54f637692e2dfb1bea
Suggestion for @vague summit:
Library: Handling disconnects
read more
how does this method fare for you? (the important part being, does the connection follow its lifecycle as expected?)
now I added it and restarted the bot; let's see if it work in the next minutes 
thanks!
let channel = client.channels.cache.get(CHANNEL_ID) || await client.channels.fetch(CHANNEL_ID)
if (!channel) return;
const player = createAudioPlayer();
const resource = createAudioResource('https://cdn.discordapp.com/attachments/877988588233580598/892818202399219763/bruh.mp3');
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
player.play(resource);
connection.subscribe(player);
I am using this code but its not playing audio and their is no error
Yes, by providing different group parameters for each bot.
Use <Guild>.voiceAdapterCreator for it, it’s the „hook“ that djs-voice uses to connect to the VC
try {
const PremiumPlan = await Premium.findOne({ Id: message.author.id });
if (PremiumPlan && PremiumPlan.isPremium) {
//if user Premium code down here
const player = message.client.manager.get(message.guild.id);
if (!player.queue.current) {
let thing = new MessageEmbed()
.setColor(ee.embed.wrongcolor)
.setDescription("There is no music playing.");
return message.channel.send({ embeds: [thing] });
}
// Check that user is in the same voice channel
if (message.member.voice.channel.id !== player.voiceChannel) {
let thing = new MessageEmbed()
.setColor(ee.embed.wrongcolor)
.setDescription("User is in the same voice channel");
return message.channel.send({ embeds: [thing] });
}
player.setNightcore(!player.nightcore);
const msg = await message.channel.send(`Turning ${player.nightcore ? 'ON' : 'OFF'} **nightcore**. This may take a few seconds...`);
let thing = new MessageEmbed()
.setColor(ee.embed.color)
.setTimestamp()
.setDescription(`Turned ${player.nightcore} **nightcore**"`);
await bot.delay(5000);
if (player.nightcore) player.speed = 1.2;
return msg.edit({ content: ' ', embeds: [thing] });
} else {
//if not user Premium code down here
let thing = new MessageEmbed()
.setColor(ee.embed.wrongcolor)
.setDescription(`*You need to be a premium to use this command.*`);
return message.channel.send({ embeds: [thing] });
}
} catch (err) {
console.log(err);
message.channel.send({
content: `Something went wrong, try again later.`,
});
}```
Error
```json
TypeError: player.setNightcore is not a function```
Not discord.js related
It's erela.js not discord.js/voice
oh yes.
what does it mean? everything worked fine before
this is not play-dl support
Either you are trying to read an empty file or some different file format that reads like json
is it normal that in my node_modules i have '@discordjs' and discord.js
yes
I'd like to uninstall just the 12.5.1 version
anyone know how to?
uninstall discord.js-light package
oh... i see. the light uses 12.5 huh
I'm using a bot template (for command handling and everything) the guy used discord.js-light... can I replace all of his 'discord.js-light' imports with normal discord?
nah
just update discord.js-light to the latest (4.7.0)
thanks!
wait
so
ytdl-core is kinda broken (as oflast time i checked)
play-dl is now dead
what's next??????
How about respecting YouTube ToS for a change?
🙂
what library would you recommend to use for music
I'm just tinkering with discordjs 13 and I'm just trying to get it to join a voice channel.
I'm using the following to get it to just simply join the channel but it says
voice.channel.joinVoiceChannel() is not a function. Here is the section thats giving me an error
client.on('messageCreate', (message) => {
if(message.content === '.join') {
const { voice } = message.member
if(!voice.channelId) {
message.reply('You must be in a voice channel')
return
}
voice.channel.joinVoiceChannel()
}
})
joinVoiceChannel() is a function that is exported from @discordjs/voice
its not a method from voice.channel
"Audio players can be used to play audio across voice connections. A single audio player can play the same audio over multiple voice connections." but a bot can only be in one voice channel at a time, right?
per guild yes. But a bot can be in many guilds
o that's what it meant. thank you!
everything was imported correctly.
var channel = message.member.voice.channel;
joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
const resource = createAudioResource(message.attachments.first().url);
player.play(resource);```
doesn't do anything. how can i play a .mp3 file attached to a message?
Subscribe the connection to the player
const moment = require("moment")
var temporary = [];
client.on('voiceStateUpdate', async (oldMember, newMember) => {
const guild = client.guilds.cache.get("979260496098238504");
const user = await client.users.fetch(newMember.id)
let voiceCH = client.channels.cache.get("979260496098238508");
let category = voiceCH.parent
let wfschannel = client.channels.cache.get("979341639959072798");
if (newMember.channel == voiceCH) {
await newMember.guilds.channels.create(`『📞』𝐀𝐮𝐭𝐨𝐌𝐨𝐯𝐞`, {
permissionOverwrites: [
{
id: newMember.id,
allow: ["VIEW_CHANNEL"]
},
{
id: newMember.guild.id,
deny: ["VIEW_CHANNEL"]
},
{
id: "979286838365782080",
allow: ["VIEW_CHANNEL"]
}
],
type: 'voice', parent: category, userLimit: 10
}).then(async (channel, error) => {
temporary.push({ newID: channel.id, guild: channel.guild });
await newMember.setChannel(channel.id).catch()
const roleslist = ((newMember.member.roles.cache.filter((roles) => roles.id !== guild.id).sort((a,b) => b.position - a.position))).map((role) => role.toString()).join()
const size = newMember.member.roles.cache.size - 1
anyone know why the bot doesnt create a new private vc
and pull the person that joined the specific channel
.
what library would you recommend to use for music
play-dl (even if it's no longer maintained)
I have music in it already works every other time (the same music)
play-dl
So I'm looking for another one
Hey, does anyone know if it is possible to access audio from voice channel with a bot that uses lavalink?
#rules 3
Sorry, I forgot
Hi how do i fix this error:
`const subscription = connection.subscribe(player);
^
ReferenceError: connection is not defined
at video_player (C:\Users\Administrator\Desktop\Simba\discordbotz\commands\play.js:99:26)
at Object.execute (C:\Users\Administrator\Desktop\Simba\discordbotz\commands\play.js:69:21)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Node.js v17.0.1`
define connection 🙂
joinVoiceChannel returns a VoiceConnection
thanks
I have managed to fix everything but when it joins a vc it doesn't play anything and theres no errors in the logs
How can i play audio?
Suggestion for @subtle granite:
Library: Voice Connections
read more
Hello, I'm trying to play an mp3 file. The bot is joining the channel but not playing anything.
const connection = joinVoiceChannel({
channelId: "782730481904254987",
guildId: "762075402570825748",
adapterCreator: client.guilds.cache.get("762075402570825748")?.voiceAdapterCreator,
});
const player = createAudioPlayer();
const resource = createAudioResource(path.join(__dirname, "../assets/elevator_music.mp3"));
player.play(resource);
const subscription = connection.subscribe(player);
if (subscription) {
setTimeout(() => subscription.unsubscribe(), 5_000);
}
I have discordjs/opus and ffmpeg-static installed
do u have voice state intents?
yes
const player = createAudioPlayer();
const resource = createAudioResource('/home/user/voice/track.mp3');
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
player.play(resource);
connection.subscribe(player);
is there a way to add a .mp3 to queue without using any external library other than @discordjs/voice?
Someone help me please?
exports.disconnect = (interaction) => {
return new Promise(async (resolve, reject) => {
console.log(await (await interaction.guild.members.fetch()).find(user => user.id === interaction.user.id));
const user = await (await interaction.guild.members.fetch()).find(user => user.id === interaction.user.id);
console.log(user.voice.channel);
if (user.voice.channel == null) return resolve("You must be in a voice channel to use this command!");
user.voice.disconnect();
resolve("You have been disconnected!");
});
}
It doesn't refresh the interaction value if i leave or join a vc. No Error it just executes the same thing until i reload the bot.
Hi folks, is there a guide for "receiving audio" in v13 as were in v12? I cant find it on the linked guide
Thank you very much
Make sure you have the guild voice states intent enabled
can i make a bot join a voice channel using the same structure as this one?
`bot.on('message', function (user, userID, channelID, message, evt) {
// Our bot needs to know if it will execute a command
// It will listen for messages that will start with !
if (message.substring(0, 1) == '!') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
// !ping
case 'cf':
bot.sendMessage({
to: channelID,
message: 'sunt viu, dude!'
});
break`
could you be a little more specific about what you're asking?
this just looks like an extremely outdated message command handler
i mean, by following the structure
`case 'cf':
bot.sendMessage({
to: channelID,
message: 'sunt viu, dude!'
});
break`
to make it join in the same voice channel as the member is joined
are you asking whether it's possible to join a voice channel in one of your cases?
yes
then yes, you can do that whenever you want as long as the client is ready
if i can use case to make it join
I was using ytdl-core to download my music and it was working fine, when i switched to the discord-ytdl-core (It returns an FFmpeg stream instead of an normal one) the player don't play anything, even if I pass through the demuxer, is there an special way to make the FFmpeg stream works?
I'm not really sure what a ffmpeg stream is, given that ffmpeg handles many different kinds of streams
but I imagine the issue is you'd need to pass a specific inputType to the createAudioResource options
Well, when I console.log the Ytdl-core stream, the constructor class is an Stream and when I do this with the discord-ytdl the class is called FFmpeg
I already have this
And the player will transit:
Idle
Buffering
Playing
Idle
In less than 5 seconds
Also, the probe always returns arbitrary
that's just the class that extends stream
you'd need to figure out what sort of data is in the stream
The player is now stuck on buffering 
Hey there!
this.client.voice.adapters.set(this.id, methods);
TypeError: Cannot read properties of undefined (reading 'set')
Somebody knows how to fix this issue?
client.channels.fetch("946890839475515486")
.then((channel) => {
joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator
});
});
what version of discord.js are you using
discord.js@13.7.0
and @discordjs/voice version?
@discordjs/voice@0.9.0
pls
lol
export const playAudio = async (interaction)=>{
const voiceChannel = interaction.member.voice.channel;
if(!voiceChannel) return ;
try {
const connection = joinVoiceChannel({
channelId:voiceChannel.id,
guildId: interaction.guild.id,
adapterCreator:interaction.guild.voiceAdapterCreator,
selfDeaf:false,
selfMute:false,
})
interaction.channel.send(`${interaction.client.user.username} has joined the voice channel`)
} catch (error) {
await interaction.channel.send("Unable to join voice channel")
}
}
```for some reason this function does not run the same time all the time. It sometime connects to the voice channel but sometimes doesnt. Any reason why that i'm missing?
Did you check if the return is running?
JoinVoiceChannelOptions
The options that can be given when joining a voice channel.
how to join a voice channel
Suggestion for @lean storm:
Library: Voice Connections
read more
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guild.id,
});
client.on('message', message => { connection = joinVoiceChannel({ channelId: message.member.voice.channel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator, }) })
That doesn’t look like DJS v13
you were right thanks
The Voice Channels Data isn't getting updated when i move the bot from Voice 1 to Voice 2 when i try to eval bots voice channel it returns voice 1 instead of voice 2
can anyone help me with this?
Note: i have already added GUILD_VOICE_STATES Intent
Try <guild>.me.voice.channel
yes tried to eval it and its returning the old voice channel
like it joined vc 1 eval shows vc 1 then i shifted the bot to vc 2 and evaled then it also returns vc 1
TypeError: Cannot read properties of undefined (reading 'once')
at AudioPlayer.play (E:\discord bot\node_modules\@discordjs\voice\dist\index.js:964:25)
at Object.execute (E:\discord bot\commands\say.js:32:20)
at processTicksAndRejections (node:internal/process/task_queues:96:5) unhandledRejection
```
line 32 say.js
what does buffer log as?
<Buffer ff f3 44 c4 00 11 98 e1 b8 01 49 48 00 9c e7 44 01 40 40 90 b8 00 0c 26 17 04 cd a4 83 10 20 41 8b 8a c1 32 74 81 32 75 02 84 89 85 c3 6f 23 27 9d 41 ... 6958 more bytes>
right
whts wrong?
looks like docs says AudioPlayer.play expects a type AudioResource so that's probably a hint towards what is wrong here
its not a audioresource?
Buffer is not a AudioResource no
is there a way to convert?
i'm not sure what to expect but try using createAudioResource from voice
Error: FFmpeg/avconv not found!
at Function.getInfo (E:\discord bot\node_modules\prism-media\src\core\FFmpeg.js:143:11)
at Function.create (E:\discord bot\node_modules\prism-media\src\core\FFmpeg.js:156:38)
at new FFmpeg (E:\discord bot\node_modules\prism-media\src\core\FFmpeg.js:45:27)
at Object.transformer (E:\discord bot\node_modules\@discordjs\voice\dist\index.js:1780:27)
at E:\discord bot\node_modules\@discordjs\voice\dist\index.js:1936:58
at Array.map (<anonymous>)
at createAudioResource (E:\discord bot\node_modules\@discordjs\voice\dist\index.js:1936:39)
at Object.execute (E:\discord bot\commands\say.js:27:28)
at processTicksAndRejections (node:internal/process/task_queues:96:5) unhandledRejection
export const playAudio = async (interaction)=>{
const voiceChannel = interaction.member.voice.channel; // check if user is in voice channel
if(!voiceChannel){
return await interaction.reply({content:"You must be in a voice channel to use this command"})
}
try{
const connection = joinVoiceChannel({
channelId:voiceChannel.id,
guildId: interaction.guild.id,
adapterCreator:interaction.guild.voiceAdapterCreator,
selfDeaf:false,
selfMute:false,
})
let url = interaction.options.getString("query")
let vid = ytdl(url)
const resource = createAudioResource(vid)
const player = createAudioPlayer()
player.play(resource)
connection.subscribe(player)
}catch(e){
await interaction.reply(`Un able to play youtube video`)
}
}
``` for some reason my audio resource is not running, i get no errors in the catch block as well.
any idea why?
ig debug
wdym?
and you should google your error (Thomas Shelby)
npm i ffmpeg-static@latest
TypeError: Cannot read properties of undefined (reading 'once')
at AudioPlayer.play (E:\discord bot\node_modules\@discordjs\voice\dist\index.js:964:25)
at Object.execute (E:\discord bot\commands\say.js:34:20)
at processTicksAndRejections (node:internal/process/task_queues:96:5) unhandledRejection
show your code and do npm ls discord.js / npm ls @discordjs/voice
at new NodeError (node:internal/errors:371:5)
at _write (node:internal/streams/writable:312:13)
at Socket.Writable.write (node:internal/streams/writable:334:10)
at pump (node:internal/streams/pipeline:150:21)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
resource: AudioResource {
playStream: OggDemuxer {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 6,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_remainder: null,
_head: null,
_bitstream: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
edges: [ [Object], [Object] ],
metadata: null,
volume: undefined,
encoder: undefined,
audioPlayer: AudioPlayer {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_state: [Object],
subscribers: [],
behaviors: [Object],
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
},
playbackDuration: 0,
started: false,
silencePaddingFrames: 5,
silenceRemaining: -1
}
} uncaughtException
const { MessageEmbed } = require('discord.js');
const {joinVoiceChannel} = require("@discordjs/voice");
const tts = require('google-translate-tts');
const { createAudioPlayer, NoSubscriberBehavior , createAudioResource } = require('@discordjs/voice');
module.exports ={
name: `say`,
permissions: [],
cooldowns: 0,
description: `bj`,
async execute(client, message, args, Discord, profileData , LevelData) {
args = args.join(" ");
let voiceChannel = message.member.voice.channel;
if(!args)message.reply("Tell me something to say")
else if(!voiceChannel) message.reply("Please Join a voice channel")
else if(voiceChannel){
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const buffer = await tts.synthesize({
text: 'Hello, world!',
voice: 'en',
slow: false // optional
});
let resource = createAudioResource(buffer);
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
console.log(buffer);
player.play(resource);
}
},
};
discord.js@13.6.0 deduped @discordjs/voice@0.9.0
const { Readable } = require("node:stream");
const bufferToStream = (binary) => {
const readableStream = new Readable({
read() {
this.push(binary);
this.push(null);
}
});
return readableStream;
};
...
const resource = createAudioResource(bufferToStream(buffer));
not sure if there is a more elegant way but this is what i came up with
at Socket.<anonymous> (E:\discord bot\node_modules@discordjs\voice\dist\index.js:353:46)
at Object.onceWrapper (node:events:509:28)
at Socket.emit (node:events:402:35)
at socketCloseNT (node:dgram:763:8)
at processTicksAndRejections (node:internal/process/task_queues:82:21) ```
before this it joined channel but did not play nothing
don't think that's voice causing it, something something network settings + i cant replicate
its pointing to voice in 3 rd line
yes, voice is throwing the error, but the error is thrown probably because of your network settings
i don't understand the package but the socket is closing because it can't perform IP discovery, like the error says https://github.com/discordjs/discord.js/blob/main/packages/voice/src/networking/VoiceUDPSocket.ts#L202
it only does when the bot joins it logs error
because that's when it begins to create the socket
and if i use the command agn it doesnt do anything
doesnt log anything
because it crashes
the bot is in vc and i use error handling
okay well the error is because it can't perform ip discovery
only thing i can say is its probably a firewall setting to discord
i was messing with code i removed await before player.play(resource)
now it has no error but doesnt play anything
i doubt that changes anything
there is no error now
what is your code now
const { MessageEmbed } = require('discord.js');
const {joinVoiceChannel} = require("@discordjs/voice");
const tts = require('google-translate-tts');
const { createAudioPlayer, NoSubscriberBehavior , createAudioResource } = require('@discordjs/voice');
module.exports ={
name: `say`,
permissions: [],
cooldowns: 0,
description: `bj`,
async execute(client, message, args, Discord, profileData , LevelData) {
args = args.join(" ");
let voiceChannel = message.member.voice.channel;
if(!args)message.reply("Tell me something to say")
else if(!voiceChannel) message.reply("Please Join a voice channel")
else if(voiceChannel){
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const buffer = await tts.synthesize({
text: 'Hello, world!',
voice: 'en',
slow: false // optional
});
const { Readable } = require("node:stream");
const bufferToStream = (binary) => {
const readableStream = new Readable({
read() {
this.push(binary);
this.push(null);
}
});
return readableStream;
};
const resource = createAudioResource(bufferToStream(buffer));
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
player.play(resource)
}
},
};```
you never subscribed the connection to the player
wht does subscribe mean here
connection.subscribe(player)
wht does it do
for simplicity i'd say it just makes the connection follow the audio player, multiple connections can follow an audio player but multiple audio players cant be fed into one connection, when the audio player actually plays, the connection will "stream" that
ok . is there any way to know that the audio playing is complete or should we just code it on our own
how to disconnect bot from channel
i tried voiceChannel.disconnet() and voiceChannel.leave() i doesnt work
connection.destroy()
y does it send msg 2 times
because it started playing audio twice?
no its playing only once
y does it do like tht?
Because you attached the same listener twice probably
Hello someone have a join voice channel code v13?
Bro i can’t understand this can u write the code for me?
#rules 5️⃣
I have been making a music bot for my discord server and the bot joins the vc but It doesn't play anything and it doesn't log an error
Do you have the voice states intent?
Is it the guild_voice_states if its that yes
show code
I'm not at home rn.. I can show you later on
Or I think I can find it hold on
Yeah I cant read that
I'll send a better version when I get home
Hi, I'm trying to implement a /seek command. It does work - the audioresource does in fact skip forward to w/e specified time, but when I log the playbackDuration, it starts from 0 rather than the seek forwarded time.
In this screenshot, the expected result was supposed to be like 200000 for 200s
Anyone know how to fix?
Add the amount you skipped
Lol, I was thinking of doing that, but I assumed I was just doing something wrong for the timestamp being wrong, lol.
Is playbackDuration working as intended? Or could there be a possibility that the method itself is broken?
That’s how it works
It’s the amount of time it actually played/consumed
It doesn’t consider the skipped time, pretty sure it doesn’t even know
I see. Fair enough. I guess I'll do the add amount skipped bit, ty. 
Witht this code, if exists vc if forst interaction timeout is over but during this i use 2nd command but its timeout isnt considered what can i do?
setTimeout(() => {
const connection = getVoiceConnection(interaction.guildId);
connection.destroy();
}, 1* 60 * 1000)
can you rephrase that first part of your message ? I dont understand
Like after a command was used it starts the timeout of one minute so in during that one minute i use a command which should delete the first timeout and create new but it doesnt do anything and follows first created timeout
Did you understood now?
so basically you use this command and then another command which interrupts the timeout?
The second one interrupt first.
I would better-lly show you in a server if you mind?
no, but you should handle the case that the connection is already destroyed or store the response from setTimeout (an id to clear) so that you can clear it when you want, like when you begin the second command
Like how with kv's?
Store the timer returned from setTimeout somewhere and cancel it on command interaction receival, before you start a new timeout
I have never worked with storing things can you help me?
Easiest way is to attach it to the client, like client.vcTimeout = setTimeout(…) and then use that to clearTimeout(client.vcTimeout). If your bot is in more than one VC at a time you’d need to make it a collection instead and get the appropriate timeout ID from it
But then how would ik a similar intwraction tooked place to delete that set timeout id and yeah it will be in more than one vc so i have to use database?
By doing the clearTimeout in the same interaction handler that calls the setTimeout, but earlier in the code
You mean doing
clearTimeout(client.vcTimeout);
to do that which should be placed on top of the setTimeout code?
Yes
And if bot is multiserver then it should matter?
Like ofc bot would be in more than 1 vcs but when i do interaction.guildId i would only clear the timeout for that particular guild right?
No, as clearTimeout gets a timer ID, not a guildId. So you should instead have a client.vcTimeouts = new Collection(); and set/get the timerId by guildId in there
What does that new Collection(); means like a new database ig mongo?
Documentation suggestion for @shrewd compass:
Collection
A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has an ID, for significantly improved performance and ease-of-use.
The relevant code
const player = createAudioPlayer();```
__**The error:**__
```ReferenceError: createAudioPlayer is not defined
at Client.<anonymous> (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\src\index.js:248:20)
at Object.onceWrapper (node:events:642:26)
at Client.emit (node:events:527:28)
at WebSocketManager.triggerClientReady (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:17)
at WebSocketManager.checkShardsReady (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketManager.js:367:10)
at WebSocketShard.<anonymous> (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketManager.js:189:14)
at WebSocketShard.emit (node:events:527:28)
at WebSocketShard.checkReady (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
at WebSocketShard.onPacket (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketShard.js:447:16)
at WebSocketShard.onMessage (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
[nodemon] app crashed - waiting for file changes before starting...```
Anyone know why this error occurs?
createAudioPlayer doesnt exist on @discordjs/voice
Where does it exist than?
When hovering on the code, it shows:
Yeah it exists, anyone knows why this happens?
show src\index.js:248:20
I use createAudioPlayer in onReady. And require it at the beginning of the code.
i think i shouldn't mess with this channel and #djs-in-dev-version
248 is: const player = createAudioPlayer();
Any idea?
nope, sorry
It works on my server.
Do you have the voice npm installed?
It functions now, took old code and just copy pasted the new code into it. It somehow works ¯_(ツ)_/¯
i did what you told till clearTimeout(client.vcTimeout); but idk what did you mean by client.vcTimeouts = new Collection(); so if i just add this line it is done or i have to add something else?
You have to understand a bit about Collections to do that I think…
Suggestion for @shrewd compass:
Additional Information: Collections
read more
okay like from collection i have to fetch guild id and clear timeout for that guild id?
Yes, exactly like that. And insert the value for the guild when calling setTimeout
ohk
i may sound dumb like i have guildid in collection now what should i do next? sry to ping you :(

is there a way to "receive" audio with discordjs/voice?
Do you have the timerId set as value for the guildId in the collection?
no, is there ids for timeout i dint know? so now this is code should i put guildID with client.vcTimeout.id ?
The code
setTimeout() returns the timerId. Store that in the collection
So .set(interaction.guildId, setTimeout(…)) and clearTimeout(…get(interaction.guildId)
client.vcTimeouts.set('timeoutID', client.vcTimeouts.id);?
No, don’t use hardcoded strings as key, else they will all overwrite the same entry. Use the guildId as key, the timerId as value
okay so now the name of set should be id and value should be timeid right?
okay i came up with this now
i replaced the guildID with interaction.guildId
You still have the hardcoded string 'guildId' instead of the actual ID as key… also you don’t need to assign the setTimeout to another var, because you already put it into the collection now
key should be ${interaction.guildID} and the value should be the var of timeout thing or a new timeout code?
The var from timeout or directly put the setTimeout in the set. Matter if coding style and taste. Both would work.
clearTimeout(client.vcTimeout);
vcTimeout = setTimeout(() => {
const connection = getVoiceConnection(interaction.guildId);
connection.destroy();
}, 1 * 60 * 1000)
});
client.vcTimeouts = new Collection();
client.vcTimeouts.set(interaction.guildId, client.vcTimeout = setTimeout(() => {
const connection = getVoiceConnection(interaction.guildId);
connection.destroy();
}, 1 * 60 * 1000) );
console.log(client.vcTimeouts.get('interaction.guildId'));
see i have this anything to add or anything to remove?
ig i have to remove vcTimeout part from this?
You need to define that collection only once, not on every run of your event. Else it gets cleared every time and becomes useless. And yes, you need to replace the vcTimeout part on top with the get(interaction.guildId) from said collection.
collection is defined only ones ig? and you mean replace vcTimeout part or clearTimeout(client.vcTimeout); ?
clearTimeout(client.vcTimeouts.get('guildID'));
client.vcTimeouts = new Collection();
client.vcTimeouts.set(`${interaction.guildId}`, client.vcTimeout = setTimeout(() => {
const connection = getVoiceConnection(interaction.guildId);
connection.destroy();
}, 1 * 60 * 1000) );
console.log(client.vcTimeouts.get('guildID'));
Is This Perfect?
when i was testing in a diffrent server it was trowing error connection.destroy(); is undefined well it worked for 1 st server properly
New Code
clearTimeout(client.vcTimeouts);
let vcTimeout = setTimeout(() => {
const connection = getVoiceConnection(interaction.guildId);
connection.destroy();
}, 1 * 60 * 1000)
client.vcTimeouts = new Collection();
client.vcTimeouts.set(`${interaction.guildId}`, vcTimeout = setTimeout(() => {
const connection = getVoiceConnection(interaction.guildId);
connection.destroy();
}, 1 * 60 * 1000) );
Not quite. The declaration of the collection happens on every call of that handler instead of only once. Move that line to your ready event instead. And for the getter use the actual guildId, not the string 'guildId'
yeah did 2nd thing see updated code and the first thing i dint understood wdym?
should i remove the part selected?
No. The line above that. Cut&paste it into your ready event
client.on('ready', async () => {
console.log(`Ready!`);
client.vcTimeouts = new Collection();
client.user.setPresence({ activities: [{ name: 'somethin' , type: 'WATCHING' }], status: 'idle' });
});
Like This?
Yes. And for the clearTimeout use the id you get from the collection for that guildId, not the whole collection
i have guild id as key and timeout as value so i have to use clearTimeout(interaction.guildId); ?
no. clearTimeout gets the timeoutId, so you need to get that from the collection by using the guildId as key
ohk i get that so clearTimeout(client.vcTimeouts.get(${interaction.guildId}));
client.vcTimeouts.set(`${interaction.guildId}`, vcTimeout = setTimeout(() => {
const connection = getVoiceConnection(interaction.guildId);
connection.destroy(); //this is line 92
}, 1 * 60 * 1000) );
that throws this error @waxen wedge
Well, check if it exists before destroying it. Should be done either way in case someone kicks the bot from the VC before timeout occurs… add some console.log statements to find out what connection gets created/destroyed when to determine where it goes wrong
What should i log in console like both vars?
I got the problem it is here there are two connection destroy so it throws error how can i solve it?
just check if the connection has already been destroyed before destroying it
Nah its not like that ig its like after one minute first connection.destroy(); disconnectes it but the other connection.destroy(); makes error to come
if (connection) connection.destroy()
Where 👀
Remove the first setTimeout. You only need the second
Ok lemme try
where you're actually destroying it 👀
Its on two places 👀
After removing it throws this error

bump
You don’t need to assign anything, remove the vcTimeout =
Yes, see recorder example
Direct setTimeout?
Can you give me the link please?
Yes
Okay it works but i am on mobile couldn't verify for multiserver thing i will let yk tmrw thanks for spending time and letting me know interesting things :)
See pinned message
Ok, thank you
hi, i have an issue with the installation of discordjs/opus, should i ask it here?
https://dontasktoask.com, and you can ask here
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
module.exports = {
name:"play",
description: "Connects and Plays music",
data: new SlashCommandBuilder().setName('play').setDescription('Connects and plays audio')
.addStringOption(option=>option
.setName('query')
.setDescription('string that is the youtube url')
.setRequired(true)),
async execute(interaction){
const voiceChannel = interaction.member.voice.channel;
if(!voiceChannel){
await interaction.reply("You must be in a voice channel to use this command") // triggered if interaction is used when user is not in a voice channel
return;
}
try{
const connection = joinVoiceChannel({
guildId: interaction.guild.id,
channelId: voiceChannel.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator,
selfDeaf:false,
selfMute:false,
})
const youtubeVid = ytdl( interaction.options.getString('query'),{filter: 'audioonly'}) // returns internal.readable
const resource = createAudioResource(youtubeVid);
player.play(resource)
connection.subscribe(player)
}catch(err){
interaction.reply(`There was an-error during the connection and playing of music ${err}`)
}
},
}
``` for some reason my bot will not play music i run this.
it connect to the voice channel but nothing is played
the slash command takes in a youtube url as an argument
Uncaught Exception Thrown
AudioPlayerError: aborted
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:402:19)
at TLSSocket.emit (node:events:538:35)
at node:net:687:12
at TCP.done (node:_tls_wrap:580:7) {
resource: AudioResource {
playStream: OggDemuxer {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_remainder: null,
_head: null,
_bitstream: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: [Function: bound onwrite]
},
edges: [ [Object], [Object] ],
metadata: null,
volume: undefined,
encoder: undefined,
audioPlayer: AudioPlayer {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
_state: [Object],
subscribers: [Array],
behaviors: [Object],
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
},
playbackDuration: 25740,
started: true,
silencePaddingFrames: 5,
silenceRemaining: -1
}
}
Anyone know why this happens?
does anyone know how to install opus on linux
? can't you just use @ discordjs/opus
no it creates an error
which is?
Why this thing isn't working
const subscription = connection.subscribe(player);
if (subscription) return interaction.reply({
ephemeral:true,
content: 'Lol No!'
});
how do i create a listen stream for a voice channel and/or person in vc?
by not working do you mean the interaction reply isnt sent?
How could I merge two opus streams into one or play 2 opus streams simultaneously in one vc?
Nah no it checks that if there is a subscription already if not it send that lol no msg but now it always sends it regardless it is not going on
Or regardless case1 or case2 it semds only case1 msg
(and ping me pls lol)
what is the default encoding for a receiver audio stream? im trying to know the encoding format etc since im trying to use google's speech to text api. Do i need to use prism media to encode it/re encode it?
Opus Audio in object mode to be more precise
I am making a tts bot the problem is whenever a command is used regardless the previous tts comamnd is over it starts the new one.
For eg-
/smr: something big sentence (First tts command is going on but i use second command)
/smr some thing new big sentence
(it stops the first tts and plays second) how do i prevent this thing? Someone knows? Like i dont wanna make queue i want like if bot is speaking something in vc then just send emprehal msg that a tts is going on pls wait how can i do that?
I used voice channel state it don't seem to work and also I tried this but it always shows the emprehal msg tho if it is case2 or case 1
Code-
const subscription = connection.subscribe(player);
if (subscription) return interaction.reply({
ephemeral:true,
content: 'Lol No!'
});
Using discord.js latest version
And by using promise resolve it doesn't get that the content was Sayed out in VC or not it only checks till bot joined VC and started speaking
Check for the player‘s state (if not Idle send that ephemeral)
Did that but shows invalid body form
if (!player.on(AudioPlayerStatus.Idle) return interaction.reply({
ephemeral:true,
content: ''somethin
});
```
Am i doing something wrong here?
yes, you‘re doing lots wrong here… player.on would be an event handler… not something to check the current state. Use player.state and compare that to the Idle state
if (!AudioPlayerStatus.Idle) return interaction.reply({
ephemeral:true,
content: 'somethin'
});
Like this?
No. I see no player.state in there and no comparison. Did you even read what I wrote?
if (!player.state === Idle) return interaction.reply({
ephemeral:true,
content: ''somethin
});
```
Like this? I think you meaned this?
Almost… use !== to compare for not equal. The ! in your code would negate the player.state (so that would be false) and false is never equal to Idle. Also where did the AudioPlayerStatus. in front of the Idle go?
Okay I will add that things :)
if (player.state !=== AudioPlayerStatus.Idle) return interaction.reply({
ephemeral:true,
content: 'somethin'
});
This is perfect?
Scratch the first !
Okay after that it should be done right?
I‘m not a clairvoyant, I know three lines of your code. Impossible to know if it will work or not. That’s for you to test and work out
Should there only be 2 equal to signs?
#rules 2
I am not sure it is related with discord.js, but after playing music for some minutes this error pop up:
Error: aborted
at connResetException (node:internal/errors:692:14)
at TLSSocket.socketCloseListener (node:_http_client:414:19)
at TLSSocket.emit (node:events:539:35)
at node:net:715:12
at TCP.done (node:_tls_wrap:582:7)
[ERROR] 18:45:08 Error: aborted
This only happens when the bot is playing music.
Where is the bot playing music from? I would bet it‘s the connection to the source, not discord
use play-dl instead of ytdl-core
oky, i was just writing that my resources is from ytdl-core, XD
thank you
It doesn't work tho I tried many things should I send you the code like on using command it creates a new adapter everytime
How would I merge two opus streams
I need to play 2 or more opus streams together in a vc
Ofc it doesn't work.. read their message
Error: Cannot find module '/home/container/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm64-glibc-2.31/opus.node'
Help me
npm ls @discordjs/opus
solved
so, running into an odd issue, not sure if it's actually a bug in voice or not
if I play an audio stream over a connection, i'm no longer able to play any resource created with a file path, only able to play streams after that (even creating a new audio player and new audio resource)
Use absolute paths, audioresources tend to not work with relative paths if you don’t make sure that it’s relative to the actual working directory
it is absolute, i actually did find others having this issue: https://github.com/discordjs/discord.js/issues/7232 and yeah my workaround has just been creating read streams to the file
How can I make my bot search a youtube video only via the title of the video pls ?
you can't do that with djs
find a different module to do that for you
i have ytdl-core and other module to
i just dont know how to do it but i know it's possible
but what module can do that for me ? pls
here's the section of ytdl-core's readme that tells you 🙂
https://www.npmjs.com/package/ytdl-core#related-projects
thx bro
in future, please don't use the djs help channels for finding what package to use 🙂
okay i m sry
Reinstall the voice package
what's meant by "clean them up"?
deleting/erasing every instance of the connection you have stored in ur code
const music = path.join(__dirname, 'Warteschleifeend.mp3' )
const resource = createAudioResource(music, { inlineVolume: true })
resource.volume.setVolume(0.5);
player.play(resource)
const channel = client.channels.cache.get(queue);
const connection = joinVoiceChannel({
channelId: queue,
guildId: serverid,
adapterCreator: channel.guild.voiceAdapterCreator,
})
const subscription = connection.subscribe(player)
player.on(AudioPlayerStatus.Playing, () => {
console.log("The music is now playing.")
} )
player.on('error', error => {
console.error(`Error: ${error.message}`)
})
player.on('idle', idle => {
console.log(`Starte neu`)
client.user.setActivity("im Support");
const resource = createAudioResource(music, { inlineVolume: true })
resource.volume.setVolume(0.35);
player.play(resource)
}) ```
This is the code of my bot that normally plays 24/7 music, it worked before, but I programmed some new stuff and now it doesnt function anymore:
It still gives out: "The music is now playing.", but it doesnt.
But beforehand it gave it out twice, now it gives it out only once
What is odd is that both input and output are deactivated. How do i activate them?
selfMute: false and selfDeaf: false
Ok unmuted, but still not playing
You know why it doesnt suddenly work?
Since I have no idea what you changed I‘m in no position to know that
@zealous blade could it be that? Since you seem to reset the local file in the idle event
I restarted my bot a lot today, and really quickly. Is there a way to clear the player and everything?
ReferenceError: createReadstream is not defined, even though I require it. @waxen wedge
Restarting the bot (as in ending node and starting it again) should clear everything. Or what do you mean?
Yeah the fix at github doesnt function for me, it worked earlier
i dont know what that means
i havent done much with audio
I‘m sure you have internet and a search engine of your liking…
const { createAudioPlayer } = require('@discordjs/voice');
let player = createAudioPlayer({
behaviors: {
maxMissedFrames: 5 // by default
}
})```
if i change `maxMissedFrames` to say 20, does this make the bot hang longer at the end of a song? what does it do?
HELP ME
Someone?
Tag suggestion for @crude stream:
To help you we need more information:
• What are you trying to do?
• What is your code?
• What errors and debug logs do you have?
did you double check serverId and queue are actually what you expect them to be?
The bot joins the channel, but doesnt play anything. Also the bot was working beforehand.
And I also use them gor other code, so yes they are correct
Is queue inside the serverId guild? I‘m a little confused on the different ways you address the guild in your code. Since usually the guildId and the voiceAdapterCreator would be got from the same guild object
Yeah as said, it joins the right channel. Queue is my Support Queue on ny server
I understand that the channel is correct. But since it doesn’t play audio the voiceAdapterCreator could be wrong
I see, I just changed it to this, but it didnt help:
const guild = client.guilds.cache.get(serverid) adapterCreator: guild.voiceAdapterCreator,
Here is the console.log of resource (logged it in player.on.ready):
Anything to note?
resource: [Circular *1],
Is it normal that resource is this, when logging my resource?
It refers to the initial reference because it's resource -> player -> state -> resource
channelId: interaction.member.voice.channel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
});
const resource = createAudioResource("test.mp3");
connection.subscribe(player);
player.play(resource);
await interaction.reply('Playing.');```My bot joins the channel but I just can't get it to play audio
have you defined "player"?
const player = createAudioPlayer();
hmm
But I know that its using my test.mp3 while running, because I can't tamper with it between.
do you have all the dependencies listed in the guide?
const { createAudioPlayer, joinVoiceChannel, getVoiceConnection, createAudioResource, StreamType } = require('@discordjs/voice');
no i meant your package.json
"@discordjs/voice": "^0.10.0","discord.js": "^13.7.0",
install libsodium-wrappers and try it then
I tryed npm i libsodium-wrappers rerun and it didn't work
oh fuck i forgot you also need ffmpeg to play mp3 files
npm i ffmpeg-static ffmpeg
my package.json "dependencies": { "@discordjs/opus": "github:discordjs/opus", "@discordjs/rest": "^0.5.0", "@discordjs/voice": "^0.10.0", "discord-api-types": "^0.33.3", "discord-buttons": "^4.0.0-deprecated", "discord-voice": "^2.0.6", "discord.js": "^13.7.0", "ffmpeg": "^0.0.4", "ffmpeg-static": "^4.4.1", "fs": "^0.0.1-security", "libsodium-wrappers": "^0.7.10", "stream": "^0.0.2", "ytdl-core": "^4.11.0", "ytdl-core-discord": "^1.3.1" }
still doesnt work?
when running your command: up to date, audited 129 packages in 2s so no difference.
hmm im comparing my music bot to yours right now, and as far as i can see you have the same dependencies and also your code is the same, so i have no idea why it doesnt work
My bot joins my channel and its quiet, it doesn't even show the ring around (indication that its playing), but it's using the .mp3 file. And I know that its not the server permission because I had it working with v12 but v13 doesn't work.
any idea?
Subscribe after beginning playing?
Like this player.play(resource); connection.subscribe(player); Doesn't work
How do you know it's using the mp3 file for sure
Because I tried to rename the file while running and it did not let me
ytdl-core doesn’t work anymore, not that it has anything to do with your current issue