#archive-voice
30636 messages · Page 27 of 31
you need to enable your intents
pass intents array to main client object
I enabled it but I still get the same error
show your client options
client options
How do I get the docs for the joinVoiceChannel method?
Tag suggestion for @hasty bough:
Frequently Asked Questions: learn more
Hey everyone! Need a lil help help here.
So, I want to make a bot that when he startup he direct connect to a channel, without command or anything. So, I wrote this :
console.log("Pret")
joinVoiceChannel({
channelId: Channel,
guildId: Guild,
})});```
Channel and Guild are defined in a const.
But, When I start the bot, it crash with this (see image)...This error code is not really useful. Yeah, "o" is not a function. And what.
Thanks for your answer, if you answer.
what is it
at Socket.<anonymous> (/home/container/node_modules/@discordjs/voice/dist/index.js:1:6361)
at Object.onceWrapper (node:events:639:28)
at Socket.emit (node:events:532:35)
at socketCloseNT (node:dgram:763:8)
at processTicksAndRejections (node:internal/process/task_queues:82:21)```
what can i do?
That has nothing to do with it, I've had it for weeks
channelId: should be the ID of a channel, not the channel itself, same thing for guild. You will also need the adapterCreator: property in that joinVoiceChannel() function which should just equal your guild object's voiceAdapterCreator.
Okay, thanks, I will try that. Thanks you !
can someone help me with my music command
my bot joins the voice channel and sends which video is playing it just doesnt play anything
const ytdl = require('ytdl-core');
const ytsearch = require('yt-search')
const Discord = require('discord.js')
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]})
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
NoSubscriberBehavior
} = require('@discordjs/voice');
module.exports = {
name: "play",
description: "play test",
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('Please connect to a voice channel!');
if (!args.length) return message.channel.send('Please Provide Something To Play!')
const connection = await joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const videoFinder = async (query) => {
const videoResult = await ytsearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if (video) {
const stream = ytdl(video.url, { filter: 'audioonly' });
const player = createAudioPlayer();
const resource = createAudioResource(stream)
await player.play(resource);
connection.subscribe(player);
await message.reply(`Now Playing ***${video.title}***`)
} else {
message.channel.send('No video results found');
}
}
}```
here is my code
also no errors when using the command
my bot is inside a voice channel and still the
const connection = getVoiceConnection(message.guildId!)!;
``` returns `undefined`
why so?
you also need voice states intents
what are they called
GUILD_VOICE_STATES, just read the docs uh
thanks
still doesn't work ;-;
the getVoiceConnection isn't working for me
By the way.
Can someone explain me WHAT is the argument adapterCreator ?
I searched, I browsed the wiki and nobody explains what is it...I'm okay for using it, but if I don't understand what is his purpose, it's not very useful...
It's a DiscordGatewayAdapterCreator, as far as I can tell it just handles the states of your connection in the background. No need to worry about it, just let it do its thing :).
So I just type adapterCreator:voiceAdapterCreator ?
No, you should provide it the voiceAdapterCreator of your guild. So: adapterCreator: guild.voiceAdapterCreator.
Ohhhhhhhhhhhhhhhhh
Like
adapterCreator: 565599771872722944.voiceAdapterCreator ?
You'll need to get the voiceAdapterCreator from your guild object. If that is your guild ID you can get your guild like so const guild = client.guilds.fetch("565599771872722944") if I'm not mistaken.
Hmm
I admit I am a little confused (in addition that I'm french so it's not easy...) I will try what you wrote later, my server is down
Anyways, thanks for the help dude.
can i use stream with ffmpeg already i played it?
i tried this and my audio player event stucked at buffering
No. Streams do not save data they emit, so if the stream has already started or ended, you cannot reuse it
Hey, can anyone help me figure out what's wrong with my code.
So i am making a bot that can record voice channels. Though the bot is working fine, Just that when each individual recording mixed with other people's recording things dont sync up.
i suspect that there is some issue with start and end events.
Here's my recording logic btw
How do I get user voice data(speaking, stop speaking, voice data/recording)? (just need the stream, not a file or anything)
subscribe to the userId of the user you want data of
It crashes with the same error code...
client.guilds.fetch() returns a promise
Hmm...
I...don't know what is it, sorry..
const guild = await client.guilds.fetch("565599771872722944")
SyntaxError: await is only valid in async functions and the top level bodies of modules
I think I need more experience with JS. If I don't even know why I'm using this function I'm not advancing.
async function
An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
Yeah, I figured out how to start it.
The bot started
He didn't crashed
But he didn't joined the channel
what does your code look like now
Client.on("ready", async () => {
console.log("Pret")
const guild = await Client.guilds.fetch("565599771872722944");
joinVoiceChannel({
channelId: 950804559146672168,
guildId: 565599771872722944,
adapterCreator: guild.voiceAdapterCreator,
})});
Maybe he join the channel and directly left it
ids are strings (in joinVoiceChannel())
you have to wrap them in " like you did in client.guilds.fetch()
Oh thanks god it works. Thank you so much. Sometimes coding is really just about how much important are symbols...
If it was the last problem...
Now my code is that.
Client.on("ready", async () => {
console.log("Pret")
const guild = await Client.guilds.fetch("565599771872722944");
joinVoiceChannel({
channelId: "950804559146672168",
guildId: "565599771872722944",
adapterCreator: guild.voiceAdapterCreator,
})
const { getVoiceConnection } = require('@discordjs/voice');
const connection = getVoiceConnection('950804559146672168');
const { createAudioPlayer } = require('@discordjs/voice');
const player = createAudioPlayer();
const subscription = connection.subscribe('player');
const { VoiceConnectionStatus } = require('@discordjs/voice');
connection.on(VoiceConnectionStatus.Ready, () => {
console.log('The connection has entered the Ready state - ready to play audio!');
const resource = createAudioResource('opbajvpc.mp3');
player.play(resource);
})});```
And I get this when I start it.
Yeah, I understand. "Subscription" has to be defined. But with what ?
It's actually connection that has to be defined. JS is weird like that, but here it's trying to read subscribe as a property of connection which it's then saying is undefined. The actual connection object is a return value of the joinVoiceChannel() function so you can just store that in a variable instead of using getVoiceConnection() that should work just fine.
On a separate note, you should refer to the player object instead of 'player' as a String in the parameter of the .subscribe() method. I would really recommend following an online course or something on Javascript before undergoing a project like this because errors like these will be common and are easily avoidable.
Thanks you!
What are the ways to make the quality of the audio better. Without the connection issues
which audio format would be played directly into discord voice channel without any converting?
Guys ls help i am trying to make a bot that plays an mp3 file when it joins the voice channel. It does join but then doesnt play the mp3 file
client.on('message', message => {
if (isReady && message.content === 'a')
{
isReady = false;
var voiceChannel = message.member.voice.channel;
voiceChannel.join().then(connection =>
{
const dispatcher = connection.playFile('./song.mp3');
dispatcher.on("end", end => {
voiceChannel.leave();
});
}).catch(err => console.log(err));
isReady = true;
}
});
error:
(node:1686) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined
Atm streams but later on YouTube and Spotify
hey @rugged sky sry to bother could you hel?
This code is v12, that version is no longer supported and will not work. You have to update to v13/14.
ok thx
Opus
If you're on mobile, there's nothing that can be done since the clients compress the audio a ton for whatever stupid reason. Otherwise, the voice channel bitrate needs to be the desired amount and you should be fetching audio which matches that bitrate or is higher and it'll be compressed down to the max bitrate of the channel. If you can't get any higher quality audio, then you're SOL
In terms of the bots code
There is no code that's universal that just magically makes your audio sound better. It's a concept you have to apply yourself
ooh ok
But does making volume inclind and increasing the bitrate to max have an effect on the quality?
No
it could even make it worse
ooh I see
Thank you I will see what I can do - Thanks alot
But do you know a way to make the bot reconnect and play if the bot goes offline
Gotta store your stuff in some form of persistent storage, rejoin voice channels, create connections and stuff through djs voice, seek to last known position + some compensation since it takes time to do all that in resource and that's it
hmm oks - Thanks
What is the equivalent of connection.receiver.createStream function, but in @discordjs/voice?
hi
is playing songs on one player better
or making new player and destroying old player whenever song changes is better
Just keep the same player.
const ytsearch = require('yt-search');
const Discord = require('discord.js')
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
NoSubscriberBehavior
} = require('@discordjs/voice');
module.exports = {
name: "play",
description: "test command",
async run(client, message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('Please connect to a voice channel!');
if (!args.length) return message.channel.send('Please Provide Something To Play!')
const connection = await joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const videoFinder = async (query) => {
const videoResult = await ytsearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if (video) {
const stream = ytdl(video.url, { filter: 'audioonly' });
const player = createAudioPlayer();
const resource = createAudioResource(stream)
await player.play(resource);
connection.subscribe(player);
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
} else {
message.channel.send('No video results found');
}
}
}
why does this code not work (the bot joins the channel and sendss which video but doesnt play it)
ok thanks
TypeError: o is not a function
at new G (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\@discordjs\voice\dist\index.js:8:7254)
at Oe (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\@discordjs\voice\dist\index.js:8:12358)
at Object.gt (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\@discordjs\voice\dist\index.js:8:12577)
at Client.<anonymous> (C:\Users\Administrator\Desktop\uwu\musicfly\index.js:41:37)
at Client.emit (node:events:390:28)
at WebSocketManager.triggerClientReady (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:17)
at WebSocketManager.checkShardsReady (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\discord.js\src\client\websocket\WebSocketManager.js:367:10)
at WebSocketShard.<anonymous> (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\discord.js\src\client\websocket\WebSocketManager.js:189:14)
at WebSocketShard.emit (node:events:390:28)
at WebSocketShard.checkReady (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
client.on("ready",async () => {
console.log("ready")
const connection =Discordvoice.joinVoiceChannel({
channelId: "932427071911780372", guildId: "870706429995130882",
adapterCreator:client.guilds.cache.get("870706429995130882")?.voiceAdapterCreator as Discord.InternalDiscordGatewayAdapterCreator
})
show us index.js line 41
the guild probably wasnt found in the cache. try removing the optional chaining on the client.guilds.cache.get(). it doesn't really matter if you use it or not since it wont work either way, and it will make the error more readable
THANKS
what format does AudioPlayer.play()'s resource use? I'm trying to use TTS and I'm confused by what I should be converting it to
If you're using v12 or below voice, it's deprecated and shouldn't be used. If you're using @discordjs/voice, then It accepts an AudioResource and an options Object. Read the docs for more info regarding what props are required for the options. You can pipe any audio stream into the AudioResource and if required, it'll pipe it through ffmpeg to be opus encoded, which is what Discord only accepts.
i know how to know if the bot is in a vc or not, but how do i know if the bot is alone in the vc or not
Documentation suggestion for @grizzled jacinth:
VoiceChannel#members
The members in this voice-based channel
For voice recording to be perfect, I have to use worker threads for each user but now I have two options on how to implement that
- Each worker thread creates his own bot instance and listens to one specific user
- Each worker thread just receives the user stream buffer from the main thread
Each worker thread relies on timestamps and the time when a user chunk is received should be as correct as possible
I can't just provide the VoiceReceiver of the connection to the worker thread because it is copied and then it isn't a reference anymore (even though, the copy process fails so nvm that)
What would you suggest?
To do what you want to do, you don't need a bot instance per worker_thread. Theoretically, all you need is the VOICE_STATE_UPDATE session_id and the VOICE_SERVER_UPDATE endpoint and token
I have an example for how that can work here: https://github.com/AmandaDiscord/Volcano/blob/main/src/worker.ts#L450
https://github.com/AmandaDiscord/Volcano/blob/main/src/worker.ts#L462
As an aside, worker_threads do not share the same require.cache, so memory usage will spike pretty harshly per worker_thread you spawn. If you don't import many modules in a thread, you can get away with it, but definitely a concern
@rose helm thx. So basically: don't use the discord.js library, use the endpoints directly to reduce all the overhead
There is no need to use anything Discord REST related in the worker threads. You can just work with djs voice and that's it in a thread. The main thread should be joining the voice channels on behalf of the threads and the child threads emit errors to the main thread.
The basic concept is to just forward the necessary data to the threads and each do their own thing
You will be fighting against memory usage if you spawn a thread per user. You can easily cluster those together since there will not be that much cpu usage as the audio is already opus encoded unless you need to do heavy audio processing. Even then, it's smarter to just cluster it all together
ok, thx
will try that out
@rose helm and of course it's a lot of memory, if I would import the whole library instead of just the things I need like you did in your example 😅
basically my bot leaves the vc after a while. no clue why
i have ffmpeg installed
I'm providing all the data but I still don't receive anything when listening to connection.receiver.subscribe(...) any ideas?
For on server and on state update I set the properties for the method (sessionId and everything else; I simply set it to the last update). I don't get any errors
Are you making sure that the types you're passing to the lib satisfy the type constraints the lib expects? The internal packet structure of my application is not synonymous with what should be passed to the lib
this.client.ws.on('VOICE_SERVER_UPDATE', async (info: GatewayVoiceServerUpdateDispatchData) => {
...
});
this.client.ws.on('VOICE_STATE_UPDATE', async (info: GatewayVoiceStateUpdateDispatchData) => {
// filter on clientID
...
});
this is 1:1 the object that should be set for onVoiceServerUpdate and onVoiceStateUpdate. I don't use any or unknown at all in my application, so there should never be a type mismatch
in the worker thread:
const _this: IVoiceRecorderData = workerData;
out = new ReplayReadable(_this.maxRecordTimeMs, _this.sampleRate, _this.channelCount, _this.options);
const connection = joinVoiceChannel({
channelId: _this.channelId,
guildId: _this.serverId,
group: _this.clientId,
adapterCreator: voiceAdapterCreator()
});
if (adapterMethods) {
console.log('methods available. setting server and state update')
adapterMethods.onVoiceServerUpdate(_this.serverConnectionInfo);
adapterMethods.onVoiceStateUpdate(_this.stateInfo);
}
const opusStream = connection.receiver.subscribe(_this.userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: _this.maxRecordTimeMs,
},
}) as unknown as ReadStream;
opusStream.on('data', () => {
console.log('data received')
})
ok. What state does the connection get into
well... signalling
well.... just switched the order of onVoiceServerUpdate and onVoiceStateUpdate and now it is working 😅
@rose helm thanks for the solution with the custom adapter!
well... F
I can only have one connection that means only one thread can have one... else it's, thread x needs it, thread y needs it...
any idea how i can debug this ?
On my docker machine it doesnt give any sound (locally it works)
I have ensured that the file is correctly loaded, my fstat does give the correct file and file infos
Happens in a docker container (streaming works tho)
this log is from my docker machine, so the file is correct 🤔
Could it be that you played a stream before playing the file?
Maybe, but locally it works with the stream and local file 😄
try using createFileStream(yourPath) instead of providing the file via path only
You can have one connection per bot instance per guild
*createReadStream
@fierce coral createReadStream from fs
Could be that this is related to this bug
https://github.com/discordjs/discord.js/issues/7232
Got it but i cant just pass it to the audioplayer ?
const resource = createAudioResource(createReadStream('myPath/to/my/file.mp3'));
audioPlayer.play(resource);
now it doesnt play the local file at all 🤔
this is weird
specifying the inputType while creating the audioResource might help
I have them as mp3 maybe thats why ?
I'm also using mp3 and it works with Docker
I've also set the streamOptions to {inlineVolume: true, inputType: StreamType.OggOpus}
everything else should be the same I guess
Oh wow just defined it with the OggOpus got @discordjs/opus missing Error
Tried to manually install 😄 Maybe some M1 issue ?
maybe some missing C++ stuff? Because node-gyp tries to compile the opus stuff which is C++
cant get smarter from this 🤷🏽♂️
Okay fixed it through "@discordjs/opus": "^0.6.0",
It stopped playing local files at all after updating the packagss
How can i make joining the bot an voice channel
discordjs.guide results:
• Getting Started: Introduction
It's covered in the voice connections section
Can just send stream data to other threads
unless the lib literally says only 1 per thread
idk if SharedArrayBuffer would be appropriate for this use case
what would be a way to wait until one file finishes playing
I want to query whether members with a specific role are in any voice channel how can i do this
get members in the voice channel, check if they have the role
I want to print whether members with that role are on the voice channel or not
so if the member with the role is not in the voice channel, I will report it as a message
If you wanna do something when a resource finshes playing you can use player.on('idle', () => {}) where player is your instance of the AudioPlayer.
Hi, when I run discord on my local windows 10 PC, it works well. But when I run it on a linux vps, there is no sound. And there is no error messages. I'm just playing some mp3 files.
Following are my dependencies:
···
"@discordjs/opus": "^0.5.3",
"@discordjs/voice": "^0.8.0",
"discord.js": "^13.6.0",
"ffmpeg-static": "^4.2.7",
"libsodium-wrappers": "^0.7.9",
···
adapterCreator: guild.voiceAdapterCreator,
iam making music bot ..what should i add here ??
is djs voice abandoned?
Nothing, just keep that.
It says : guild is undefined
Well yeah, guild has to be an instance of your Guild.
Ok.. Ty
const subscription = connection.subscribe(audioPlayer);
// subscription could be undefined if the connection is destroyed!
if (subscription) {
// Unsubscribe after 5 seconds (stop playing audio on the voice connection)
setTimeout(() => subscription.unsubscribe(), 5_000);
}```
What should I put in "audioPlayer"? The folder where my audio track is?
Your AudioPlayer object.
Why do I get Cannot play a resource that has already ended?
I'm trying with a spotify song
const { audioPlayer, joinVoiceChannel, createAudioPlayer, createAudioResource, createReadStream } = require('@discordjs/voice');
let server = client.guilds.cache.get("951556244492132382")
joinVoiceChannel({
channelId: "952690515327987712",
guildId: "951556244492132382",
adapterCreator: server.voiceAdapterCreator,
});
const player = createAudioPlayer();
const resource = createAudioResource('https://www.youtube.com/watch?v=jcBd5GLP1fg', {
metadata: {
title: 'A good song!',
},
});
resource.playStream.on('error', error => {
console.error('Error:', error.message, 'with track', resource.metadata.title);
});
player.play(resource);```
Why isn't it playing nothing
Does anyone have any tips for scaling DJS voice stuff? I keep running into issues where when the bot has been up for too long, the audio becomes distorted and slow :(
i have an AudioRecieveStream that i would like to send over a websocket using socket.io. i'm wondering if i could convert it into a format that could be sent over the socket. could i use @discordjs/opus to encode it, then decode it when it gets received by the client socket? if so, can i directly pass the AudioRecieveStream into the OpusEncoder#encode function and send that?
.
The first parameter of createAudioResource() is a Readable, not a String.
So how can I fix it?
Get a library that gets a readable stream of a song from youtube with only the url and use that instead as a parameter.
const { createAudioPlayer, createAudioResource } = require('@discordjs/voice');
const player = createAudioPlayer();
const resource = createAudioResource('img/a.mp3', {
metadata: {
title: 'A good song!',
},
});
resource.playStream.on('error', error => {
console.error('Error:', error.message, 'with track', resource.metadata.title);
});
player.play(resource);```
Why isn't it playing now?
Is your connection subscribed to your player? Do you have the GUILD_VOICE_STATES intent? Have you tried making the path to your resource absolute?
It could be any number of reasons.
Now I moved the track in the same folder of index.js..
So is only 'a.mp3' or '/a.mp3'?
How do I subscribe the connection?
connection.subscribe(player)
Look into using Path.join() to make it absolute.
const { createAudioPlayer, createAudioResource, getVoiceConnection, audioPlayer } = require('@discordjs/voice');
const connection = getVoiceConnection('952690515327987712');
const player = createAudioPlayer();
connection.subscribe(player);
const resource = createAudioResource('a.mp3', {
metadata: {
title: 'A good song!',
},
});
resource.playStream.on('error', error => {
console.error('Error:', error.message, 'with track', resource.metadata.title);
});
player.play(resource);```
You sure that's the correct ID?
yes, i have to put the voice channel id right?
No, guild ID.
oh ok
can i repeat the song more times?
No
does anyone know if this is possible?
How could I have a queue loop functionality that adds a song to the queue after it finishes
is there an event to listen to?
Hello so am ..
When I run my bot on a vps/locally I face a small problem - After playing a YouTube audio I cant seem to play a stream audio [Radio Stream].
I dont get any error on my console but no audio seems to be played
player.on('idle', () => {}) That'll run whenever a resource finishes playing in the AudioPlayer.
but how do i know what to add back
What do you mean?
well
how will it know the track that just ended, so i can add it back
@rugged sky ?
Just store your youtube link or whatever somewhere so you can create another resource with it when the time comes.
how could i do tha
?
Just add it to your client or whatever as a property
and how do i do that, i only started discord.js today sorry
I would recommend learning Javascript as a language first before diving into this. It's just basic stuff that'll help you solve issues like this.
ok, but could u tell me for now how to add the track as a property
ive learnt a decent bit of js
client.track = <your track here>
so if i edit client.track in a command, it will change globally
It'll just add a property called track to your client object.
so would i do it so like
when the client player starts playing, it stores client.track as the current song
You shouldn't store the resource itself since you cannot replay a resource. Store whatever link or file path you created the resource from so you can create another one.
oops
Would smth like this work?
idk just run it to see
it never triggered the event
Did the audio start playing and the event didn't trigger or did it never start?
the audio played fine
just that listener never ran, once it started playing
bruh this slow mode is annoying
What are you expecting to happen in the listener that isn't happening?
well the listener isnt running?
How do you know?
oh my bad, i added a console.log after that image
Welp if the listener doesn't work I can't help you with that. It should just do it.
well am i doing the listener wrong
Not that I can see, otherwise I would have said so.
can i send full index.js
Sure, but I'm in class right now so I'll take a bit to look at it.
alr ty
Yeah, you're not using only discord.js; This is a help server for that package. For the player you're using discord-player so it doesn't work the same. You should find a discord-player help server if you have questions about it, but for this specific one I'm pretty sure the events are called different names in that package so you should figure out what even you should listen to.
yea my bad,
thanks for the help (darn slowmode)
np
@discordjs/opus stuck at 99%
Isnt opus deprecated
its deprecated
use @djs/voice
Utilizing the @discordjs/voice package and the basic code for playing music, the Discord bot I'm using doesn't seem to play anything. I have tried installing and uninstalling many packages, changing how my code works, etc. Nothing seems to be working.
audioPlayer.js (fileName is a String):
https://sourceb.in/VQkXMkPrvp
package.json:
https://sourceb.in/aFTYUYmvC8
interactionCreate.js (just for /play):
https://sourceb.in/Oz0YxToSFU
@discordjs/opus and voice are only related because opus encodes and decodes opus packets while voice is Discord voice related stuff which uses opus packets. What you should be recommended instead of the djs opus package is opusscript. Everyone should be using opusscript
idk never used djs for voice
Hello so am ..
When I run my bot on a vps/locally I face a small problem - After playing a YouTube audio I cant seem to play a stream audio [Radio Stream].
I dont get any error on my console but no audio seems to be played
opusscript isnt too great for production
Well, it's the next best option considering there's a memory leak whenever encoding opus packets with @discordjs/opus. This can be observed by setting inlineVolume: true in AudioResources in voice and the pipeline going from ffmpeg pcm to opus
I personally use it for production and have encountered no issues thus far.
Hi, I was trying to get my bot to join a channel but its not working at all, as I'm getting a TypeError: o is not a function
I tried removing the adapter control, but neither is working for this.
const { joinVoiceChannel } = require('@discordjs/voice');
const connection = joinVoiceChannel({
channelId: "123",
guildId: "12344",
adapterCreator: client.guilds.fetch("12344").voiceAdapterCreator,
});
});```
The IDs you're using are undoubtedly wrong. Did you double check them?
Ah I've used those just so I don't show my real channel/guild IDs
Ah okay, that makes sense haha.
Does any one known why 
I can seem to see why ...
You're still yet to show code
u didnt resolve promise of guild fetch
How should I send the code like the important parts or the whole code
relevant parts
const player = createAudioPlayer();
try {
await joinVoiceChannel({
channelId: interaction.member.voice.channelId,
guildId: interaction.guildId,
adapterCreator: interaction.guild.voiceAdapterCreator,
}).subscribe(player)
} catch (error) {
}
const resource = createAudioResource(stationURL);
player.play(resource);
player.on(VoiceConnectionStatus.Disconnected, async (oldState, newState) => {
try {
await Promise.race([
entersState(player, VoiceConnectionStatus.Signalling, 5_000),
entersState(player, VoiceConnectionStatus.Connecting, 5_000),
]);
} catch (error) {
}.catch(() => {
})
return player.destroy();
}
});
Don't use joinVoiceChannel if it already exists.
You're using VoiceConnectionStatus events instead of player status events.
If its youtube its ```js
let play_youtube = await ytdl(song.url, { highWaterMark: 1 << 25, filter: 'audioonly' });
If it does exists?
you can getVoiceChannel
So have an if?
ye
Will that solve the issue?
idk. If you also fix the fact you're using the wrong events, then maybe
What are the event that needs to be checked
read the docs for player events
or just change passing the player for the connection instead
const msg = message.content.split(" ").slice(1).join(" ")
const channel = message.member.voice.channel;
if(!channel) return message.channel.send("You need to be in a voice channel to use this command!");
say.export(msg, null,1, `./temp/${message.id}.mp3`, (err) => {
if (err) {
return console.error(err)
}
console.log("Saved!")
})
const player = createAudioPlayer();
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
})
connection.subscribe(player);
const resource =createAudioResource(`./temp/${message.id}.mp3`);
player.play(resource);
player.on('error', error => {
console.error(error);
});
player.on(AudioPlayerStatus.Idle, () => {
connection.destroy();
});
the bot isn't playing the audio
the file is created
am I able to store player and call it in a different function like pause cause rn I have to make it a global to use it
I want player.pause(); to work like vc[guild].player.pause();
Hey, how come the voicestate has all these null fields after joining a voice channel?
Its logging before it joins
Do you have the GUILD_VOICE_STATES intent? If you do, try making the path to your file absolute.
More specifically while its attempting
Ah! I attempted to do a .then on the joinVoiceChannel method but it threw an error saying that was invalid
Is the joining async? I'm not sure how to latch onto it and run subsequent code
Unfortunately you cant async it or from what ive found you cant. Ive been trying to do the same thing but with checking if it failed to join. You will have to either set timeout or log later in your code
Just listen for the 'ready' state.
You can get your player from your voice connection if it is subscribed to it. I can't quite remember what it is exactly, but something like connection.state.subscription.player gives you it. And you can get your connection anywhere in your code by using getVoiceConnection().
joinVoiceChannel returns a Promise you can await iirc
sick!
can you tell me how can i see the voice connections of the bot? bot.voice.connections.size isn't working anymore, please help its needed
getVoiceConnections(), it returns a Map<String, VoiceConnection>.
oh
https://www.codepile.net/pile/VmZvG0mG
Any idea what's that?
happens few seconds after starting a voice activity:
channelId: vc.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
})
const stream = ytdl(vid, { filter: 'audioonly' })
const player = createAudioPlayer()
const resource = createAudioResource(stream, { inlineVolume: true })
resource.volume.setVolume(vol / 5);
player.play(resource)
connection.subscribe(player)```
is there any method in @discordjs/vocie package that would detect the StreamType for us?
or does the StreamType even required?
i'm working on a package, i just wanna know what kinda types should i get?
right now i'm accepting Readable, IncomingMessage, Buffer, Opus.Encoder, FFmpeg
How would I go about doing something like this
So I am creating a public radio bot. And want it so the user can invite the bot and the server administrator can set a channel that will make it so the bot only joins that channel. And another part of the bot will be able to grab the listeners that each server currently have and plug it in to my api
not kinda related to this channel, but i'm pretty sure you can check and update some variables on the voiceStateUpdate event
https://discord.js.org/#/docs/discord.js/stable/class/Client?scrollTo=e-voiceStateUpdate
i don't really get your question but:
you could use a database to store data heres how it will go:
KEY: GUILDID
VALUE: CHANNELID
there are some simple key, value npms out there that allow you to use databases
best one (this allows you to use cloud databases): keyv
an built in one (this is called fs allows you to write to files you could make your own json database): fs
semi best (this one is called simple-json-db this is really simple for json databases and requires zero effort): simple-json-db
honestly this one is pretty good still (its called quick.db and it works like simple-json-db but a different file format and some more methods for storing data): quick.db
how do I make bot as a speaker in a StageChannel?
stagechannel.guild.me.voice.setSuppressed(false);
Do you recommend me to use packages or discordjs voice?
is it possible to set the volume?
yep
Asked this a while ago, never received any guidance. Anyone got anything?
how?, and also how can i check when a song ended?
you need to enable inlineVolume
where?
and after that?
After a player finishes a resource it will enter the 'idle' state, you can listen to that. If you want to check a resource specifically you can check its ended property.
player.on("idle")?
Yeah
ok thanks guys
it didnt work
ohh nvm i accidentally did connection.on
So
resource.volume = 100 for example?
is it possible to stream video in vc?
any1?
nope
resource.volume?.setVolume(0.5)
ok
i am unable to install this @discordjs/opus
I can't get newly voice channel of member using message.member.voice.channel, it returned null
does anyone have this?
nvm, I'm lack of intents
npm install --global --production --add-python-to-path windows-build-tools
install these first, on an administrative cmd
Will it work
Cause is run and then nothing
These are removed
is it possible to somehow get the sound that's coming from a user in a voice channel?
How to make bot leave VC?
connection.disconnect() or connection.destroy() where connection is your VoiceConnection.
where connection is your VoiceConnection.
https://www.codepile.net/pile/VmZvG0mG
Any idea what's that?
happens few seconds after starting a voice activity:
channelId: vc.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
})
const stream = ytdl(vid, { filter: 'audioonly' })
const player = createAudioPlayer()
const resource = createAudioResource(stream, { inlineVolume: true })
resource.volume.setVolume(vol / 5);
player.play(resource)
connection.subscribe(player)```
Probably an issue with YTDL. It has quite a few abort issues. I'd recommend switching to play-dl.
oke ty 🙂
hey guys my bot joins my vc but doesn't play the audio, and there are no errors can someone help me? this is my code https://sourceb.in/GwqqYzvahX
try install discord opus
createAudioResource() only takes a Readable, or a String that is a filepath as input. You cannot just use a link.
Hi, my music bot doesn't work, when I install @discordjs/opus it gives me these errors, now I send them to you
i tried a filepath also but that didn't work
i tried ./path/to/file/ and D:/DiscordBots/bot/path/to/file but neither worked
Do you have the GUILD_VOICE_STATES intent?
No.
You need that.
how can i know which users have permission to join in voice channel
i want there names or id as output
did you got your answer ?
i added them and now the bot joins the channel, it appears that its talking and leaves the channel, but the audio isn't playing
Then your AudioResource is probably still not being created properly. Could be any number of reasons.
i didn't have the output device set up properly in my settings
it works now
is it possible to capture the audio from a vc the bot is in? like when someone talks, start recording and when they stop talking it saves in a mp3 file
or is that against discord tos or something
needs a seperate package and/or api for that
for example mee6 does create voice recordings after u speak in a voice channel
what package and/or api is it?
The voice package can do voice receive
idk tbh u can go check at their git hub repo tho
@discordjs/voice can do that?
wait fr 👀 ?
Yes
how
hmmm okay ty! ill explore more into that then i rly didnt know that tysm 
i saw something called VoiceRetriever
and something called AudioReceiveStream, are those it?
👀
yep its all there tysm
As long as it’s reasonable. Music bots shouldn't be recording vc, for example
i want to record what a person talks then change the pitch and say it back
i think u can add filters to ffmpeg if im not wrong
so with that u can just alter/edit the voice of that person? rly gotta dig into it
How do I handle a memory leak?
Guide suggestion for @feral coral:
discordjs.guide results:
• Creating Your Bot: Event handling
• Creating Your Bot: Individual event files
how can i wait for an AudioRecieveStream to be closed?
i'm trying to read from a receiver subscription, but the read function is returning null.
i think it might have to do with the write stream not being closed before it tries to read
Hi 😄 How can i create voice channel with users limit in specific category?
use userlimit and parent id
hey so ive been trying the past couple of hours but nothing seems to be working. How can I get my discord bot to join a voice channel when I start the bot?
tried the guide and all
nun works
anyone?
I said I tried the guide
how do you get users speaking on vc
connection.receiver.speaking.users returns Map(0) {} when speaking or not speaking
am i missing something?
https://discord.js.org/#/docs/discord.js/stable/class/VoiceChannel how do i join a voicechat if the method isnt even here
you may need to enable your intents
i have all of them emabled on code and discord dev portal
what about where you intialized your client
wdym
on my main file?
it should look something like this so you can get voice states
^
where you instantiated your client
i didn't get it (sorry for bad english)
Yes but what does it have to do with @discordjs/voice library
idk, as it is pretty much in vocal, i didn't really know where to put it,
also i found how to, so i'll delete
what the hell does this mean
i dont understand why this couldn't just stay in the main library like it always was 🧍🏼♂️
Again no answer on this, asked quite a few times. Anyone have any ideas?
It means you are trying to call .once() on something, but it's undefined.
Use the joinVoiceChannel() function. It's in the guide.
I'll be honest i know we're meant to give information about this, but i really don't know what's happening, yesterday it was working, but sometiems in a vc with multiple people it does this( and it randomly started working again, same vc same people)
anyone had any issues with audio quality going bad after a few seconds of playing via an audio stream via url? Hosting via AWS. If you did, if you could let me know any solutions u had to this it will help me a lot.
İ always get connection.playStream() is not a function
Are you trying to call .playStream() on your connection?
client.on('messageCreate', message => {
if(message.content === 'tst') {
const name = db.get(`j_${message.guild.id}`)
voiceDiscord.joinVoiceChannel({
channelId: name,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
})
const streamOptions = { seek: 0, volume: 1 };
const { getVoiceConnection } = require('@discordjs/voice');
const connection = getVoiceConnection(message.guild.id);
const stream = ytdl('https://www.youtube.com/watch?v=_8Ql9I0qJoM', { filter : 'audioonly' });
const dispatcher = connection.playStream(stream, streamOptions);
}
})
connection.playStream() is nothing. I don't know where you got it, but that's not how you play audio on a voice connection. Read the guide regarding AudioPlayers and AudioResources.
when i move the bot from one channel to another it shows the same channel id for both the voice states
this issue has been bugging me from a year
and also when i move the bot to another vc and check the cache it shows that the bot is still in the initial channel
Add the GUILD_VOICE_STATES intent to let your bot receive voice state updates.
it's been there the whole time, i wouldn't have gotten the initial events otherwise
Show full code
this is all that's needed for voice state updates
i have a question
when something playing on player for example i ytdl() a song and my player is stucking for a second then resuming play
i don't know how i explain this
Can anyone tell me did different lavalink help music bot to give different kind of audio quality ? Or all the lavalink works same.
If im not wrong i personally think its due to discord api lag if it happens sometimes.
but it only happens when i do ytdl stuff
dont mind but what u mean by ytdl
i mean downloading a youtube video from ytdl
to play it with audioplayer
this is not the server to ask that, the jda server would be better
is it possible to record a voice channel?
your dms are closed and you can't post invite links here but the vanity url is "jda"
it is
How?
How do you mean?
I don't think so. This is the AudioResource if you wanna check it out for yourself: https://discord.js.org/#/docs/voice/stable/class/AudioResource
?
does anyone know anything about this?
how do i check if somebody is speaking? cause i want to record then send to speech to text for voice commands
with the recorder example im getting
prism_media_1.default.opus.OpusHead is not a constructor
My join function:VoiceChannel.join().then(connection => { connection.play(getRadioURL(radioID), {volume: 0.5,});}) How can I now in another function get connection from client to change stream/song
v12 voice is not supported
Hello there, I'm trying to use v13 Voice to join a voice channel and play an audio file, I've set the GUILD_VOICE_STATES, looked all over google, bot has the Connect and Voice permissions... connection gets stuck in signalling
I'm using node LTS 16.14.2 with these deps
"dependencies": {
"@discordjs/voice": "^0.8.0",
"bufferutil": "^4.0.6",
"discord.js": "^13.6.0",
"ffmpeg-static": "^5.0.0",
"libsodium-wrappers": "^0.7.10",
"opusscript": "^0.0.8",
"tweetnacl": "^1.0.3",
"utf-8-validate": "^5.0.9",
"zlib-sync": "^0.1.7"
}
still stuck
also the guide page for voice needs to be expanded since there is not really much there
Seems like the channel had some wierd permissions for Robots, it's all good
hey, yesterday i made a radio bot. However this one when he joins the voice he broadcasts music but it stops after 5 sec can someone help me the bot has no error ect
did you use the guide cause in the guide there is a part that stops it after 5 seconds
Thé problem is if the people in vc non speak = music is stoping but i want if no people speak = playing again ( srry my english is so Bad)
i dont know how to check if somebody is speaking sorry
https://github.com/discordjs/voice/releases/tag/v0.6.0
Trying to use this djs code in mine but EndBehaviorType is not defined ??
here's my code btw: https://srcb.in/rKHRvOwAly
it's pretty much identical but i changed the connection thing to work for the user's channel
help me pls im somehow getting this same error whenever bot joins and plays music in my vc ```js
Connected to mongodb
AbortError: The operation was aborted
at abortListener (node:events:838:14)
at EventTarget.<anonymous> (node:events:874:47)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
at EventTarget.dispatchEvent (node:internal/event_target:504:26)
at abortSignal (node:internal/abort_controller:97:10)
at AbortController.abort (node:internal/abort_controller:122:5)
at wt (C:\Users\chibu\OneDrive\Desktop\moosic beta\node_modules@discordjs\voice\dist\index.js:9:316)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}
[antiCrash] :: Multiple Resolves
reject Promise {
[
{
status: 'connecting',
adapter: [Object],
subscription: [O],
networking: [z]
},
{
status: 'ready',
adapter: [Object],
subscription: [O],
networking: [z]
}
]
} AbortError: The operation was aborted
at abortListener (node:events:838:14)
at EventTarget.<anonymous> (node:events:874:47)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
at EventTarget.dispatchEvent (node:internal/event_target:504:26)
at abortSignal (node:internal/abort_controller:97:10)
at AbortController.abort (node:internal/abort_controller:122:5)
at wt (C:\Users\chibu\OneDrive\Desktop\moosic beta\node_modules@discordjs\voice\dist\index.js:9:316)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}
i need guidance
i followed the guide for playing yt music
but it only works with this !play URL I want it to search songs and then play so smth like !play <song name> or !search <song name>
I dont think its related to discord.js
Use a library to search youtube song based on search terms. Discord.js can't help you with that.
ah thx
oops
Don't use entersState. Make your own entersState function
i'm using the discord-player package and made my own extractor for it but here is the only place in the package where i found the entersState what should i do ?
issue on their end then
check if someone unmutes in the vc and stop your player accordingly
it's probably an error in that package or your own extractor, i'd suggest to try without your extractor for a change
instead use an open source one which is maintained regularly
Anyone know anything
522 is a CF error, not much you can do except try again later
CF?
Cloudflare
You’ve prob seen the screen before https://support.exabytes.com.my/en/support/solutions/articles/14000100761-error-522-connection-timed-out
It might be because playing audio in many voice channels?
Because it’s happening a lot
The discord api status page seems to state that voice is working fine
My bot joins the channel and spams The audio player has started playing!
but it doesnt acctualy play anything...
const { createAudioPlayer, createAudioResource, StreamType, joinVoiceChannel, AudioPlayerStatus } = require('@discordjs/voice');
const { createReadStream } = require('node:fs');
var fs = require('fs');
module.exports = {
name: 'voiceStateUpdate',
async execute(oldMember, newMember) {
const player = createAudioPlayer()
const audioResource = createAudioResource('./src/audio.mp3')
joinVoiceChannel({
channelId: newMember.channel.id,
guildId: newMember.guild.id,
adapterCreator: newMember.guild.voiceAdapterCreator
}).subscribe(player);
player.play(audioResource)
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
},
}
any quick fix?
how do i make the bot leave after 30 secs of joining the voice channel
setTimeout 🤔
@subtle granite could ya help me?
This issue happened but i don’t remember how did i fixed it😅
Idk how’s this helping, but search for it, it’s easy
i did
im searching for multiple hours now, can u show me your code?
@subtle granite could u check your code?
I'm also stuck on this, trying to get my bot to play an mp3 in a channel
Yea the guide doesnt help
yeh, ive followed a bunch of different tutorials at this point 😢
It’s not simple as yours
I can’t now
ah
Someone help me with this haha
so on https://discordjs.guide/voice/audio-resources.html#creation the first example given they've made the audio file into .ogg and .webm when using createAudioResource
so you might need todo that? I'm learning still so i have no idea
createAudioResource(createReadStream(join(__dirname, 'file.ogg') they've also got anther param here, not sure why
oh and they're using createReadStream()
shouldnt matter
wait, its working
thanks :)
@subtle granite Now it works, but the audio is stopping randomly and replaying and it also starts after 30sec of being in the voice channel
what does your code look like now? @devout quarry
const { createAudioPlayer, createAudioResource, StreamType, joinVoiceChannel, AudioPlayerStatus } = require('@discordjs/voice');
const { createReadStream } = require('node:fs');
const { join } = require('node:path');
var fs = require('fs');
module.exports = {
name: 'voiceStateUpdate',
async execute(oldMember, newMember) {
const player = createAudioPlayer()
const audioResource = createAudioResource(createReadStream(join("./src/", 'audio.ogg'), {
inputType: StreamType.OggOpus,
}));
joinVoiceChannel({
channelId: newMember.channel.id,
guildId: newMember.guild.id,
adapterCreator: newMember.guild.voiceAdapterCreator
}).subscribe(player);
player.play(audioResource)
},
}
cheers
after some seconds of lagging, it just stops and replays
made it an .ogg file then eh
audio is something like 3min long but it cuts at 15sec
i couldnt understand this bit join("./src/" but that's shows me now, thanks
oh yea its a path
ah sweet, it was the .join() function i didnt get
oh you have a audio.ogg file
so i need to make my mp3 file into that?
join(path, filename)
what does .join() do exactly?
create a path to the file if im not wrong
because .../audio.ogg wont work i think
yeh makes sense, how did you convert audio file into a .ogg file?
just google convertor
ah cool
ah was trying to figure out which language that was haha
changed it
cant get mine to work, get this DiscordAPIError: Invalid Form Body on player.play(audioResource);
which means audioResource is wrong for player.play() somehow? I dunno
record multiple users at once how
It means the embed you sent is malformed/invalid
Has nothing to due w/ voice
so my createAudioResource(createReadStream(join("/sounds/", 'Sup-brah.ogg'), file embed is wrong?
That's not an embed
oh which bit is?
I'm talking abt a Discord Message Embed
Has nothing to due w/ voice
how would i make my bot join vc auto and play the radio stream
right but im not using the messsage embed, im using createAudioResource() is that an embed? I dont really get what an embed is.
But smth is sending an embed
thanks for the help btw
discordjs.guide results:
• Popular Topics: Embeds
• Popular Topics: Embed preview
oooo okay so im sending that somehow
Yea. Voice package doesn't (and can't) do that on ur behalf
cheers, got rid of that error now! Thank you ❤️ ❤️ ❤️
Hi
I'm having trouble creating a @discordjs/voice player
My problem is the code works fine when run locally, or in Docker container on my machine, but won't run in a Digital Ocean app
This is my code ```typescript
import {
AudioPlayerStatus,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
NoSubscriberBehavior,
VoiceConnection,
} from "@discordjs/voice";
import Config from "config";
import path from "path";
import { Global } from "../Global";
export default class VoiceChannelController {
static player = createAudioPlayer({
behaviors: { noSubscriber: NoSubscriberBehavior.Pause },
});
static get resource() {
const p = path.join(__dirname, "..", "sounds", "test-sound.webm");
return createAudioResource(p);
}
static connection: VoiceConnection;
static async init() {
const bb = Global.bot("VOICE_BOT");
const channel = await bb.guild.channels.fetch(Config.channelId("VOICE"));
if (channel === null) {
throw new Error("Cannot find voice channel.");
}
this.connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
debug: true,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false,
});
this.connection.subscribe(this.player);
this.connection.on("debug", (...args) => {
console.log(...args);
});
this.connection.on("error", (...args) => {
console.log(...args);
});
this.player.play(this.resource);
this.player.on(AudioPlayerStatus.Idle, () => {
this.player.play(this.resource);
});
}
}
As I mentioned it works as expected running on my machine, or in a Docker container on my machine, but fails silently in a Digital Ocean app container. It feels like this will be an utter pain to debug - hoping somebody here has some insight
Here is some of the debug output - https://pastebin.com/USHAtrfH
Use joinVoiceChannel from this package
message.member.voice.channelId
how would I create an event listener that listens to every guilds player without making a listener for each guild or would I just make listener for each guild anyway?
cause rn its activated as a function
Just make the event every time you make the player
just to be clear you're saying an event for each player?
Thank you!
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
}); ```
This mean if no one in the VC, it will pause, right?
No, it means if no connections are subscribed to the player, the player will pause itself
And how it can play if there’s no connection 🤨
Is it possible to do something like this @icy maple
Hi again, can't get the audio to play in the voice channel. I'm not getting any errors. Can anyone see any issues with this code?
hello whenever it try to install "@discordjs/opus": "^0.7.0" on my vps it gives me these errors: https://media.discordapp.net/attachments/766116919983079434/956852527251456000/unknown.png?width=904&height=582
it installs with node perfectly on my vsc on pc but when transferred to a VPS it emits that error
my server is running node: v16.14.0 & npm v8.5.2 (errors)
my PC is running a slightly older version than vps v16.13.1 & npm 7.20.0 (0 errors)
show the rest of the error
whats the os on your vps
centos
i didn't quite get the:
sudo yum groupinstall 'Development Tools'
what should i do in my case?
run that on your vps
oh ok
installed
install opus again
Playing isn't the responsibility of the Connection. The connection just manages the ws connection for voice
Yea, you just have to implement it yourself using the voiceStateUpdate event
@subtle granite still have the same problem as yesterday,
My audio laggs a bit then stops after ~15sec and restarts
i have connection.destroy() how i do make it disconnect after 30 seconds tho?
not discord.js related
Thats some basic js
Is there a way to make the bot go into voice chat when the bot is in ready status?
thats what im trying to do
Did I need to make a client for djs voice?
There needs to be an active gateway connection, but it can be totally separate from your bot's code
Is createAudioResource deprecated? I cannot find it in the documentation
It's an exported function, which jsdocs currently doesn't support showing
Trust the .d.ts files the most
Hi guys, i'm starting to implement the discord/voice library, before this change i was using join to use .then() to execute code whenever the bot connected, is there a way to do the same?
//OLD CODE
voiceC.join().then(async connection =>{ //connect the bot
msg.channel.send(this.bh.embed.createSongEmbed(this.bh, msg, song.title, song.member.user.username, song.member.user.avatarURL, song.link, song.thumbnail))
connection.play(link)//(ytdl(song.link,{filter: "audioonly"})
.on('start', ()=>{
//Canzone iniziata, metto timeout a null
if(this.timeout != null) clearTimeout(this.timeout);
this.timeout = null;
})
.on('finish', reason =>{
console.log("[DEBUG]" + `[${msg.guild.name}]` + " canzone finita: " + song.title + " Reason: " + reason)
//check if there are more songs to be played
this.playNext(msg,guildQ.random)
})
}).catch(console.error)```
```js
//NEW CODE
const { joinVoiceChannel } = require('@discordjs/voice');
joinVoiceChannel({
channelId: msg.member.voice.channel.id,
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator
})```
connection.on('ready', () => {}) executes whenever your connection is done and ready. The joinVoiceChannel() function returns a VoiceConnection object so store that as connection or whatever.
That's not code executed at the start of the bot, it's when someone calls it to play something from youtube
But i think i've found a guide on the website
With JoinVoiceChannel, the bot exits the channel after a while... Is it possible to somehow solve this?
const { createAudioPlayer, NoSubscriberBehavior, joinVoiceChannel, createAudioResource } = require('@discordjs/voice');
const player = createAudioPlayer({behaviors: { noSubscriber: NoSubscriberBehavior.Stop, deaf: NoSubscriberBehavior.Deafen }});
const resource = createAudioResource(`${process.cwd()}/assets/audio.mp3`);
const connection = joinVoiceChannel({
channelId: vc.id,
guildId: client.config.guildId,
adapterCreator: vc.guild.voiceAdapterCreator,
});
player.play(resource);
connection.subscribe(player);
any reason why this is joining the vc but not playing audio? (the mp3 file exists)
what was it?
I would guess the path was wrong?
oh, lol, I see
ah, I see, you should have waited for the connection to be ready before starting to play the audio resource
or used NoSubscriberBehavior.Pause for it to resume as soon as the connection is available
til
const connecting = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.member.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: true,
selfMute: true,
})
if (connecting) {
message.reply(`${client.emotes.success} | Move Me To Another Vc!`)
client.on("voiceStateUpdate", async (oldmem, newmem) => {
if (newmem.member.voice.channel && newmem.member.voice.channel.id !== channel.id) {
let newchannel = message.guild.channels.cache.get(newmem.member.voice.channel.id);
if (client.user.id === newmem.member.user.id) {
channel.members.forEach(e => {
e.voice.setChannel(newchannel);
})
const connection = getVoiceConnection(newchannel.guild.id);
connection.destroy();
}
}
})
}
bot joins and moves everyone to second vc the first time
but if i'm executing the command second time it's not connecting to voice channel
nothing happens, it just says application did not respond
Hey does someone here know any way to check if the client was kicked out from vc.
discord didnt send that event as i know, only voiceStateUpdate
when I play a video that is during a quite long time, I got this error: https://sourceb.in/xjpDGVb03N
is that ytdl?
you use ytdl-core or play-dl?
Your trying to editReply without replying first
ytdl-core
try to use play-dl
are you sure that this coming from ytdl-core?
so many user getting aborted issue when using ytdl-core
I'll try to change when I go home, thanks
is it possible to make a bot say things based off what the string is in the command?
Does anybody have any ideas with this 🙏
how do I get the timestamp for how far player is through a song?
nvm I finally found it in the doc
https://discord.js.org/#/docs/main/v12/class/StreamDispatcher?scrollTo=streamTime
hi, is djs capable of recording the audio from the channel?
hello, this is my code
https://sourceb.in/RLkhbQ3vWZ, im trying to do a music bot but gives this warn, who can help me fix it? idk how
(node:11940) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 addSong listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit (Use `node --trace-warnings ...` to show where the warning was created) (node:11940) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 playSong listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit (node:11940) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 searchNoResult listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit
im trying to make a simple and little music bot, idk how to fix this warn/error
nvm i fixed
whyy
That only checks if connection is null/falsy
You would need to check if the actual .state.status is destroyed
if (connection && connection.state.status != "destroyed")
Like this will work👀
idk how to try it
I think so, I just use the enums instead of magic strings
i don't like this magic, but idk about enums, so ty
d.js v14 will force you to use enums (at least for the main lib)
then i don't think i'll use it soon 🙁
hi, i'm seeing stageInstance = null, but stage is already open when i try to createStageInstance
I followed the discordjs voice recorder demo, and have it recording chat perfectly, but weirdly, when someone else speaks, they are not picked up at all, is there any way to subscribe to everyone in the channel speaking?
const { VoiceConnectionStatus, entersState } = require('@discordjs/voice');
is this correct?
npm i @discordjs/voice
what is the difference between that and:
client.on('voiceStateUpdate', async (oldState, newState)=>{ ...
?
voiceStateUpdate and the voice package are completely different things
what is the package for then?
voice.
.
in which sense voice
sending voice data, apparently you can even receive it too
is like a voice bot with prerecord mp3 files?
hey! sorry for the ping but i wanted to ask u what did u define client.play as ? just to know /g
I’ll check later
I don’t think I defined it
I'm fairly certain it can only do a single user, thats why you have to provide the user id when calling it
Makes sense, but like... why?
because thats how discord sends audio
if you want to record all the users in a channel you would have to subscribe to each user individually and merge them together (probably with ffmpeg or something similiar)
Sure, except, discord only listens when you're speaking so if I was to take 4 different people talking and each person spoke at different times, all the tracks would be off, so merging them is almost impossible.
It's like I need to create some kind of empty audio stream and then merge the user streams into that single audio stream, as they speak.
correct, ffmpeg can fill it with silence, and then you would have to merge each stream into it,
I managed to do the "have silence if there they arent speaking", not sure how to stream multiple streams into it tho
Okay, how do you do the "have silence if no one is speaking"? that may help me a lot, I am sure I can f*** around with ffmpeg to merge multiple streams part, it's the making empty noise part that is kinda confusing.
I see there is a behaviour type of manual, but typescript throws a tantrum when trying to set it, saying you can't set behaviour to that.
are you using discord.js or discord.js/voice?
@discordjs/voice
I dont see any type parameter
its now "end" and that just defines when it should stop listening
I have this code tat when the connection reaches ready it runs the below.
Ignore all the logging btw, just testing output.
Then that is the contents of createListeningStream
yes there is EndBehaviourType.Manual but it just means that you have to stop the receiver whenever you feel like it
its quite a time ago so I dont remember but this seems promising
https://superuser.com/questions/1598926/fill-gaps-in-piped-in-audio-with-silence-in-ffmpeg
there might be easier ways to do this but I usually just use ffmpeg for everything lol
Okay interesting, so if I remove the end: {} part, I assume just don't define it, then it would keep creating audio>
nono
Oh
That is what happens if I set it to manual.
probably have to remove duration
You're a saviour, so okay, to confirm, this will keep recording even though there is no voice activity? which would create a continuous stream?
yes, but pretty sure it wont be filled with silence
Okay, so maybe if I was to drop OggStream and use something like ffmpeg, I could accept the voice stream, fill any empty space with silence, and then merge them together (probably after the voice call)?
you have the receiver.subscribe method which returns a stream,
at all times the stream will only write data when the users speaks, afaik this will always be like that
with AfterSilence => destroys the stream as soon as the user stops speaking
with manual => the stream runs forever until you stop it
you still have to manually fill it with silence if the person isnt speaking
if its ok to do it after the voice call it would be the easiest way to do it like that yes
Yeah I think so, we just want to use it for recording live discussions/meetings in voice chats, we won't need it directly after, and at least then I could call the ffmpeg from a thread rather than the main bot process I think.
So next, but probably silly question, I assume I shouldn't use OggLogicalBitstream but rather pipe the AudioReceiveStream into something better? Or do I still need to use this part:
const oggStream = new opus.OggLogicalBitstream({
opusHead: new opus.OpusHead({
channelCount: 2,
sampleRate: 48000,
}),
pageSizeControl: {
maxPackets: 10,
},
crc: false,
});```
I'm not sure I didnt do much with the new voice system, before that I just piped the raw pcm into ffmpeg
// spawn is from child_process
const child = spawn('ffmpeg', [
'-f',
's16le',
'-ar',
'48000',
'-ac',
'2',
'-i',
'pipe:0',
// add rest of ffmpeg parameters here
// preferrably test it with a file as output
]);
const pipe = pipeline(stream, child.stdin, err => {
if (err) throw err;
});
if you need any more help, I will be back in like 40 minutes and then I can play around with it myself and see if I can get it working
Interesting okay, I shall have a look at it and get back to you, thanks so far.
@astral lark did you get it to work
Not yet, reminding myself how to use ffmpeg aha, but don't worry I will shout if I get stuck.
I'm trying to get the recorder example working but have run into a ton of issues 😦
I've gotten the bot to start and join voice, but it throws this error on line 19 of createListeningStream.ts when it tries to begin recording:
const oggStream = new prism_media_1.default.opus.OggLogicalBitstream({
^
TypeError: Cannot read property 'opus' of undefined
I'm on node v16.8.0. Anyone know how to fix it? I also think it's odd that the actual line in the file is new prism.opus rather than what the error says, which is new prism_media_1.default.opus.
Huh... importing the function directly worked but I'm not sure why:
import { OggLogicalBitstream, OpusHead } from 'prism-media/dist/opus';
const oggStream = new OggLogicalBitstream({
opusHead: new OpusHead({
...
Make sure you're using the alpha version.
I had the same issue earlier.
My package.json has "prism-media": "^2.0.0-alpha.0" and I reinstalled it a few times just be sure. I also updated other libraries in there to more recent versions in case any of those were the issue
who can help me? when i say ~play the bot joins and leaves, my code is:
im in v13
This server is for help with Discord.js. You're using Distube to play music. You should look for a Distube help server.
okk
how do i get a list of all voice channels my bot is in
how to get the parent category of a channel in voice state change event?
<VoiceState>.channel.parent
VoiceState has to have pointy brackets?
Explaining <Class> and Class#method notation: learn more
https://discord.js.org/#/docs/discord.js/stable/class/VoiceState
i dont see parent here tho
you didnt see the channel properties yet
i see parentId only in categoryChannel
Documentation suggestion for @pure ledge:
VoiceChannel#parent
The category parent of this channel
read the docs carefully
let ch3 = newState.channelId
console.log(client.channels.cache.get(ch3).parentId
is this supposed to be the way?
can't you just access channel property from newState and parent from newState.channel
actually that code works
const client = require("../index").client
const { Collection, UserFlags } = require('discord.js')
const voiceCollection = new Collection();
const guildmodel = require('../models/guild.js');
const jointocreatemodel = require('../models/jointocreate.js');
client.on("voiceStateUpdate", async (oldState, newState) => {
const member = newState.member
let guilddata = await guildmodel.findOne( { guildId: newState.guild.id} )
if(guilddata.jointocreate === "") return
let test = await jointocreatemodel.findOne( { guildId: newState.guild.id, userId: member.id } )
if(!oldState.channelId && newState.channel.id === guilddata.jointocreate ){
let jointocreatedata = await jointocreatemodel.findOne( { guildId: newState.guild.id, userId: member.id } )
if(jointocreatedata) {
let jointocreatedata = await jointocreatemodel.findOne( { guildId: newState.guild.id, userId: member.id } )
let channel = await client.channels.cache.get(jointocreatedata.channelid)
return await member.voice.setChannel(channel)
}
channel = await newState.guild.channels.create(member.user.username+ "'s Room", {
type: 'GUILD_VOICE',
parent: newState.channel.parent,
});
member.voice.setChannel(channel);
voiceCollection.set(member.user.tag, channel.id);
jointocreatedata = await jointocreatemodel.create( { guildId: newState.guild.id, userId: member.id, channelid: channel.id } )
}else if(member.voice.channelId === guilddata.jointocreate && test ){
let targetchannel = await client.channels.cache.get(test.channelid)
return await member.voice.setChannel(targetchannel)
}else if(!newState.channel) {
let jointocreatedata = await jointocreatemodel.findOne( { guildId: newState.guild.id, userId: member.id} )
if(!jointocreatedata) return
if(oldState.id != jointocreatedata.channelid) {
await jointocreatemodel.deleteOne( {guildId: newState.guild.id, userId: member.id } )
let targetchannel = await client.channels.cache.get(jointocreatedata.channelid)
await targetchannel.delete ()
}
}
})
This is my JoinToCreate event code. It works but how could i make it so if the owner of a jtc channel switches to another call it deletes the channel that was created by him?
Is there a way to make a bot join the channel and then start playing a music stream?
I want to make a bot that starts playing the music when someone joins the voice channel. I have made it filter on members and check on the size of members in the channel, but now I only need it to play and stop.
It needs to be in the VoiceStateUpdate event.
??
dispatcher.on('finish', () => {
connection.destroy();
})```
TypeError: connection.play is not a function
full code: https://srcb.in/MqyDjUbNVy
only a player can play something
ur connection is only to the voice channel
create a player and subscribe it to the connection and then play smth
like this?
subscribe before playing with the player (personal advice) off rest everythings perfect
ok its work but how to make it disconnect when player done?
player.on("idle", () => {
player.stop();
connection.destroy();
});
basically when the player isnt playing anything it stops the player at all and destroys the voice connection/// disconnects
https://discordjs.guide/voice/audio-player.html#life-cycle u can use AudioPlayerStatus or just the words themselves tbh
ok tysm
npp
does anyone know how to check if bot is in a voice channel in discord.js v13
AkiArasaki — Today at 10:55 PM
how can I setVolume before playing music in v13?
if(interaction.guild.me.voice.channel) {
// ...
}
async leave(msg) {
//如果机器人在语音频道
if (this.connection[msg.guild.id] && this.connection[msg.guild.id].state.status != "Destroyed") {
//如果机器人播放过歌曲
/*if (this.queue.hasOwnProperty(msg.guild.id)) {
//清空列表
delete this.queue[msg.guild.id];
//将isPlaying设置为false
this.isPlaying[msg.guild.id] = false;
}*/
//离开频道
this.connection[msg.guild.id].destroy();
msg.channel.send({embeds: [
new MessageEmbed()
.setColor('#E74C3C')
.setTitle('ヾ( ̄▽ ̄)Bye~Bye~')
]});
return;
} else {
msg.channel.send({embeds: [
new MessageEmbed()
.setColor('#E74C3C')
.setTitle('I\'m not in any channel')
.setDescription('.help for commands')
]});
}
}
this is my code, but when i make the bot leave again after it leaved channel, it gives an error.
it does not go into the else section
error looks like this
don't make it leave again after it left
hello is this the right way to disconnect a user in djs v13 async function disconnect(userID){
let user = await client.users.fetch(userID)
console.log("Disconnecting " + user)
user.voice.disconnect();
} it doesnt seem to be working
player.on() not working, can someone help me?
when i try to run this
connection.subscribe(player);
player.play(resource);
player.on(AudioPlayerStatus.Playing, () => {
interaction.followUp('playing now!');
});
the player.on() function just doesnt work
Try calling .play() after the .on().
I was trying to make a radio bot and following the example on @discordjs/voice but always get an error
AbortError: The operation was aborted
can someone explain what happen please?
did you use ytdl-core?
no
please im begging
let voiceConnection;
const audioResource=createAudioResource(stream, {inputType: StreamType.Arbitrary, inlineVolume:true});
if (!voiceConnection || voiceConnection?.state.status===VoiceConnectionStatus.Disconnected) {
voiceConnection = joinVoiceChannel({
channelId: message.member.voice.channelId,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator,
selfDeaf: false
});
voiceConnection = await entersState(voiceConnection, VoiceConnectionStatus.Connecting, 5_000);
message.channel.send('Processing text-to-speech');
}
message.channel.send('Waiting');
console.log('AAA');
const audioPlayer=new AudioPlayer();
audioPlayer.play(audioResource);
voiceConnection.subscribe(audioPlayer);
Hi! When i join the voiceChannel with selfDeaf as false i can hear the resource playing, wherease with selfDeaf property not given, i cannot hear the bot play. How can I make the bot play the resource while staying at deafen?
Hey, I keep getting a connResetException after 5-10 mins of playing music through a YT video in my bot, there is no error and it just says connection aborted. Any idea what situations cause this to happen?
rq question <AudioResouce>.playbackDuration is returning 0, any idea why? ping me if u can help 
Error: Cannot play audio as no valid encryption package is installed.
what is the required package ?
when i try to install one of them they don't get installed ! , sodium, libsodium-wrappers, or tweetnacl
Hello
I'm getitng all meta datas and song datas etc.
It all works
but it's not playing any sound in the channel
no matter what i try.
idk why
Do you have the GUILD_VOICE_STATES intent/
Any of the packages mentioned is fine. Tweetnacl should be the easiest to install, if you're having issues installing them it's not related to discord.js.
ya ya i tried sodium but it faild then tried libsodium-wrappers it works fine
Great
oh dont say i forgot it againnnn
thanks : )
thanks dude !
do you know, how i can get a player later?
At any point in your code you can get your connection with getVoiceConnection(). On that object you can use <VoiceConnection>.state.subscription.player as long as that connection is subscribed to the player.
great thanks!
everytime i try to log the player
it's crashing
all i wanna do is, change the resource volume, stop playing etc.
I got the volume change done, by saving the resource in a map
thanks
issue resolved
getting this error everytime the bot is disconnected from a vc
Hi
i have a command that connect bot to mentioned vc but why when i use it give me this err
Thast just showing the multiple resolves, since nodejs v16.9 that is showing either downgrade, or ignore
how can i make <VoiceConnection>.ping.ws not return undefined?
My ytdl Discord bot is still laggy in the voice channel. According to these posts:
https://github.com/fent/node-ytdl-core/issues/405#issuecomment-456410319
https://v12.discordjs.guide/voice/optimisation-and-troubleshooting.html#using-highwatermark
you could set the highWaterMark options like so (one for ytdl and one for discordjs v12):
let dispatcher = queue.connection.playStream(
ytdl(music.url, {filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1<<25 }),
{highWaterMark: 1});
I could not find a way to set the highWaterMark on discordjs v13. How can I do this?
Hello there, I am making a discord music bot and I get this error. (I am using DisTube) the support server says that this is a djs error
Cannot read property 'set' of undefined
at C:\Users\dante\Desktop\OutLand-Source\node_modules\discord.js\src\structures\Guild.js:1388:34
at new G (C:\Users\dante\Desktop\OutLand-Source\node_modules\@discordjs\voice\dist\index.js:8:7254)
at Oe (C:\Users\dante\Desktop\OutLand-Source\node_modules\@discordjs\voice\dist\index.js:8:12358)
at gt (C:\Users\dante\Desktop\OutLand-Source\node_modules\@discordjs\voice\dist\index.js:8:12577)
at DisTubeVoice._DisTubeVoice_join (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\voice\DisTubeVoice.js:246:41)
at DisTubeVoice.set channel [as channel] (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\voice\DisTubeVoice.js:96:106)
at new DisTubeVoice (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\voice\DisTubeVoice.js:39:22)
at DisTubeVoiceManager.create (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\voice\DisTubeVoiceManager.js:36:16)
at QueueManager.create (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\manager\QueueManager.js:37:35)
at DisTube.play (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\DisTube.js:197:60)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Unhandled 'error' event.
See: <link>```
That is the error
Here is my code
```JS
const { Discord, MessageEmbed } = require("discord.js");
const config = require("../../config/emojiConfig.json");
module.exports.run = async (client, message, args) => {
return message.channel.send("You actually thought\nFeature comming soon!");
const { options, member, guild, channel } = message;
const VoiceChannel = member.voice.channel;
const Embed = new MessageEmbed().setColor(config.colors.grey);
if (!VoiceChannel) {
return message.reply({
embeds: [
Embed.setDescription(
`${config.emojis.denied} You must be in a voice channel to use this command.`
).setColor(config.colors.red),
],
});
}
if (guild.me.voiceChannelId && VoiceChannel.id !== guild.me.voiceChannelId) {
return message.reply({
embeds: [
Embed.setDescription(
`${config.emojis.denied} I'm already playing music in <#${guild.me.voice.channelId}>`
).setColor(config.colors.red),
],
});
}
try {
client.distube.play(message.member.voice.channel, args.join(" "), {
textChannel: message.channel,
});
} catch (err) {
return message.channel.send({
embeds: [
Embed.setDescription(`${config.emojis.denied} ${err}`).setColor(
config.colors.red
),
],
});
}
};
module.exports.config = {
name: "play",
aliases: ["p"],
category: "",
displayName: "",
description: "",
usage: "play <query>",
};
not voice related
which djs version are u using?
13
its a music script
doesnt make ur issue voice related
i dont know about the internal workings of distube but seems like no voice adapter was created
could you log client.voice.adapters for me
gimme a sec
Ok
12.5.3 da best
cap
how do you fix those abort errors?
Code: https://github.com/Tomato6966/light-music-bot/blob/main/util/musicUtils.js:137
Thanks in advance
use play-dl instead of ytdl-core if you dont want aborted issue
I'm not using ytdl-core
I'm not using ytdl-core
i am having a custom version self made
on the github not
so i'm trying to fix it
well, you provide the code that had ytdl-core. no clue then
Okay
undefined
what about client.voice
lemme check
here: ```Collection(0) [Map] {}
ok
can you do client.voice.get("id of the guild where youre trying to play audio")
and tell me the result
undefined
just a moment ill check something
thats odd
client.voice shouldnt be a collection
huh
thats client.voice
huh
I made a collection in my index called voice 💀
yeah thats a problem
lemme see if it works now
TypeError: client.voice.get is not a function
remvoe that piece of code i told u to add
I had a temp vc system that had the collection named voice
ic
if thats vital for the operation of ur code and bot ull have to rename it to something else
Hi! I'm trying to stream music from a radio station using discord.js v13. However, I can't find any code that don't use ytdl or local files. Does anyone have a solution?
PS: I tried to create a ressource with the URL but it's not working (and it doesn't output any error).
const resource = createAudioResource(this.streamURL);
this.audioPlayer.play(resource)
The resource needs to be created with either a String of a file path or a Readable. A URL will not work. There are plenty of libraries out there that can get readable streams from URLs.
Okay thanks I'll take a look
is it possible to make the bot say something from a string
sounds like you want a tts package
which is not what we have here, go search npm
Why does this keep happing like 3/4ths through the song?
this new voice library sucks ass ngl idk why it wasnt just left the same
If ur using ytdl-core, that lib is the issue
why was it never an issue before
Recent yt api changes ig?
It's a known issue w/ ytdl-core
You should switch to play-dl instead
hmm
thanks 
@icy maple is there like better instructions on how to use this anywhere cuz like the documentation doesnt even seem to have any functions for playing music just getting info
oh 🧍🏼♂️ im blind
mb
They should have an example w/ d.js
why does it play from the info doe why not just the link 
Wdym? It does take the link
i appear to just be really blind tonight and i suppose its the 3 hours of sleep, thanks for the help
Tho, you could do more stuff w/ the info
tired programmer = useless programmer
A wise Evie once said "A tired programmer is a dumbass programmer"
💀 shes my favorite
i suspect this isnt good
nevermind this library is built by pepegas
The error message is usually more insightful than the code itself
that was the error, but i fixed it already idek what i did tbh
Error: Cannot play audio as no valid encryption package is installed.
- Install sodium, libsodium-wrappers, or tweetnacl.
- Use the generateDependencyReport() function for more information.
can some one give me help
Install one of the listed packages
where are there
My discord bot waits for someone to say something in vc and then replies with a random answer
It is is 1000 servers and starts lagging after like 10 hrs of being online
What's a fix?
My server I run the bot on is a
64gb ram ubuntu server
With 8 cores and 4 TB of storage
try sharding ur bot even with this amount of guilds
let stream = await playdl.stream(args[0], { quality: 1 })
let resource = createAudioResource(stream.stream, {
inputType: stream.type,
inlineVolume: true
})
let player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause
}
})
player?.play(resource)
connection.subscribe(player)
Its laging for some reason and I cant find out why at all. Any advice?
ik i saw that and im doing that now
How would I get all connections active and destory them?
dunno very much about voice, client.voice ig
getVoiceConnections() returns a Map of connections
Just iterate over them and call destroy
thim pretty
im pretty sure they removedd this in discord js 13
as i dont see it on the docs anymore @icy maple
Top-level functions are not shown by the docs
so
client.getVoiceConnections()?
No
It's a top-level function of the voice package
ah ok they should show those
Hopefully in a future version of tsdocs + docsgen
so this should worK?
process.once('SIGINT', async () => {
console.log("I was killed")
getVoiceConnections().forEach(function(connection) {
connection.destroy()
Bot.user.setStatus("invisible")
})
process.exit(0)
})
ok it works
thx
If im running in shards would Bot.guilds.size still work, if not how would I set the activity to the amount of guilds its in
as my bot is in 1k+ servers and im switching to shards
how do i createAudioResource from a url e.g. https://example.com/audio.mp3
How would I detect if my bot is already in a voice channel?
its in 1000 servers
fetchClientValues returns an array, look at the .then() in the guide
i did that rn
setInterval(async () => {
var guilds
await Bot.shard.fetchClientValues('guilds.cache.size')
.then(results => {
Bot.user.setActivity(` ${results.reduce((acc, guildCount) => acc + guildCount, 0)} servers`, {
type: "LISTENING"
});
})
}, 2500);
});
but its still doing it
doing what
still saying 900k servers
that code you just sent will not show 900000 servers unless your bot is in 900000 servers
never lol didnt upload the file changes back to my ubuntu server
xd
Hey, my bot keeps randomly looping, skipping, and stops playing. Is there a list of things that could be going on or that I should look into? It works in test but breaks in prod
I'm using play-dl for the audio
and streaming stuff I uploaded to youtube
AbortError: The operation was aborted
How do I fix this error?
listened music, appeared
const ytdl = require('ytdl-core');
client.on("messageCreate", msg => {
if (msg.content === "test") {
const {
AudioPlayerStatus,
StreamType,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
} = require('@discordjs/voice');
const connection = joinVoiceChannel({
channelId: "960932830337183764",
guildId: "876058982609989654",
adapterCreator: msg.guild.voiceAdapterCreator,
});
const stream = ytdl('https://youtu.be/EP625xQIGzs', { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
const player = createAudioPlayer();
player.play(resource);
connection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => connection.destroy());
}
})```
use play-dl instead of ytdl-core
I can help you in #869652447881207858 if u want
how to get a preview
(await play.video_info("https://youtu.be/EP625xQIGzs")).video_details```
how to get video preview in play-dl
Any advice on that?
how do I make my bot leave automatically after playing music, my code looks like this, but it doesn't work
player.on('AutoPaused', () => {
//如果队列中仍有歌曲
if (this.queue[guildID].length > 0) {
this.playMusic(msg, guildID, this.queue[guildID][0]);
} else {
this.isPlaying = false;
msg.channel.send({embeds: [
new MessageEmbed()
.setColor('#3498DB')
.setTitle('End of queue')
.setDescription('.help for commands')
.setTimestamp()
]});
this.connection.destroy();
}
});
👀.
why? ytdl-core works fine
miniget can be finicky, but really it's a matter of personal preference
im trying make my bot automatically become speaker after joining a stage channel but I get this error:
interaction.guild.me.voice.setSupressed is not a function
pretty sure bots are not allowed to speak in stage channels, but I could be wrong
yeah, also spelt suppressed wrong
setting suppression wouldn't work anyways since you need to request to speak in a stage channel
Error [VOICE_NOT_STAGE_CHANNEL]: You are only allowed to do this in stage channels. - thats on the set suppressed
ah welp. I guess discord.js' interface is ambiguous to someone who doesn't use it
I use to use it a lot back in the days of 1.11 and 1.12 but when 1.13 came out a lot of things puzzled me so i ended up just giving up but need this for a project im working on
got it working in the end, its because the stage channel wasnt started
after playing an audio that is during 10~15 minutes you got an abort error
TypeError: client.voice.onVoiceStateUpdate is not a function
at VoiceStateUpdate.handle (/home/container/node_modules/discord.js/src/client/actions/VoiceStateUpdate.js:29:22)
at Object.module.exports [as VOICE_STATE_UPDATE] (/home/container/node_modules/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js:4:35)
at WebSocketManager.handlePacket (/home/container/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
at WebSocketShard.onPacket (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/container/node_modules/ws/lib/event-target.js:199:18)
at WebSocket.emit (node:events:526:28)
at Receiver.receiverOnMessage (/home/container/node_modules/ws/lib/websocket.js:1137:20)
at Receiver.emit (node:events:526:28)
at Receiver.dataMessage (/home/container/node_modules/ws/lib/receiver.js:528:14) uncaughtException
[Error_Handling] :: Uncaught Exception/Catch```
anyone please help
that is not a thing
are you trying to get the voiceStateUpdate event?
It’s an error within a djs file
They’re probably doing something wrong. Can you send the code of the thing you’re currently working on?
I fixed my self
Oh okay
Thanks
this seems to fail when i install it, here's the log file, any idea what's going on?
how can i use custom ffmpeg arguments for audio resources?
you can
pipe the audio through a prism ffmpeg instance
thank you so
AbortError: The operation was aborted
How do I fix this error?
i've tried to get the bot an event when the user starts listening, but the event is never called ```ts
const connection = await joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
selfDeaf: false,
selfMute: false,
adapterCreator: channel.guild.voiceAdapterCreator,
})
const receiver = connection.receiver
receiver.speaking.on('start', userId => {
console.log('receiver speaker, start', userId)
})```
Hello, I'm currently facing an issue where there are certain songs on YouTube that just stop when I try to play it (as if they have 0 duration). It seems to happen whenever the audioresource uses the oggdemuxer. But when it uses the webmdemuxer, there isn't any issue. Does anyone know why?
EDIT: turns out this was a youtube-dl issue. I tried using play-dl now it works fine.
How to make skip or stop - Music Bot
connection.dispatcher.end() results in TypeError
how to get what user is speaking from
connection.receiver
(cant find any docs)
anyone 1
Is there a way to receive the AudioPlayer object when using getVoiceConnection?
connections.state.subscription.player
Thank you so much!
how to get audio/string (i dont think we can get string without google api) from voice channel receiver?
async execute(interaction) {
const channel = interaction.member.voice.channel;
if(!channel) return interaction.reply("You are not in a voice channel. I can't sing.");
const player = voiceDiscord.createAudioPlayer();
const resource = voiceDiscord.createAudioResource('./pathtofile.mp3');
const connection = voiceDiscord.joinVoiceChannel({
channelId: channel.id,
guildId: interaction.channel.guild.id,
adapterCreator: interaction.channel.guild.voiceAdapterCreator,
});
player.play(resource)
connection.subscribe(player)
player.on(voiceDiscord.AudioPlayerStatus.Idle, () => {
connection.destroy();
})
}
so i got this code, but the bot joins the vc and then instantly leaves, why?
also, even if i remove the connection.destroy part, the bot doesnt play anything.
try subscribing to the player before playing something on the player
lemme try
same thing happens
which same thing
instant leave or nothing playing?
nothing playing
it changed now, sorry
fixed?
no
i meant now it joins, doesnt play anything and never leaves
nvm, it not leaves instantly again
idk why this happens
because player is idle at the start iirc
yeah but if i remove player.on(voiceDiscord.AudioPlayerStatus.Idle, () => { connection.destroy(); })
it still doesnt play anything
so can you tell me how to fix it?
please..
is the bot deafened?
Does the mp3 file exist?
yeah, the bot is deafened
and yeah the mp3 file exists
do selfDeaf: false in join optins
Same error
Well, problem
show new code
One sec
sorry for the wait
const channel = interaction.member.voice.channel;
if(!channel) return interaction.reply("You are not in a voice channel. I can't sing.");
const player = voiceDiscord.createAudioPlayer();
const resource = voiceDiscord.createAudioResource('./filename.mp3');
const connection = voiceDiscord.joinVoiceChannel({
channelId: channel.id,
guildId: interaction.channel.guild.id,
adapterCreator: interaction.channel.guild.voiceAdapterCreator,
selfDeaf: false,
});
connection.subscribe(player)
player.play(resource)
player.on(voiceDiscord.AudioPlayerStatus.Idle, () => {
connection.destroy();
})
}```
remove the connection.destroy() part
ok
joins, and doesnt do anything
and i played the music file, it does indeed work
so @languid quail are you still able to help me?
or anyone
is it undeafened now?
yea
hmmm, idrk what the problem is
You don't have the bot muted or anything from your side, right?
oof
also no i dont
its unmuted, undeafened
Do you have the GUILD_VOICE_STATES intent?
what? you don't need that to join vc and play sound
well yeah i do tho
Voice Guide says otherwise
?
You don't need it to join vc and play sound, you need it to receive events and get updated voice state info
as you can see it's normal so
https://discordjs.guide/voice/voice-connections.html#life-cycle right above the life-cycle
I have it enabled tho
so that isn't the problem
weird, never heard of that
so, how do i solve the problem? or dont i?
I really don't see the problem
off
i added a ready status check
it said it's ready, but no audio was played
try putting the subscribe back below the player.play ¯_(ツ)_/¯
okk
it's already there
:/
@languid quail does this help?
Looks like it played and immediately stopped. Seems like the player has an issue with the mp3 file to me
lemme try another one
what format is the best to test?
maybe mp3 has some issues because ffmpeg
.ogg or .webm to not rely on ffmpeg I guess
what if its because of the bitrate?
discord has a max 64k i think
ffmpeg should resample that on the fly I think
same thing happens
bruh
i got it
somehow
wait it's working now?
yeah
wanna see the code?
👍
basically added this:
let resource = createAudioResource(join(__dirname, 'soldierpoetking.mp3'));
resource = createAudioResource(createReadStream(join(__dirname, 'soldierpoetking.ogg'), {
inputType: StreamType.OggOpus,
}));
player.play(resource);
it worked idk how
Probably didn’t find the file with relative path and needs absolute
probably
Guys can you help me
alright another question, how to check if the bot is alr in a vc? like i made it play the song and all, but if someone in another vc does the command WHILE the bot is in a diff vc, it will leave the first one and get into the second one. How to do this checking?
Not sure if it’s the best way, but I‘d look at guild.me.voice
oh, and that will check if the bot is in the vc, and if it is then wont join. Ty
It‘s a VoiceState object, so you would need to check any of its member properties…
Documentation suggestion for @light basin:
VoiceState
Represents the voice state for a Guild Member.
yeah, ik that, thanks tho 😄
I get this error every time i try to install certain npm packages (enmap and @discordjs/opus), can anyone help? works on my windows pc and i have same npm and node version installed on both
regarding this error, it's a node-gyp problem. you can't do anything for now
i can't seem to get the voice working.
currently, im using this
client.on("ready", async() => {
const channel = client.channels.cache.get("<insert id here>");
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
});
but it doesnt seem to join the voice channel, or throw any errors.
how would i seek local audio files?
dont see a seek option for audioResource
how would set a listener for just someone talking in any connection i have as
(node:1183014) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 start listeners added to [Q]. Use emitter.setMaxListeners() to increase limit
(node:1183014) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 end listeners added to [Q]. Use emitter.setMaxListeners() to increase limit
(node:1183014) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 start listeners added to [Q]. Use emitter.setMaxListeners() to increase limit
(node:1183014) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 end listeners added to [Q]. Use emitter.setMaxListeners() to increase limit
put the id in the place lol
put the id where it says <insert id here>
Do you have voice intent?
Use ffmpeg
You need one listener per Connection.receiver, so I'm afraid it's not possible
this lags my bot and makes too many listeners
That warning says you have 11 listeners on the same object though…
how else would i do this
wanna make it leave after scilence but if a person is speaking to the bot longer than the timeout it will leave
and i want it to leave after a certain amount of scilence
You could do everything in the on end listener below instead of creating a new listener everytime someone starts speaking
You should do that even. Never create more than one listener for any events, only leads to ugly race conditions
You also don’t even check who stopped talking, could be someone else than the one who started speaking. So if Person A starts, B says a short word and A keeps on talking during then person B stopping would end the event for A too…
yes but if they talk for 10 seconds the bot will leave