#archive-voice
30636 messages · Page 12 of 31
This has worked for many users, you should at least try once
how can i use it ?
I was hoping I could get a quick bit of help. I'm new to discord.js and I wanted to make a simple music bot.
const { Client, Intents } = require("discord.js");
const botclient = new Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const { joinVoiceChannel } = require("@discordjs/voice");
const token = `lolnicetry`;
let PREFIX = "-";
botclient.on('ready', () => {
console.log("Bot enabled.");
})
botclient.login(token);
botclient.on('messageCreate', message => {
let args = message.content.substring(PREFIX.length).split(' ');
switch (args[0]) {
case 'play':
let vc = message.member.voice.channel;
console.log(message.member)
console.log(vc);
if (!vc) {
message.channel.send("You must be in a channel to play music!");
return;
}
if (!args[1]) {
message.channel.send("You need to provide a link.");
return;
}
joinVoiceChannel({
channelId: message.member.voice.id,
guildId: message.channel.guild.id,
adapterCreator: message.channel.guild.voiceAdapterCreator
})
break;
}
})
When I execute the command in a voice channel, the bot doesn't connect. Any advice?
@warped sigil
const botclient = new Client({ intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_VOICE_STATES"]});
Apparently that's an invalid bitfield?
Got it!
yeah sorry, i edit it
Still wont connect unfortunately.
and. u must download ytdl-core & @discordjs@voice
I know I eventually will need ytdl-core but I just want it to connect.
It seems it wont
joinVoiceChannel({
channelId: message.member.voice.id,
guildId: message.channel.guild.id,
adapterCreator: message.channel.guild.voiceAdapterCreator
}).subscribe();```
try this
So, do I only need to install FFmpeg and discordjs/voice to make my code for voice from v12 work again?
Of course not. V13 has completely changed how voice works. Read docs - https://discordjs.guide/voice
Cannot read property 'subscribe' of undefined.
I will try something, just some mins
All I want to be able to do is delete voice channels, but it doesn't seem to be working with just discordjs. I don't actually use the bot within voice channels.
What’s your code?
const createAudioResource = require('@discordjs/voice');
const player = createAudioPlayer();
@Mr.Treeman#6969 put this codes.
// Listen for voice state updates
client.on("voiceStateUpdate", (oldState, newState) => {
// Call the channel left handler from the voice controller
voiceController.voiceUpdateHandler(oldState, newState, client);
});
// In another file and within some conditionals
oldState.channel.delete()
and download ffmpeg
.subscribe(player);
You are code is wrong. js joinVoiceChannel({ channelId: message.member.voice.channel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator });
Legend
Thanks for your help aswell!
Along with the above, this:
What are trying to achieve?
Temp channels.
When a user joins it "activates" the channel, then once activated, once all members leave the channel, it auto-deletes.
It worked fine in V12, I'm not sure what is preventing it from deleting now. I'm not getting any errors or anything
I’m not sure about it but did you enable GUILD_VOICE_STATES intent?
Ooooooohhhhh, thanks.
Yea, that fixed it, thanks a lot Muhitrhn!
Anytime
Using play-dl as my downloading import, is it possible to start the audio at a certain timestamp with a video?
I saw some docs use seek in a dictionary in the .play command as a second argument, but in the docs provided by hydrabolt, there is no second argument in .play. I tried it anyway but obviously nothing changed, so...
play-dl is a third party pacage that we don't support; if this question is specific to it we can't answer it here
you can reach out to the maintainer in dms or find its support server
I'm specifically asking if there is a method in which to play the audio resource at a different timestamp. I saw playbackDuration was not read-only and thought that was the solution but no haha. If I can't do it through djs-voice, I'll see if I can find a way to do it with play-dl, but would prefer to do it with the audio being played.
My apologies for not clarifying.
using ffmpeg would work using the seek option
@empty torrent Really quick, when playing an audio like this I only get about 3 seconds before the audio stops, is that anything quick to fix?
const resource = createAudioResource('C:/Users/Clayt/Downloads/firstsong.mp3');
player.play(resource);
connection.subscribe(player)
Do you have ffmpeg installed? Try installing ffmpeg
Thanks, I'll try it out. I already have volume working, I just wasn't sure how to proceed, first time working with ffmpeg and djs voice, a bit overwhelming haha.
Not sure if you're talking to me, but yes.
Where do I find the ‘EndBehaviorType’s for receiving voice?
On ios so i can’t codeblock properly
Yes was talking to you. Code seems okay to me. I can only think of ffmpeg issue as i faced this issue with live streams before and was fixed after installing ffmpeg
Maybe I just need a restart
You can try that.
Apologies for a lot of questions. Regarding ffmpeg, I'm struggling to figure out how I would use it with a stream or audioResource, considering it is typically used for video with some options for audio, and documentation seems light or hard to understand for djs-voice atm.
Do I need to fully save the audio to my computer for ffmpeg to modify it, or am I capable of doing that through djs-voice's provided options like with .inlineVolume and .volume? I assume the former because I couldn't find additional options provided in creating audioResources, including .inlineVolume and .volume on hydrabolt's documentation, I had to find it on https://discordjs.guide, and you wouldn't suggest me use ffmpeg otherwise. It's still good to check however ^^.
you can create a new ffmpeg transcoder with prism-media
and then pipe ur input stream into that
and pass the transcoder into createAudioResource
I'll take a look, thank you again once more. I should also learn streams more completely, to ensure I won't be confused in the future.
can someone help me please ?
https://cdn.discordapp.com/attachments/844185086613258290/880049376184131584/image0.jpg
not a djs voice error
AudioPlayerError ?
thats just how it shows up. The error was actually emitted from ytdl-core
That I believe is an error that happens a lot using ytdl-core, I had less issues when I learned and switched to play-dl myself, if that helps.
its interesting as i barely ever run into that issue when using ytdl-core
Strange, I kept running into it and it would cause issues when playing audio for me, crashing at random times. I suppose I could have set something up wrong, that could very well be the case.
the options you pass in could have an effect
👍
how can i use play-dl ?
Is she working like ytdl ?
like
ytdl("link")
Not particularly, to get a stream from a link you would do
const ytdl = require("play-dl")
ytdl.stream("link")```
there’s nothing like this
I'm not sure what that's meant to mean.
Less issues or no issues ??
No issues, my apologies for the lack of clarity.
Oh big relief
^^ Thanks for checking up on that though!
👍
Just one last question, Is play-dl faster than ytdl-core ??
It claims to be but I wouldn't happen to fully know based off of my testing, since I've been changing so much and my code is pretty inefficient overall haha. Feel free to test though, I'd be glad to know as well!
👍, I will test it
can someone please show me an example of how to create a new connection
hi, umm im having trouble downloading discordjs/opus
const subscription = connection.subscribe(player);
player.play(resource);```
This is how I subscribe the connection, I think this is wrong. How can I subscribe correctly?
how can i get the volume down only having the player?
player.state.resource.volume.setVolumeLogarithmic
Only works if the player is in the middle of playing smth
It looks fine
The bot it's connecting
but not playing
that works in v13?
It’s assuming inlineVolume is enabled and the player is actually playing smth (not idle/destroyed)
Volume is per-resource, doesn’t persist between songs
Are you checking if the connection is actually ready?
nope
Should use the entersState method to make sure the connection actually enters the ready state
Ok, ty
what's this
Also log the Player.stateChange event to see what the player is doing
What are you playing?
Prob lost internet or computer went to sleep
it did not, as soon as i run the command it errors
it errors then it logs the AudioResource i believe
Ur brackets are off I think
You did ytdl(…).videos[0]. …
nope, found the issue
Oh, you got some weird nesting there
the issue was that i didn't specify some options in the second parameter of ytdl-core
I’ve never used that fork. The regular ytdl-core always worked fine for me
okay, thanks anyways
TypeError: Cannot read property 'setVolumeLogarithmic' of undefined
at player.state.resource.volume.setVolumeLogarithmic(args[0] / 100)
There is a player and a song playing
You didn’t enable inlineVolume for the resource
how can i do that
like that?
Yea
Ok thank you
PLZ SOMEONE HELP ME ! I've tried the discord.js guide on how to create a connection, and look through dozens of other websites but every time i try it like this it gives me an error that says "AdapterCreator is not a function" no matter what i declare Adapter function with.
Run this and show me npm ls @discordjs/voice
You forgot to add @
Oh right, mb
What did you define channel here ??
i copied the id of a channel and pasted it there like this "872128266713055275" but i also tried it with message.member.voice.channel.id
Can you show me exact code for joining a voice channel ??
i tried other inputs for adapterCreator too
Type npm ls discord.js
Update it by npm i discord.js@latest
done
@carmine timber im having trouble downloading @discordjs/opus
Error pls and start a new thread
ok
Now try again
Connecting to a voice channel
now it says client_missing_intents
add intents
Since you updated to latest discord.js, so you need to add intents
Make sure to add GUILD_VOICE_STATES intent too
even after adding intents it gives me this
i tried giving it Intents.ALL and GUILD_VOICE_STATES but it just returns this
Show me code where did you defined client
it's in the same file where i write my code
Sorry I gave you wrong docs, mb
https://discordjs.guide/additional-info/changes-in-v13.html#intents
Now change according to this
See the + one
Fixed ??
it fixed that previous error xD, but now i get this
wait 1 sec
i think this is because it misses alot of intents to execute other code, let me just add some more intents
You need >= v16.0.0 for discord.js
how do i get that ?
node version
Update your node.
YOU F*CKING LEGEND !! I posted this question like a dozen times the past days and searched for answers for ever and u finally helped me !! IT WORKS TYYYY, though now my previous code that worked but that was probably outdated doesn't work no more, but thx !
const ffmpeg = require("ffmpeg");
const opusscript = require("opusscript");
const fs = require('fs');
const request = require('request');
const { join } = require('path');
const { createReadStream } = require('fs');
const { joinVoiceChannel, createAudioResource, createAudioPlayer, StreamType, VoiceConnectionStatus, AudioPlayerStatus, entersState } = require('@discordjs/voice');
exports.run = (client, message, args) => {
const player = createAudioPlayer();
const member = message.member;
if (member.voice.channel) {
const channel = member.voice.channel;
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
let resource = createAudioResource(join(__dirname, 'muzica.mp3'));
const subscription = connection.subscribe(player);
player.play(resource);
message.reply('Connected! Playing..');
} else {
message.reply('Nu esti pe canal bedboi');
}
};```
The connection doesn't enter the ready state, and the player, enters the playing state, and then AutoPaused.
The connection doesn't enter any status.
how to play audio in discord.js v13
what intents does your client have
[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS]
there's your problem, one sec
you'll want to add Intents.FLAGS.GUILD_VOICE_STATES
done, ty so much
🙇
hmm why
the interface for playing sound is a bit different now: https://discordjs.guide/voice/audio-player.html#cheat-sheet
oh thanks
Socket.<anonymous>(/home/container/node_modules/@discordjs/voice/dist/networking/VoiceUDPSocket.js:120:52)
Object.onceWrapper (node:events:475:28)
Socket.emit (node:events:381:22)
socketCloseNT (node:dgram:754:8)
processTicksAndRejections (node:internal/process/task_queues:80:21)
UnhandledRejection Error at - Error: Cannot perform IP discovery - socket closed```
Why is it happening and how to Solve ??
Why am I hearing no audio? The bot is joining the channel and it logs in console that the player started
can I export a player from a play.js file, to leave.js file and control it?
do we have an event for audioPlayer for when it stop playing audio?
<AudioPlayer>.on(AudioPlayerStatus.Idle, () => {})
Yeah, btw that is basic js
tnx i got it
Show me code where you defined client in main file
It is a socket issue, just restart the bot or the internet
host issue ?
Might be
means there is no permanent solution ?>
As written, socket is closed. So maybe you need port forwarding
hmm , can't do anything about it
btw , when it happens , bot leave vc from every server at that moment
Thanks I know what to do now I fixed it yay
What fix ??
I added an intent
GUILD_VOICE_STATES intent ??
yeah
Ok good
maybe ask new voice module owner
who is he ?
hydrabolt
Hi, i'm getting the following error and I don't know why...
TypeError: Cannot read property 'set' of undefined
at /Users/MIGI28/vscode-git/opus-bot/node_modules/discord.js/src/structures/Guild.js:1290:34
at new VoiceConnection (/Users/MIGI28/vscode-git/opus-bot/node_modules/@discordjs/voice/dist/VoiceConnection.js:76:25)
at Object.createVoiceConnection (/Users/MIGI28/vscode-git/opus-bot/node_modules/@discordjs/voice/dist/VoiceConnection.js:515:29)
at Object.joinVoiceChannel (/Users/MIGI28/vscode-git/opus-bot/node_modules/@discordjs/voice/dist/joinVoiceChannel.js:18:30)
at Object.module.exports.run (/Users/MIGI28/vscode-git/opus-bot/commands/play.js:58:43)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
play.js:58 is
var connection = client.voice.joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator,
});
Does someone have an idea of what happens?
@zinc wadi you're not supposed to have client.voice.joinVoiceChannel, it's just joinVoiceChannel
var connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator,
});
Problem persists... I have require('@discordjs/voice') declared to client.voice
are u using any partials?
nope
can u show me ur client options?
const client = new Discord.Client({ intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MEMBERS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Discord.Intents.FLAGS.DIRECT_MESSAGES,
Discord.Intents.FLAGS.GUILD_PRESENCES,
Discord.Intents.FLAGS.GUILD_VOICE_STATES
]
});
hmm
looks like an issue within the voiceAdapter
get voiceAdapterCreator() {
return methods => {
this.client.voice.adapters.set(this.id, methods);
return {
sendPayload: data => {
if (this.shard.status !== Status.READY) return false;
this.shard.send(data);
return true;
},
destroy: () => {
this.client.voice.adapters.delete(this.id);
},
};
};
}
the error comes from this.client.voice.adapters.set(this.id, methods);
this is Guild.js:1290
which version of discord.js are u on?
13.1.0
and 0.6.0 for @discordjs/voice
ok i see ur issue
you overwrote client.voice by setting that as require('@discordjs/voice')
true, that's it
thank you
Why tf is this giving me "ffmpeg/avconv" not found whne I clearly hav it
how did u install it?
npm install ffmpeg
thats not the correct thing
• NPM: npm install ffmpeg-static
• Install: Download | chocolatey | homebrew | your distributions package manager
• Tutorial: YouTube
• ffmpeg-binaries is deprecated, uninstall it with npm rm ffmpeg-binaries
oh
I see, lemme try that
Oo, thanks now it works, but it's not giving error and it's failing the interaction
It smth wrong with how I play it
Probably cuz its in a forEach loop, and the player gets overloaded becusse i try to play more than 1 resources at it at the same time
How will I make it wait untill the 1st resource finishes and then make it move on to the 2nd?
Can use like a sleep function or smth? Even for that I need to know the accurate duration of the audio file.
on the old voice system there was a 'finish' event that was fired when the current track ends.
is it removed now? if so what should i use instead?
Readable.once("end", () => ...)
what's Readable?
ReadableStream
whatever you pipe into the lib
I'm using createAudioResource
that returns an AudioResource
and putting it as parameter into player.play method
Okay... but the audio you send into the library should be a ReadableStream
I still don't understand, my current code is
could you link documentation please?
looks like resource.playStream is a Readable
Alternatively, don't pass a string into create audio resource. It's more consistent to just pass in a ReadableStream for everything
Audio player state should switch to idle
Does it need vs 2017 to run?
The recorder
ohh
mh okay
pausing the player switches the state to idle iirc
not just when the resource is ended
This is an example code and I'm confused what this part of the script is for. Why is it multiplying the amount of rejoin attempts by 5 seconds? Why is it 5 rejoin attempts?
how can I disconnect the bot if AudioPlayerStatus.idle?
player.disconnect();
})```
This isn't working
it's Idle not idle
hi there, im relativelly new to djs.13 and after hours of trying to update voice i´ve failed. My bot joins, queqe works, bot is signaling that is speaking (the green circle) but it is totally silent. is there a known bug or something not written in docs ? I have downloaded the examples and also non of them works. I´am currently on windows 10 with node.js 16.8.0
connection.destroy();
connection is the name of your joinVoiceChannel()
could you do this
const { generateDependencyReport } = require('@discordjs/voice');
console.log(generateDependencyReport());
and tell me what it says
If I receive a Buffer from a website that is audio in an unknown format, how can I "convert" or somehow make them into real opus packets?
mp3 file***
that looks like it should work
i don't know
Actually nvm I think I can just pipe it into a stream
im trying to set up a command that just makes my bot join whichever voice channel the user that prompts it is in, but im having trouble reading the guide and i don't know how to set it up exactly:
module.exports = {
name: 'join',
description: 'join',
async execute(message, args){
const Discord = require('discord.js');
const { joinVoiceChannel } = require('@discordjs/voice');
const channel = message.member.voice.channel;
if (channel) {
try {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
} catch (error) {
console.error(error);
}
} else {
message.reply('join a voice channel');
}
}
}
this gives me the error TypeError: adapterCreator is not a function, why is this happening?
can it be something with bot setting on developer portal or invite perrmissions ?
i don't think so
i used to have this problem on an older version of discord.js
i made a mistake when installing the FFmpeg (windows installation)
try message.guild.voiceAdapterCreator
and how should i correctly install it ?
that mistake was before this voice library for discord.js V13
but just follow the guide
worked for me
why doesnt this work?
const {joinVoiceChannel, DiscordGateawayAdapterCreator} = require("@discordjs/voice")
joinVoiceChannel({
channelId: memberIsInVoiceChannel.id,
guildId: message.channel.guild.id,
adapterCreator: DiscordGateawayAdapterCreator,
});
problem: adapterCreator is not a function
You made a typo
I'm once again getting stuck with the voice module... it started throwing https://sourceb.in/nqHePvWA4f this out when trying to play songs
--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.6.0
- prism-media: 1.3.2
Opus Libraries
- @discordjs/opus: 0.5.3
- opusscript: not found
Encryption Libraries
- sodium: not found
- libsodium-wrappers: 0.7.9
- tweetnacl: not found
FFmpeg
- version: 4.4-essentials_build-www.gyan.dev
- libopus: yes
--------------------------------------------------
``` and here are the deps
How do I destroy an AudioResource?
Oh actually, can I just unsubscribe and it would destroy itself, or would that lead to a memory leak?
thanks for this
Oh I can just AudioPlayer.stop()!
Ok so make a new folder and copy and paste your codes there and then do
npm init -y
npm install <all your dependencies>
but but that is now how it's supposed to work...
Actually you had a old file of @discordjs/opus, so doing above just changes it to latest and voice also requires latest file only
but i deleted the file
i uninstalled d.js opus globally it was not in the modules folder anymore and reinstalled it
forced install on 0.6.0 opus and that resolved my problem
👍
That is not how you supposed to get a adapterCreator
https://discordjs.guide/voice/voice-connections.html#creation
Do
npm ls @discordjs/voice
npm ls discord.js
And tell me what you see
This is a late response. However, I don't think Youtube Together would make music bots obsolete, cause Youtube together doesn't work on non desktop clients, in stage channels, or when another activity is being run at this point in time.
just realised i'm still on v12, ill update now
Hello can i by @discord.js/voice get events about connecting disconnecting members
Documentation suggestion for @subtle granite:
(event) Client#voiceStateUpdate
Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
client.on("voiceStateUpdate", async (oldState, newState) => {
Why this isnt working
Maybe you need GUILD_VOICE_STATES intent too.
Anyone?
Yes I had
you can push the resources into an array. After one ends u just play the next one
How will I know the 1st resource ended
you can listen when audioPlayer state changes from playing to idle
@fervent estuary Can you look at this issue ??
so the issue is that the event doesnt fire i assume?
That's smart
Thonku, ima tri
u can also listen for resouce.playStream end event
that should work too
Ohhh
how to leave a voice channel
voiceConnection.destroy()
just likw there is joinVoiceChannel
doesnt work, i tried it
did u get an error or what?
class constructor VoiceConnection cannot be invoked without "new"
if i do that, add new, then it wouldnt leave the channel
can you show the code where youre trying to leave the channel and got this error?
sure just give me a minute or two
https://srcshare.io/?id=6128dfc1d56829e3273998e5 error included
can u show me the full error u got here?
i did
ah yeah got it
mb
where did u add the new
why should i add new if there is a connection
i already tried doing it with new and it didnt work
yes but where did u add that?
before voiceConnection()
here?
either way thats not how ur supposed to get the voiceConnection
require getVoiceConnection call that and then call destroy on the connection that returns (provided that ur client is in a vc)
message.guild.me.voice.channel
Ok bro
connection.receiver.createStream is not a function any help?
Is AudioPlayer.status a string?
console log it
when i do player.unpause() then i get the error The reply to this interaction has already been sent or deferred
so how would i do
player.on(AudioPlayerStatus.Playing, () => {
interaction.reply(`🎶 Now playing\n**${link}**`);
});
without getting that error?
so you want to reply to an interaction twice? Once with the original response, and then later when the player starts playing?
uh good wai
when i do play command it replies with that but if i pause and then i unpause then i want it to either skip sending that message or do something else
maybe something like this?
player.on('stateChange', (oldState, newState) => {
if (oldState.status == "idle" && newState.status == "playing") {
interaction.reply(`🎶 Now playing\n**${link}**`);
}
});
so it only fires when it goes from idle to playing, not from paused
I realized I did it backwards lol, fixed
Ooo this event will help me, thxxx
is there like a place in a guide or just anywhere to help me get started on voice in v13
(I know nothing about voice)
Last link in pins
Nvm
Music Bot question: I'm using YT for music resources but as well all know some videos give a 410 error. I'm able to detect and print the 410 error, however the bot still joins the VC then leaves and prints the error.
player.on('error', error => {
botchannel.send(`Audio Player error ${error.message} due to ${video.title}`)
console.log(`Error ${error.message}`)
});```
is there a better way to detect the error and have the bot do nothing?
Even if all song is finished, somtimes ffmpeg process is not finished. Is there any solution?
AudioPlayerStatus.Idle ?
Hey, guys. How u doin'? What can I do to make my bot join a voice channel with discordjs v13?
if you have a reference to the child process, use ChildProcess.kill("SIGINT");
That ffmpeg is used in voice module, so I don't have any refference about ffmpeg process :(
Then you need to change your code so that you don't pass arbitrary streams to the voice lib and that you pipe all of the arbitrary type streams through ffmpeg yourself and output opus so you can hold the references and kill them later.
Here's some ffmpeg arguments to output as opus :)
thanks
how can i link a youtube stream audio to a voice channel... since vc.join() is not there any more
coudl someone please let me know
Read this - https://discordjs.guide/voice
hello
my bot takes so long to play audio
i will send the logs which indicate every step
you can see there it takes about 10 miliseconds to create the audio resources but takes about 5 seconds to play the resource
my code is basically like this:
const connection = joinVoiceChannel();
const player = await createAudioPlayer();
const subscription = await connection.subscribe(player);
async function play() {
const resource = await createAudioResource(); // takes about 10ms
player.play(resource); // takes about 5 seconds to start playing the resource
}
play(); // this is an async function since it plays multiple audios
this is what require('@discordjs/voice').generateDependencyReport() returns:
Those aren’t async methods tho
Ur awaiting things that don’t return Promises
You have to use entersState to check if the connection actually enters the ready state
@fossil delta
the problem is that the resource is taking long to start playing
sorry, my bad for not clarifying that
how do i know if the bot is speaking in a voice channel-
what type of audio are you playing? From YouTube?
If YouTube, what package are you using for it
no its from google translator
its not the resource's fault, this worked flawlessly with v12
someone-
You can check if bot is in a voice channel by :
(message | interaction).guild.me.voice?.channel
But I don't know how to check if it is speaking
@vocal valley
Have you got time to test play-dl ??
I am waiting for your review.
This weekend I am busy, however I should be free for a few weeks after this weekend
ive never done voice at all and now my friends are forcing me to make a v13 music bot help
Oh okay 👍
will look at finishing up /voice reviews etc. and looking into play-dl next week
👍
please guys i need this badly the guide doesnt help me i dont understand it
Well first of all, you shouldn't be responding to friends that are forcing you to do things. Secondly, there's a guide. https://discordjs.guide/voice
the guides confusing
eh i owe them a lot but 
Well, it shouldn't be if you learnt JS.
i know basic JS
Well then it shouldn't be confusing
eh i'll just pay more attention while im reading everything
can someone PLEASE help me?
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'call',
UserPerms: ["ADMINISTRATOR"],
/**
* @param {Client} client
* @param {Message} message
* @param {String[]} args
*/
run: async (client, message, args) => {
var voiceChannel = message.member.voice.channel;
const joinEmbed = new MessageEmbed()
.setColor('RED')
.setTitle('!call - Error')
.addField(`They didn't pick up...`, `You weren't in a voice channel.`)
if (!voiceChannel) return message.channel.send({embeds: [joinEmbed]});
voiceChannel.join().then(connection => {
const dispatcher = connection.play('./call-center-open.mp3')
const callEmbed = new MessageEmbed()
.setColor('#15EC96')
.setTitle('!call')
.addFields(
{ name: 'Calling', value: 'UrGud Call Center'},
{ name: 'Channel', value: 'Waiting Room'},
{ name: 'Message ID', value: `\`${message.id}\``},
{ name: 'Username', value: `\`${mention.user.username}#${mention.user.discriminator}\``},
)
message.reply({embeds: [callEmbed]})
dispatcher.on("end", end => {
voiceChannel.leave();
});
}).catch(err => console.log(err))
}
}```
here's the error
voiceChannel.join().then(connection => {
^
TypeError: voiceChannel.join is not a function
at Object.run (C:\Users-\Desktop\Bot\commands\Service\call.js:19:22)
at Client.<anonymous> (C:\Users-\Desktop\Bot\events\MessageCreate.js:22:23)
at Client.emit (node:events:394:28)
at MessageCreateAction.handle (C:\Users-\Desktop\Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:23:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users-\Desktop\Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users-\Desktop\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:345:31)
at WebSocketShard.onPacket (C:\Users-\Desktop\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
at WebSocketShard.onMessage (C:\Users-\Desktop\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
at WebSocket.onMessage (C:\Users-\Desktop\Bot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (node:events:394:28)
so i set up my connection variable and i'm just trying to make the bot join. is there like a function or anything i need for that?
joinVoiceChannel
The guide linked above covers that
i use joinVoiceChannel for my connection variable
Then you got the connection correctly
yeah
I would use entersState to wait until it becomes ready or it disconnected
is that for joining?
Yea
so is it like connection.entersState() or how does it work
It’s an exported function from the lib
discordjs.guide results:
• Library: Life cycles
• Library: Life cycle
i dont, understand
When you call joinVoiceChannel, it’ll start trying to connect to the vc (Signalling)
Since the method isn’t async, it will immediately return the connection
If it becomes disconnected next, then the bot is missing perms or the guild voice states intent
Otherwise, it’ll detect that it’s connected to the vc and becomes ready
so I have my connect variable, i just need to call joinVoiceChannel and it'll join?
It’ll try to join
how do I call joinVoiceChannel
discordjs.guide results:
• Library: Voice Connections
Hi, is there a way to set player volume rn?
how i fix?
Woops wrong one @pine rose. It's
https://discordjs.guide/voice/voice-connections.html#creation
ah ok I have to do that now
voiceChannel.join() doesn't exist
also getting "cannot read property 'once' of undefined" errors
trying to get this working with ytdl
@jaunty nova you'll need to update node version too
https://discordjs.guide/additional-info/changes-in-v13.html#before-you-start
oh my bot runs
I'm sure it does
it's just the music part I haven't got working yet, but thanks
Regardless, if you want to use voice, you'll need to update your node version
yeah I did
and install discord voice
yeah ofc
or I wouldn't be getting errors from the npm package
also I found the issue, I was stupid enough to play a non-resource 🤷
thanks
the voiceChannel.join() isn't a function though, wouldn't be getting that from a npm package.
that wasn't me, I replaced that alr
it was Pineapple
oh gotcha. My bad.
um
You're going to have to rewrite your music bot logic from scratch and pull what works out of the old code.
It's not a copy and paste situation from the docs
oh
@pine rose ```
function getVoice(message) {
//verify user is in voice channel
const voiceChannel = message.member.voice.channel;
if (!voiceChannel.isVoice()) {
return message.channel.send(
"You need to be in a voice channel to play music"
);
}
//check for existing connection in guild
const existingConnection = getVoiceConnection(voiceChannel.guild.id);
const connection = existingConnection !== undefined ? existingConnection : joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator,
});
connection.on(VoiceConnectionStatus.Ready, () => {
console.log('The connection has entered the Ready state - ready to play audio!');
});
return connection;
}
This will return the connection
what theeeeeeeeeeeeee
all of that
Then you just need create a player and subscribe the player to the connection
connection is defined, why is it saying not defined?
yeah, it's exactly what I'm doing atm
It's not globally scoped @pine rose
YTDL is being a prick tho
so how i globally scope it?
@pine rose It'll be much easier if you go through the voice docs page by page. None of the code you have there other than the function i send you will work as is.
https://discordjs.guide/voice/voice-connections.html#cheat-sheet
How so
I mean, I'm probably just stupid
I'll look around for a bit first lmao
Only issue i ran into it was i had to update the npm package
whats a subscription?
do i also need audio player?
@pine rose Allows you to use an audio player for different voice connections. i.e. Lounge Channel and Gaming Channel can listen to the same audio source.
tbh I'm just puzzled, what stream format does ytdl return?
@jaunty nova I can't recall. Are you running into an encryption error or are you getting no audio in voice channel ?
I'm kinda just completely clueless as to how to declare the ytdl source in the resource
the docs doesnt show how to play music
since the example in the guide uses file names 🤷
It does. It's a bit general, but all the information you need is there.
@jaunty nova this is what I'm using to load song data when it's ready to be played
function loadSong({ url, title }) {
const resource = createAudioResource(ytdl(url), {
metadata: {
title: title,
url: url
},
})
return resource;
}
@jaunty nova then, player.play(resource);
hmm ok
This is how you pull the url and title
const songInfo = await ytdl.getInfo(url);
I use simple-youtube-api to get those
since I search for songs first, and it's a monoserver bot so no big concerns about ratelimits
Gotcha. Regardless, the loadSong should return what you ned to play on demand. You dont want to build the resources ahead of time.
yeah, the createAudioResource function seems like it'll work fine like that
thanks a lot :)
Np. Just a heads up, you can't reload those audio sources. ex) going to a previous song wont work since the stream is dead. You'll have to reload the audio
yeah I always do that
figured that out when I tried to implement looping
ah. also, you'll want to take advantage of the lifecyle states. Specifically the Idle state for switching songs after one finishes.
will note for the future
currently figuring out why my bot says it isn't in a stage channel when it is, probably because of async tho
How can I prevent my bot from losing connection when no one is in the channel?
Don't think I've ran into that issue unless the bot was developed that way. You sure you're not timing yourself out ?
turns out it wasn't
async
Anyone able to help me solve a problem where my bot disconnects from VC after about 3-4 mins ( seems to be on every song change )
The code for it is here:
https://haste.onlytunes.uk/ohekagicar.js
how to make bot auto disconnect from vc after inactivity and send message that i left vc due to inactivity
<AudioPlayer>#on(AudioPlayerStatus.Idle, () => {
<VoiceConnection>#destroy();
/* your code */
})
you can use setTimeout to add a delay
and message?
put it in /* your code */, depending on the channel etc.
sorry didnt undetood
destroy(guildID) {
const dispatcher = this.get(guildID);
dispatcher?.connection?.destroy();
return this.delete(guildID);
}```
https://cdn.discordapp.com/attachments/869621122352709714/881209500898574356/unknown.png
This is crashing my bot too anyone know why ?
the error is quite self explanatory
ur trying to destroy a voiceConnection that has already been destroyed
Hmm what I do wrong then
literally exactly what i just said
for some reason my bot can join the voice channel but is just playing silence, does anyone know why? (queuem is a map btw) https://pastebin.com/9zBZb167
whenever a certain person joins this vc, i made it where my bot joins and plays a sound, and it works, but it also joins and plays whenever the person mutes or unmutes, how would i fix this?
@outer kraken
.then((probe) => playing = createAudioResource(probe.stream, {inputType: probe.type }));
sQueue.player.play(playing)
sQueue.player.play(resource);```
I don't see where you defined resource in your snippet
ignore sQueue.player.play(resource);, its been removed in the code but is on pastebin
@outer kraken Try this
demuxProbe(stream) .then((probe) => { const playing = createAudioResource(probe.stream, {inputType: probe.type })); sQueue.player.play(playing) }
i only want it to play the sound when the person joins
still just silence
@outer kraken What happens when you do
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
interesting, doesn't every say anything
did you put that near where you create the players?
nevermind
i put sQueue.player.on instead and it puts it in console
try this for your resource
const resource = createAudioResource(ytdl(url), {
metadata: {
title: title,
url: url
},
})
does it need the metadata?
No
can i just have it as const resource = createAudioResource(ytdl(url)) then?
should work
nope, still playing nothing the voice activity circle isn't turning green either
Hm. Try logging the audio resource
what do you mean by that?
how do i make it where a bot detects only when someone joins not if they muted or not
Put a console.log on the resource should look something like this
here
and other half of it
show me the vp function again
const sQueue = queuem.get(guild.id);
if (!song) {
interaction.followUp("something happened")
return;
}
console.log(song)
const stream = ytdl(song,{
o: '-',
q: '',
f: 'bestaudio[ext=webm+acodec=opus+asr=48000]/bestaudio',
r: '100K',
}
)
const resource = createAudioResource(ytdl(song))
console.log(resource);
sQueue.player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
sQueue.player.play(resource);
sQueue.player.on('stateChange', (oldState, newState) => {
if (newState.status === AudioPlayerStatus.Idle && oldState.status !== AudioPlayerStatus.Idle) {
sQueue.songs.shift();
vP(guild, sQueue.songs[0])
}
})
}
async function vP(guild, song) {
const sQueue = queuem.get(guild.id);
console.log('QUEUE:',sQueue, '\n', song);
const resource = createAudioResource(ytdl(song))
sQueue.player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
sQueue.player.play(resource);
}
try running just this
then send me the console
Hii! But I can't understand what's player in this case.
How you define it?
player is refering to an audio player, created using createAudioPlayer and connections subscribe to them to get audio
@outer kraken Can you log this connection._state.subscription
also add this to your connection just to be sure
connection.on(VoiceConnectionStatus.Ready, () => {
console.log('The connection has entered the Ready state - ready to play audio!');
});
doesnt show up in console
Did you make sure to bind it to where you put make the connection ?
i put it here
Try this for your connection
const existingConnection = getVoiceConnection(voiceChannel.guild.id);
queue.connection = existingConnection !== undefined ? existingConnection : joinVoiceChannel({
channelId: voiceChannel.id,
guildId: voiceChannel.guild.id,
adapterCreator: voiceChannel.guild.voiceAdapterCreator,
});
Hmm, okay thanks!
I don't understand exactly what you mean though...
Soo where I can find more info than here https://discordjs.guide/voice/voice-connections.html#cheat-sheet, about how to play music?
Is there any other guide about that?
@outer kraken How's that lookin?
hasnt fixed it tbh
you still don't have any logs on the connection ?
lmao i should probably fix this first
That might be an issue lol
hasn't changed anything
No logs on connection ?
oh yeah there is this, but that was there already
Yeah i meant that the connection was in the ready state
nah
send me ur play function again just to be sure i'm looking at the same thing
console.log(song)
var queue = queuem.get(interaction.guild.id);
if (!queue) {
if ( interaction.member.voice.channel) {
queuem.set(interaction.guild.id,{songs:[],connection:null,player:null});
var queue = queuem.get(interaction.guild.id);
const channel = interaction.member.voice.channel;
const existingConnection = getVoiceConnection(channel.guild.id);
queue.connection = existingConnection !== undefined ? existingConnection : joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
queue.connection.on(VoiceConnectionStatus.Ready, () => {
console.log('The connection has entered the Ready state - ready to play audio!');
});
queue.songs = [song]
queue.player = createAudioPlayer()
queue.connection.subscribe(queue.player)
try {
vP(interaction.guild,queue.songs[0]);
} catch (err) {
console.log(err)
interaction.followUp("an error occured, try again");
}
} else {
await interaction.followUp('join a voice channel');
return;
}
} else {
queue.songs.push(song);
}
};```
You're not getting any other errors in your console ?
nope, just a message saying the audio player has started, no message about the connection being ready
did you import VoiceConnectionStatus
its under { VoiceConnectionStatus, other stuff} = require("discordjs/voice")
gotcha, and you have GUILD_VOICE_STATES in your client?
where abouts?
is there a simple way to troubleshoot "Invalid webhook token" errors? the bot plays music just fine but sometimes 5 - 20 mins into a 1hr song it errors with that^
i have this
try the line i pasted
thanks so much its working now
Great to hear! and np
i forget intents were a thing, gotta love discord api changes
how do i check if someone is speaking
how to make a bot join a voice channel?
how can i set the volume of bot in VC
How can i play mp3 file form url?
still having invalid webhook token issues, especially on song end. any docs or resources i can take a look at to research?
Depends on the audio source. https://discordjs.guide/voice/audio-resources.html#cheat-sheet
its from file
I want from url (.mp3, for example radio https://icecast8.play.cz/kisspublikum128.mp3)
From file has an example on the cheat sheet posted above
Still depends on the audio source
async function probeAndCreateResource(readableStream) {
const { stream, type } = await demuxProbe(readableStream);
return createAudioResource(stream, { inputType: type });
}
const resource = await robeAndCreateResource(createReadStream("https://icecast8.play.cz/kisspublikum128.mp3"));
player.play(resource);
something like that
okay
my message went up and nobody helped me, please read
The bot joins the channel but doesn't switch into Ready mode. I cannot figure out why.
// Create Audio Player
const player = createAudioPlayer();
// Create Connection
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator
})
connection.on('error', err => { console.log(err); })
connection.on('stateChange', (oldState, newState) => {
console.log(`Connection transitioned from ${oldState.status} to ${newState.status}`);
});
player.on('stateChange', (oldState, newState) => {
console.log(`Audio player transitioned from ${oldState.status} to ${newState.status}`);
});
// Play song
let audioResource = createAudioResource('./song.mp3');
player.play(audioResource);
// Subscribe to my channel
connection.subscribe(player);
Created following the upgrade guide on the documentation
createReadStream is through the fs. If you want a stream from the internet, use the built in http lib. If it's an icecast/shoutcast server and you get an http parse error, use the icy npm module which mimics the built in http lib
Dabs in sad boi
how to selfDeaf in discord js v13
pass selfDeaf as true in the options when connecting to a channel
also its enabled by default
@rancid blaze please do not use slurs
hello, i am trying to make a bot join a voice channel and play an mp3 file. It successfully joins the channel, but then nothing happens. no audio is played. js DiscordVoice.joinVoiceChannel({ channelId: message.member.voice.channel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator }) const player = DiscordVoice.createAudioPlayer() const resource = DiscordVoice.createAudioResource('../../hello.mp3') player.play(resource)
did you suscribe to the channel?
connection.subscribe(player);
store the joinVoiceChannel() result into a variable and then call the suscribe() method on it
i just added that and it still doesnt work
can someone please help me with this?
try adding console.log() to each line and see if there are any errors
also, try listening to the player's events: Buffering, Playing, Playing
ready occured, but playing didnt
what the hell is even that?
what is bot.queue.get()
check if the queue exists? thats not a djs voice issue?
are you sure there arent any errors?
thats still not a djs voice error, its an error in your code
it console logs things at the end fine, no errors appear in the console
then what are you doing here? XD
debug your code correctly and you will find the error
the on ready event works
are you sure that whatever you're trying to play is actually playable?
im just trying to play this
XD
check if the resource is not null
logs this
hmm
can you run require('@discordjs/voice').generateDependencyReport()?
just paste it in the code and run it?
done that
--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.6.0
- prism-media: 1.3.2
Opus Libraries
- @discordjs/opus: 0.5.3
- opusscript: not found
Encryption Libraries
- sodium: not found
- libsodium-wrappers: not found
- tweetnacl: 0.14.5
FFmpeg
- version: N-101991-gc8fb68ec52-glq
- libopus: yes
--------------------------------------------------```
@fossil delta am I missing one i need
what is that ffmpeg version??
custom compiled version
oh i see
adds fixes for gifs so that they work better in discord
@fossil delta if i print the state every time it updates, it does this
This error occurs while playing music
node:events:371
throw er; // Unhandled 'error' event
^
AudioPlayerError: Status code: 403
at ClientRequest.<anonymous> (/Users/user/Documents/PositronDEV/node_modules/miniget/dist/index.js:210:27)
at Object.onceWrapper (node:events:514:26)
at ClientRequest.emit (node:events:394:28)
at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:621:27)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
at TLSSocket.socketOnData (node:_http_client:487:22)
at TLSSocket.emit (node:events:394:28)
at addChunk (node:internal/streams/readable:312:12)
at readableAddChunk (node:internal/streams/readable:287:9)
at TLSSocket.Readable.push (node:internal/streams/readable:226:10)
Emitted 'error' event on AudioPlayer instance at:
at OggDemuxer.onStreamError (/Users/user/Documents/PositronDEV/node_modules/@discordjs/voice/dist/audio/AudioPlayer.js:213:22)
at Object.onceWrapper (node:events:514:26)
at OggDemuxer.emit (node:events:406:35)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
This is the code:
const Voice = require('@discordjs/voice');
const ytdl = require('ytdl-core')
const ytSearch = require('yt-search')
const { generateDependencyReport } = require('@discordjs/voice');
console.log(generateDependencyReport());
const cmdArray = [
"play", "leave"
]
client.on("messageCreate", async (msg) => {
x = msg.content.split(" ")
if (msg.author.bot || msg.content.split(" ")[0] != prefix) return
if (!cmdArray.includes(x[1])) return
const { channel } = msg.member.voice;
if (!channel) return msg.reply("You need to join a voice channel")
const VoiceConnection = Voice.joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
if (x[1] == "play") {
if (x.length > 2) {
try{
const player = Voice.createAudioPlayer();
VoiceConnection.subscribe(player)
const videoFinder = async (query) => {
const videoResult = await ytSearch(query)
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null
}
args = x.splice(2, x.length);
console.log(args)
const video = await videoFinder(args.join(' '))
if (video) {
const stream = ytdl(video.url, { filter: 'audioonly' })
const resource = Voice.createAudioResource(stream);
player.play(resource);
await msg.reply(`Now Playing: ${video.title}`)
}
else {
msg.reply("No video Results found")
}
}
catch(e){
console.log(e)
}
}
else {
msg.reply("Please send a song request as the second argument.")
}
}
else if (x[1] == "leave") {
VoiceConnection.destroy();
}
})
That’s related to ytdl-core, has nothing to do with djs-voice
ok thanks
@bronze swan
Can someone explain what this piece of code does?
I'm currently trying to implement ytdl-core, getting the audio stream playing a song from url.
let stream = ytdl(song.url, {
filter: "audioonly"
});
console.log(stream);
song_queue.audio_player.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
song_queue.text_channel.send(`🎶 Now playing **${song.title}**`)
I'm currently getting this error, anyone know why?
E:\Discord Bots\Funky\node_modules\@discordjs\voice\dist\audio\AudioPlayer.js:221
resource.playStream.once('error', onStreamError);
^
TypeError: Cannot read property 'once' of undefined
at AudioPlayer.play (E:\Discord Bots\Funky\node_modules\@discordjs\voice\dist\audio\AudioPlayer.js:221:29)
at video_player (E:\Discord Bots\Funky\music.js:107:29)
at musicPlay (E:\Discord Bots\Funky\music.js:74:17)
at Client.<anonymous> (E:\Discord Bots\Funky\index.js:98:13)
at Client.emit (node:events:394:28)
at MessageCreateAction.handle (E:\Discord Bots\Funky\node_modules\discord.js\src\client\actions\MessageCreate.js:23:14)
at Object.module.exports [as MESSAGE_CREATE] (E:\Discord Bots\Funky\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (E:\Discord Bots\Funky\node_modules\discord.js\src\client\websocket\WebSocketManager.js:345:31)
at WebSocketShard.onPacket (E:\Discord Bots\Funky\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
at WebSocketShard.onMessage (E:\Discord Bots\Funky\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
The stream itself appears to be an object, as it returns information when I log it to the console.
I am getting the error Aborted everytime
Any tips on catching Miniget errors? Currently I’m able to catch them via audioplayer.on error. But that’s after the bot attempts to play the YouTube search…
Usual errors are 410’s
If you are getting miniget errors, switch to play-dl [ Best Recommendation ]
Switch to play-dl [ Best Recommendation ]
You need to createAudioResource first like this :
https://discordjs.guide/voice/audio-player.html#playing-audio
Just pass the stream into createAudioResource
This code just creates a youtube-dl process and checks if the process started or not.
Then it will check type of youtube-dl data that is given to us and finally create a audio resource
It depends upon what type of resource you are playing.
For example, If I play a unknow type of stream, then voice module will change it to ogg using ffmpeg and then pass this to OGG demuxer and then it will play.
Your pipeline is taking time, nothing else
It is recommended to pass inputType while creating a opus, webm-opus, ogg streams since they will be requiring a demuxer and will take less time to play.
For more info : https://discordjs.guide/voice/audio-resources.html#playing-opus-streams
It occurs because ytdl-core, nothing we could do for that
@empty torrent au
I stopped using ytdl-core, in your case discord-player because of this error.
const ytdl = require('ytdl-core');
const {
AudioPlayerStatus,
StreamType,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
} = require('@discordjs/voice');
const { SlashCommandBuilder } = require('@discordjs/builders');
const Discord = require('discord.js');
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
});
trying out joining a voice chat with the code in the guide, but it gives me this error
D:\rustl\Documents\plazmicbot\commands\play.js:13
channelId: voiceChannel.id,
^
ReferenceError: voiceChannel is not defined
it doesn't say anywhere in the guide how to define it
nvm i didn't include the const { clientId, guildId, token } = require('./config.json'); if that's causing it
You have to get the voice channel of the user who used the slash-command (if he is in one) and pass it to channelId: , also same for guildId:
thanks, but im getting this error now whenever i try to play a youtube link:
Error: Cannot play a resource that has already ended.
at AudioPlayer.play (D:\rustl\Documents\plazmicbot\node_modules\@discordjs\voice\dist\audio\AudioPlayer.js:194:19)
at Object.execute (D:\rustl\Documents\plazmicbot\commands\play.js:30:16)
at Client.<anonymous> (D:\rustl\Documents\plazmicbot\index.js:153:17)
at Client.emit (node:events:394:28)
at InteractionCreateAction.handle (D:\rustl\Documents\plazmicbot\node_modules\discord.js\src\client\actions\InteractionCreate.js:66:12)
at Object.module.exports [as INTERACTION_CREATE] (D:\rustl\Documents\plazmicbot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (D:\rustl\Documents\plazmicbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:345:31)
at WebSocketShard.onPacket (D:\rustl\Documents\plazmicbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
at WebSocketShard.onMessage (D:\rustl\Documents\plazmicbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
at WebSocket.onMessage (D:\rustl\Documents\plazmicbot\node_modules\ws\lib\event-target.js:132:16)
ill send the rest of the code in the next message
const ytdl = require('ytdl-core');
const {
AudioPlayerStatus,
StreamType,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
} = require('@discordjs/voice');
const { SlashCommandBuilder } = require('@discordjs/builders');
const Discord = require('discord.js');
const stream = ytdl('youtube link', { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
const player = createAudioPlayer();
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('stupid music'),
async execute(interaction) {
voiceChannel = interaction.member.voice.channel;
guild = interaction.member.guild;
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
});
player.play(resource);
connection.subscribe(player);
player.once(AudioPlayerStatus.Idle, () => connection.destroy());
},
};
this is pretty much just copied from the guide so i don't know what i could've done wrong here
How u guyz code?
Please use bin for sharing large codes. And i guess that’s an ytdl-core issue.
Oh I see the issue, You are trying to create a audio resource at start of bot. So this will work only once. Then It will give you this error. Since you already played that resource.
Not a ytdl-core issue.
so do i move the const connection outside of the module.exports? or do i have to do something else
Move this code inside execute function :
const stream = ytdl('youtube link', { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
const player = createAudioPlayer();
My bad
Is this a ytdl error? , it says the error is emitted from @discordjs/voice.
Thats and ytdl-core error
It just gets forwarded from the resource over to the audioPlayer and then comes out as an audioPlayerError
ok thanks
Hey I am pretty new to discord.js can anyone help out with what are some good audio library for discordjs
And I have been exploring erela.js can anyone tell me if I can play mp3 files with it or not
Sometimes I get this error just after subscribing to an audio player and it crashes the process
throw new ERR_SOCKET_DGRAM_NOT_RUNNING();
Error [ERR_SOCKET_DGRAM_NOT_RUNNING]: Not running```
originating from https://github.com/discordjs/voice/blob/f1869a9af5a44ec9a4f52c2dd282352b1521427d/src/networking/VoiceUDPSocket.ts#L152
Does anyone know why it's happening?
Hello, how do I install the sodium package?
I get this error when installing
You have to install libtool on your system
Okay but how?
sudo apt install libtool if you're on ubuntu, otherwise google is your friend
Okay thanks :) (im on ubuntu lol)
It is not able to create a UDP socket so it creates this error
Bruh after installing libtool I have the same error
Install libsodium-wrappers, much easy to install
Okay
Ty :)
You're probably missing something else too. sodium is better for performance tho
Yes but what
show us the new error
Does the UDP socket get created after subscribing to a player or when joining a channel?
ah yes, you're missing autoconf too sudo apt install autoconf
UDP socket is basically required for sending audio data to a url
So it is created during joiningVoiceChannel creation
Okay
It works thanks!
I made sure that the connection is already in the ready state before creating the player, I think that's not the case..
how would i get my bot to join voice channel id on ready? for my music bot
client.on("ready", () => {
const channel = client.channels.cache.get("ChannelID");
if (!channel) return console.error("The channel does not exist!");
channel.join().then(connection => {
// Yay, it worked!
console.log("Successfully connected.");
}).catch(e => {
// Oh no, it errored! Let's log it to console :slight_smile:
console.error(e);
});
});
This seems to work but the bot joins the voice channel but cannot play music
this channel is for v13. Please move over to #archive-djs-v12-voice-deprecated with v12 questions
Hey, im trying to use player.on(AudioPlayerStatus.Idle, () => {
but audioplayerstatus is undefined, from where do i need to define it
you need to require/import it from discordjs/voice
ok
how is this connection.dispatcher.streamTime now?
nvm it's player.state.playbackDuration
so how can you seek a stream now?
and also change the volume?
set inlineVolume to true when creating the audioResource. Then you can use resouce.volume.<whatever method you used in v12)
yup already found about the volume
for seeking
you can create ur own ffmpeg transcoder
and then spawn it with the seek argument
how can I do that
const { SlashCommandBuilder } = require('@discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Play mp3 file'),
async execute(interaction) {
channel = interaction.member.voice.channel;
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const resource = createAudioResource('../test.mp3');
player.play(resource);
connection.subscribe(player);
await interaction.reply(`Bot is in the house!`);
},
};``` Bot does join the channel but it doenst play any sound, pls help 😄
you need to subscribe the player
still doesnt work...
how did you do it
i edited it
any error in the console?
nope
You need to put subscribe after the play ig
still doenst work
let vc = interaction.member.voice.channel;
if(!vc){
return interaction.reply({ content: "Please join a voice chat first", ephemeral: true });
}else{
const connection = joinVoiceChannel({
channelId: vc.id,
guildId: vc.guild.id,
adapterCreator: vc.guild.voiceAdapterCreator,
});
}``` it says please join a voice chat even if I am already in a vocal chat
const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
module.exports = {
data: new SlashCommandBuilder()
.setName('test')
.setDescription('This is a command for testing'),
async execute(interaction) {
await interaction.reply('Loading Data');
const channel = interaction.member.voice.channel;
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer({});
const resource = createAudioResource('../music/song.mp3');
const subscription = connection.subscribe(player);
subscription.play(resource);
},
};
``` i have no errors but after my bot joins the voice channel it does not play music
oh i do get error i get this: ```Error: FFmpeg/avconv not found!
at Function.getInfo (D:\Programing\Discordbots\Danzr\node_modules\prism-media\src\core\FFmpeg.js:143:11)
at Function.create (D:\Programing\Discordbots\Danzr\node_modules\prism-media\src\core\FFmpeg.js:156:38)
at new FFmpeg (D:\Programing\Discordbots\Danzr\node_modules\prism-media\src\core\FFmpeg.js:45:27)
at Object.transformer (D:\Programing\Discordbots\Danzr\node_modules@discordjs\voice\dist\audio\TransformerGraph.js:144:29)
at D:\Programing\Discordbots\Danzr\node_modules@discordjs\voice\dist\audio\AudioResource.js:156:60
at Array.map (<anonymous>)
at createAudioResource (D:\Programing\Discordbots\Danzr\node_modules@discordjs\voice\dist\audio\AudioResource.js:156:41)
at Object.execute (D:\Programing\Discordbots\Danzr\commands\test.js:19:20)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Client.<anonymous> (D:\Programing\Discordbots\Danzr\index.js:27:3)
D:\Programing\Discordbots\Danzr\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89
if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
^
Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
at CommandInteraction.reply (D:\Programing\Discordbots\Danzr\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89:46)
at Client.<anonymous> (D:\Programing\Discordbots\Danzr\index.js:31:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}
• NPM: npm install ffmpeg-static
• Install: Download | chocolatey | homebrew | your distributions package manager
• Tutorial: YouTube
• ffmpeg-binaries is deprecated, uninstall it with npm rm ffmpeg-binaries
thanks that worked, but now i dont get errors but it still does not work
i added this player.on(AudioPlayerStatus.Playing, () => { console.log('The audio player has started playing!'); });
now it prints in console that the audioplayer is playing but the bot itself does not produce any sound
thank you so much!
the file im trying to play is a mp3 from an internet URL
hello, i am trying to make a command so my bot can play music but i get no errors but there is no sound comming out of the bot, this is the code: ```const { SlashCommandBuilder } = require('@discordjs/builders');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice');
module.exports = {
data: new SlashCommandBuilder()
.setName('test')
.setDescription('This is a command for testing'),
async execute(interaction) {
await interaction.reply('Loading Data');
const channel = interaction.member.voice.channel;
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer({});
const resource = createAudioResource('D:/Programing/Discordbots/Danzr/music/song.mp3');
connection.subscribe(player);
player.play(resource, channel);
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
player.on('error', error => {
console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`);
});
},
};
Hello, does <AudioPlayer>.end() exist?
if i print the audioresource i get this: https://pastebin.com/YiwNCEJB
Don't think so🤔 either unsubscribe() or check for idle status depends on what you mean with end()
In the past, we had <StreamDispatcher>.end()
Hey guys, are there streamoptions available for this new discord audio player? Before we could specify a seek time and a volume, like this:
var streamOptions = {
seek: 0,
volume: 1
};
This new v13 audio player is not even documented. Seems inferior to the v12 version
Documentation just for you
But the end method wasnt on the old documentation
The end() is for skipping the actual music
const connection = await message.member.voice.channel.join();
const receiver = connection.receiver.createStream(message.member, {
mode: "pcm",
end: "silence"
});
const writer = receiver.pipe(fs.createWriteStream(`./recorded-${message.author.id}.pcm`));
writer.on("finish", () => {
message.member.voice.channel.leave();
message.channel.send("Finished writing audio");
});
how to change the end receiver? like end the record with a command or just say stop?
I'm on prism-media's documentation and I don't see anything about seeking (https://amishshah.github.io/prism-media/?api). How would we create our own ffmpeg encoder stream with the seek argument?
someone posted a seek example they got to work in the issue tracker on voice repo
can anyone explain why the music-bot example is using import? im kinda confused
I can't remember the issue they posted it on exactly
ok thank you sir, I'll take a look 🙏
someone? 😄
it's typescript syntax
@dusk hawk that's v12 voice, use #archive-djs-v12-voice-deprecated
Hey hydra, any thoughts on this?
was this it? I'm having trouble finding it: https://github.com/discordjs/voice/issues/168
@fading palm
cheers bro, you're a blessing
not sure from the top of my head, could you make a ticket on the issue tracker
If u found a fix send it me I have same issue
Does joinVoiceConnection return a Promise ?
Because I get this error: TypeError: connection.suscribe is not a function
No
Show code
Oh wait, you misspelled subscribe
suscribe, lol
F
i need help with a small thing, do u guys know how to do the command !join for a music bot?
Use the joinVoiceChannel function from the voice package
Hi, I'm trying to make my bot connect to a voice channel. I read the new guide (https://discordjs.guide/voice/voice-connections.html) and created this code:
const Discord = require("discord.js");
const client = new Discord.Client();
const { joinVoiceChannel } = require("@discordjs/voice");
client.on("message", message => {
if(message.content === "!join") {
var connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.channel.guild.voiceAdapterCreator
})
}
})
client.login(<MY_TOKEN>);
It ends with this error:
/node_modules/@discordjs/voice/dist/VoiceConnection.js:76
const adapter = adapterCreator({
^
TypeError: adapterCreator is not a function
at new VoiceConnection (/node_modules/@discordjs/voice/dist/VoiceConnection.js:76:25)
at Object.createVoiceConnection (/node_modules/@discordjs/voice/dist/VoiceConnection.js:515:29)
at joinVoiceChannel (/node_modules/@discordjs/voice/dist/joinVoiceChannel.js:18:30)
at Client.<anonymous> (/index.js:7:9)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
What am I doing wrong?
discordjs.guide results:
• Library: Voice Connections
i need help with a small thing, do u guys know how to do the command !join for a music bot?
which voice package?
The one owned by discordjs
@discordjs/voice
Thanks for your help, it "works"
not finding it
Can you check ur d.js version?
im kind of new thats why im a bit slow
Did you look at the guide I linked earlier?
It's version 13.1.0
Can you try logging the <Guild>.voiceAdapterCreator
where can I find the docs for the voice library?
When using console.log(message.channel.guild.voiceAdapterCreator); it logs undefined.
Reinstall djs using npm rm discord.js and npm i discord.js@latest
thanks
This is the guide not the documentation
Oh mb, sorry I misunderstood
Hi, what do miniget error 410 gone errors thrown by players mean in this package?
Reinstalled and now it ends with this error:
const token = this.client.token ?? this.client.accessToken;
^
SyntaxError: Unexpected token '?'```
I changed nothing, same code, same token.
that error is forwarded from ytdl-core
oh
is that just when ytdl-core's source errors out (e.g. 403)?
yes
Update nodejs to v16.6+
it just shows up as an audioPlayerError due to the reason @discordjs/voice is built
alright thanks a lot
also any better alternatives than ytdl-core you can recommend for djsvoice?
youtube-dl possibly
the non-depreciated package right? (the one in the guide example)
if so I'll go look at it and see what I can do
yes thats the one
the one the examples use
ah ok good
hey Matte, you said this before when I asked about seeking:
for seeking you can create ur own ffmpeg transcoder and then spawn it with the seek argument
but how can I do this?
heres an example
#archive-voice message
Is it possible to destroy an AudioPlayer ?
audioPlayer#stop()
thanks, so if I'm using a stream from ytdl-core I should use pipe() right?
ytdl returns a readable stream so in that case you would pipe stream to that and pass the result to createAudioResouce()
something like ytldStream.pipe(stream) right?
yes
ok thank you
I have seen that the player will become in his Idle phase and not completly destroyed
well thats the best solution for "destroying" the player that i can think of
Okay
no i still have no fix, so if anyone else has an idea to why this does not work please tell me
@chrome junco idk if that can help you but you don't have to specify a channel when you <AudioPlayer>.play()
i know but it didn' t work when i did not specify the channel so i tested it also with specifieng it no difference
Hm
Sorry but for me everything is fine with your code
yea that is what i was thinking too but it still does not seem to be working. and other people have the same problem or am i the only one?
hmm, this seems to happen sometimes during a song
Hey, i upgraded to discord JS v13 and i ve got a problem.
I am trying to figure out how to make the following code work in the new version:
const { Client, Intents, MessageEmbed } = require('discord.js');
global.client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on("voiceStateUpdate", function(oldMember, newMember) {
console.log(`a user changes voice state`);
});
client.login(token);
I know that i need the discordJS/voice thing but idk how to use it xD
What is this error? AudioPlayerError: write EPIPE
nevermind I didnt have ffmpeg-static installed
Is there a way to get a voice connection's subscription? I'm trying to make a check for if the bot is moved to allow it to resubscribe to a vc which I presume is necessary.
If not I can definitely do a workaround
Which youtube module is best for discord bot to play the music?
has anyone made this work with ytdl-core without the need of saving the file first?
It works fine for me
I don’t do anything special. Just createAudioResource(ytdl(…)) then play it on the Player
eew okay thank you, I was trying to add some meta data at the same time and wasn't working
now it works with only including the ytdl function
It doesn’t work when you include meta data?
no
how would i force a bot to leave all voice channels when it starts running (if it ended while in a voice channel and didnt leave)
You can’t
You have to destroy the connections before the bot shuts down
it works now, I need sleep. I like added after it by just doing ressource.metadata =, then tried again... I just closed the ) at the wrong place. I thought it was because of ytdl-core, but it was the freaking )
Hello, what is the advantage of using demuxProbe in discordjs/voice?
what does socket hang up mean?
using play-dl for music now.. liking it alot better. whats the best way to catch "Error: While getting info from url
Sign in to confirm your age"
Try and catch error. Best way to determine whether url is invalid or any other errors
Or simple do this
youtube.stream(...).catch((error) => {
//Error occured
})
thanks, typical overthinking at it's best
was trying to deconstruct the error from the Extractor util -.-
XD
It just tells the type of probe. Helpful if you don't know the type of stream
I personally think play-dl.
You need one more intent GUILD_VOICE_STATES.
Ytdl-core issue.
thanks
👍
What's the typical approach for playing Spotify playlists/songs? Finding the name from the Spotify link and then searching on youtube?
whats a good js library for doing youtube searches for videos?
I think you need Youtube API for that
There is documentations for discord.js
https://discordjs.guide/voice/#installation
The link is
Thats the guide
Not official ones. U will most likely be able to find unofficial ones tho
How do i make the music bot join a channel when i type !join?
@lime bough ^^^^^
The first one “joinVoiceChannel”?
Cuz I don’t see any command for that like !join
Yes, you have to put that code in !join command execution.
Can you please show me how cuz I’m kinda new to this
I just need to make the !join command and then I’m fully done
#rules 2 and 5
That should be easy as making a new command file and adding validations and the code. Shouldn’t be that hard if you already have commands. Just copy paste and modify them
I have a command for “disconnect” but what should I change or “modify” it to so I can get the command !join
Is it possible to stream files from Google Drive?
Hey can anyone tell me how to get a position of the current playing stream and how to seek using discordjs Voice ?
if it is a public file you can read mp3 files from an url
v13 record
error?
You added the intent GUILD_VOICE_STATES?
in your client
someone can't teach me how to make bot music ?
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice');
module.exports = {
data: new SlashCommandBuilder()
.setName('test')
.setDescription('This is a command for testing'),
async execute(interaction) {
await interaction.reply('Loading Data');
const channel = interaction.member.voice.channel;
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer({});
const resource = createAudioResource('../music/song.mp3');
connection.subscribe(player);
player.play(resource);
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
player.on('error', error => {
console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`);
});
},
};``` Does somebody know what is wrong with my code, it gives no errors it even prints: ' The audio player has started playing!' . But no sound is comming out of the bot
no:
const Discord = require('discord.js');
Intents = Discord.Intents;
const client = new Client({ intents: [Intents.FLAGS.GUILD_VOICE_STATES]});
try this
const Discord = require('discord.js');
Intents = Discord.Intents;
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILD_VOICE_STATES], disableeveryone: true});
try this
an error?
yes
euhhh idk sorry
Above everything else, you need GUILDS, GUILD_MESSAGES and GUILD_VOICE_STATES intents. Enable those and try again with your code.
Yes, add GUILDS, GUILD_MESSAGES also
1 sec
yep not workin
Can you add GUILD_MEMBERS and enable privileged intents also from dev portal?
Not sure but that’s the last thing i can think of
ok lemme see
this not workin either
Any error or anything?
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Play music'),
async execute(interaction) {
const { createAudioResource, createAudioPlayer, joinVoiceChannel } = require('@discordjs/voice');
const ytdl = require("ytdl-core");
channel = interaction.member.voice.channel;
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channelId,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const stream = ytdl('https://www.youtube.com/watch?v=hFPMDH0TwFg', { filter: 'audioonly' })
const player = createAudioPlayer();
var resource = createAudioResource(stream);
player.play(resource);
connection.subscribe(player);
await interaction.reply(`Track duration: ${stream.readableLength} s`);
},
};``` Can somebody help me with this, it joins the channel, no errors, but doenst play anything
does someone have a working music bot that i can borrow to see if the problem is on my pc or not?
my music bot using ytdl is just randomly aborting for no apparent reason. how can i prevent this?
You need to switch to better package than ytdl-core
i tried play-dl but i didnt really understand what was going on and there isn't much documentation
Go for play-dl, it has pre built examples to test it
ye i used that before and got something functional working, ill just try to go with that thanks
Ok no issues 👍
Show me code where you defined client in main file.
thanks, it works now!
thanks
thank you so much i found out i had a problem in my index.js and now it is fixed
👍
Thanks
.then(connection => console.log('Connected!'))
.catch(console.error);```why?
``` joinVoiceChannel.join()
^
TypeError: Cannot read property 'join' of undefined```

does somebody know how to disconnect a bot from a voice channel
this is discordjs v12 and not v13
else if (command === 'vc'){
const member = message.member;
const channel = member.voice.channel;
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
}```const connection = joinVoiceChannel({
^
TypeError: joinVoiceChannel is not a function
Hi!
There is any way I can listen for the user talking event?
I don't want to listen to mute or unmute event, I want the talking event. I found the old event, but I think it is deprecated (guildMemberSpeaking)
Thank you!
Are you on v13? Did you import voice?
Did you require* it in your bot?
yes
joinVoiceChannel
ahhh what's this?
some one help
client.on('voiceStateUpdate', (oldChannel, newChannel) => {
if(newChannel.channelID === "23948567239769"){
let Name = newChannel.member.nickname.split('[')[0]
console.log(newChannel.members.size)
//console.log(Name.length)
}
})```
Im trying to get the count of how many members are in the newChannel. but no matter what i research, it keeps leading me to members.size which doesnt seem to work
hey, iam trying to detect when someone joines special channel. I got the voiceStateUpdate with oldState and newState. In version 12 all worked fine. But if i want to get the channel id in v13 i get indefined
respectively null and i dont know why.
Can someone explain me how to get this working?
id: 'id',
serverDeaf: false,
serverMute: false,
selfDeaf: false,
selfMute: false,
selfVideo: false,
sessionId: 'sessionId',
streaming: false,
channelId: null,
suppress: false,
requestToSpeakTimestamp: null
Okay so I have a live video stream from my own website that is using HLS and I want to take the stream convert that to ogg and stream it through a voice channel is that possible?
Am i doing this right
Do you have voice intents?
Can someone help me with the bot so it can join the channel when i type !join
Anyone
Hi! I'm not sure why but when console.log(oldState) while a voiceStateUpdate I get undefined, but doing it with newState actually prints what it's supposed, does anyone now why this could be happening?
My music bot throws up this error sometimes when trying to play something from youtube but not everytime. I am using play-dl
not a voice related error
okay thanks
You need the adapterCreator as a param too
yes
Is there a way to destroy an AudioPlayer?
I know they're designed to be re-used, but is there no way to destroy them?
https://discordjs.guide/voice/audio-player.html#deletion
the docs recommend stopping it and nulling out any references that hold it
I see, I was just wishing to see if there was an official manner beyond that, as with VoiceConnection.destroy().
Thank you very much, I also wasn't sure if those docs were official 😅 .
@subtle granite ? xd
Does @discordjs/voice's connections support extracting a channel from it?
Can you please tell me how do I achieve that?
@vocal valley Is there a streamtime property available to find the current time elapsed since streaming?
No
??
Plenty of information on the internet.
https://hastebin.com/hupoqigiju.typescript
TypeError: Cannot read property 'id' of undefined
you're trying to get attribute from an id lol. line 12 and line 10
interaction.member.voice.channel.id```
VoiceChannel.guild.id
Think about that one for a second.
ohhhhhhh i understand now thanks
np
You can get a voice channel from a connection, this is how I do it.
await Guild.channels.fetch(VoiceConnection.joinConfig.channelId)```
You can fetch the voice channel that the bot is currently in through this, if I am not mistaken, as well.
await Guild.channels.fetch(djsVoice.getVoiceConnection(Guild.id).joinConfig.channelId)```
The issue with the AudioPlayer that keeps aborting. Is that a Discord.JS issue or the library ytdl-core for the music?
Nvm my bad
It plays the music avg. 3 mins until it just crashes and the error is AudioPlayer: Aborted
@subtle granite It is not there
Thanks!
How do i check if someone is in a voice channel and then get that voice channel? An example in DJS 12 would be message.member.voice.channel.id
Still works but you need voice intents
How do I get them?
GUILD_VOICE_STATES need this intent
because im confused with the docs, it means that the bot can play a song on 2 or more voice channels ? https://i.imgur.com/rknotTG.png
Essentially yes, you can have one audio source output to X number of connections.
function play(msg) {
const connection = joinVoiceChannel({
channelId: "605804242493636757",
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator,
});
const connection2 = joinVoiceChannel({
channelId: "594999501203177473",
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const stream = ytdl('https://www.youtube.com/watch?v=hFPMDH0TwFg', { filter: 'audioonly' })
const resource = createAudioResource(stream);
player.play(resource);
connection.subscribe(player);
connection2.subscribe(player);
}```
that's good but I tried with a simple way and it's not working
i mean it will play only on connection2
console.log(interaction.member.voice.channel.id) spits out TypeError: Cannot read property 'id' of null
You're overwriting your connections.
From what I understand, it's for cross guilds.
ex) Server 1 and Server 2 can listen to the same playlist
ooooh. . . that means, i see now makes sense, that's why i got confused, so was for cross guilds 👍 thanks
how to play a hight quality audio ?
So whenever a channel is deleted while the bot is in it, the voice state still shows the channelId as the deleted channel
How are you checking that when the channel is deleted?
You can check the voice state
How
member.voice
So you're just calling it at a random point in time after the channel is deleted?
Sure
I can't get that to happen. It's null for me
How do I get a members voice channel ID they are in using interaction? Would it be something like interaction.member.voice.channel.id?
try it and see
you need @discordjs/voice package iirc
TypeError: Cannot read property 'id' of null
Ohhh ok, do i need to require that too?
I don't think so
still get TypeError: Cannot read property 'id' of null
Do you have the intents required?
Maybe they're not in voice?
I wasn't at the time, lemme try while in a vc
Well... kind of a duh moment, lol
Yeh, I thought that I had it setup to say if I wasn't in a vc
Now I get this... time to go to the package discord
Why didn't this trigger?
Unsure
Okay I am running v13 so I am now using an audioplayer to play mp3 files but is there a way to instead of playing mp3 files play a live broadcast?
From for example youtube
Discord can do it. That's more of a Node.js question.
You would need to find a way to get a stream from the broadcast. ytdl-code might support it, not sure how reliable it is
Unless there’s a way with voice activities
"live broadcast" is pretty broad. m3u8stream doesn't support shoutcast or icecast web servers (pretty common) iirc. You'd need to use a lib that changes the built in http's parser. Something like icy would work great which is what I use to stream all http source files. It's just the built in http lib under the hood, so it's simple to look up help articles for.
The built in http lib to use for everything else is pretty nice assuming it isn't an icecast or shoutcast web server since it's stream based
Are music bots still doable or has youtube done stuff to make it too hard?
Just looking at making a small one for me and my family
api is still open. nothing they can really do about it
awesome, thanks!
Why doesn't this join a vc?
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channel,
guildId: interaction.guild.id,
adapterCreator: interaction.member.guild.voiceAdapterCreator,
});```
Look at the second line
whats wrong with it ?
You didn't pass an id
interaction.guild.id is an id
That isn't the second line
OH
Live Stream is supported in play-dl. You can check that out.
So my bot joins the voice channel, queues song, then shows the song popup, but is silent and doesn't start playing anything. Console logged for errors but no errors are produced, it just goes silent afterwards
code please
let d = discordVoice.getVoiceConnection(interaction.guild.id);
let v = global.songVolume[interaction.guild.id];
let player = discordVoice.createAudioPlayer();
let resource = discordVoice.createAudioResource(await base.yt.audio(song), {inlineVolume: true});
async function start() {
player.play(resource);
try {
await discordVoice.entersState(player, discordVoice.AudioPlayerStatus.Playing, 5_000);
console.log('Playback has started!');
} catch (error) {
console.error(error);
}
}
void start();
is GUILD_VOICE_STATES in your intents?
Hey so I'm trying to get my bot to join a channel through a SlashCommand but for some reason it just entirely fails to execute any command. I've checked my command manager and it runs any other commands just fine so I'm pretty sure it is to do with how I'm having the bot join the channel.
const { SlashCommandBuilder } = require('@discordjs/builders');
const { joinVoiceChannel } = require("@discordjs/voice");
module.exports = {
data: new SlashCommandBuilder()
.setName('join')
.setDescription('Joins your voice channel!'),
async execute(interaction) {
const connection = joinVoiceChannel({
channelId: interaction.channelId,
guildId: interaction.guildId,
adapterCreator: interaction.guild.voiceAdapterCreator,
});
},
};
This is the code for my join.js command.
nvm i'm stupid
You are missing connection.subscribe(player)
what Can I do to prevent this from happening?
It tried this but It didnt work:
const checkConnection = getVoiceConnection(message.guild.id);
player.on(AudioPlayerStatus.Idle, () => {
setTimeout(() => {
if(checkConnection){
connection.destroy()}
else return;
}, 300000);;
})
const checkConnection = getVoiceConnection(message.guild.id);
player.on(AudioPlayerStatus.Idle, () => {
setTimeout(() => {
if(checkConnection){
checkConnection.destroy()}
else return;
}, 300000);;
})
Try this
That's what I did!