#archive-voice

30636 messages · Page 30 of 31

spice flint

I'm not using it

fiery blade

Still, I think you should use absolute paths like the guide does

spice flint
fiery blade
spice flint

Can I use a test stream?

loud sinew

@spice flint try playing audio from a url instead of a local file

spice flint
loud sinew

hmm thats odd

loud sinew
loud sinew
spice flint

Reinstall ffmpeg?

loud sinew

if i remember correctly my bot started working when i did that and it also says so in the discordjs guide

the website is hard to navigate doe lol

spice flint
loud sinew

ffmpeg - install and add to your system environment

spice flint
loud sinew >`ffmpeg` - install and add to your system environment

I removed dependencies and reinstalled ffmpeg-static "dependencies": { "@discordjs/opus": "github:discordjs/opus", "@discordjs/rest": "^0.5.0", "@discordjs/voice": "^0.10.0", "discord-api-types": "^0.33.3", "discord-buttons": "^4.0.0-deprecated", "discord-voice": "^2.0.6", "discord.js": "^13.7.0", "ffmpeg-static": "^4.4.1", "libsodium-wrappers": "^0.7.10" } I installed ffmpeg on system using git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg and tried to run but...

loud sinew
pseudo forum

what's the point of having ffmpeg?

loud sinew

^ this is not a 100% correct explanation but its just so you get the idea

pseudo forum
loud sinew
pseudo forum

I see

spice flint
loud sinew

well im out of ideas pepesad

pseudo forum

what was the issue?

spice flint
pseudo forum

can you show the code

spice flint

const player = createAudioPlayer();

const connection = joinVoiceChannel({
        channelId: interaction.member.voice.channel.id,
        guildId: interaction.guild.id,
        adapterCreator: interaction.guild.voiceAdapterCreator,
      });
      const resource = createAudioResource("https://live.radio1.si/Radio1");
      player.play(resource);
      connection.subscribe(player);
      await interaction.reply('Playing.');```
pseudo forum

probably something to do with the input type
defaults to StreamType.Arbitrary

fiery blade

No, that link works

pseudo forum

I'm talking about the inputType option

spice flint
pseudo forum

defaults to StreamType.Arbitrary

spice flint
pseudo forum

I'll try your code on my side

fiery blade
spice flint
fiery blade Is there more to the file than what you're posting?
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const { createAudioPlayer, joinVoiceChannel, getVoiceConnection, createAudioResource, StreamType } = require('@discordjs/voice');

const player = createAudioPlayer();

// **Declerations** //
var radioID = 0;
var playing = false;

// **Login** //
client.once('ready', () => {
  sendMessage(client.channels.cache.get("888939829176467506"), 99)
  console.log( 'Bot is online!');
});

client.on('interactionCreate', async interaction => {
    if (!interaction.isButton() || !interaction.channelId == '888939829176467506') return;
  if(!interaction.member.voice.channelId){
    return interaction.reply('You are not in the voice channel. Please join one and try again');
  }
  if(interaction.customId === '0'){
    
    if(!playing){
      playing = true;
      const connection = joinVoiceChannel({
        channelId: interaction.member.voice.channel.id,
        guildId: interaction.guild.id,
        adapterCreator: interaction.guild.voiceAdapterCreator,
      });
      const resource = createAudioResource("https://live.radio1.si/Radio1");
      player.play(resource);
      connection.subscribe(player);
      await interaction.reply('Playing.');
    }
    else{
      player.stop();
    }
  }
});```
spice flint
fiery blade

No, the intent flag for voicestate

spice flint

Intents.FLAGS.VoiceState

dusty needleBOT
fiery blade

You can check for yourself y'know

pseudo forum
spice flint tried none of them

it works for me
here is my code:

const Discord = require('discord.js');
const Builders = require('@discordjs/builders');
const Voice = require('@discordjs/voice');

module.exports = {
    guildOnly: true,
    category: 'music',
    data: new Builders.SlashCommandBuilder()
        .setName('playy')
        .setDescription('📤 Command to make the bot leave your voice channel.')
        .setDMPermission(false),
    /**
     * 
     * @param {Discord.ChatInputCommandInteraction} interaction 
     */
    async execute(interaction) {

        const connection = Voice.joinVoiceChannel({
            channelId: interaction.member.voice.channelId,
            guildId: interaction.guildId,
            adapterCreator: interaction.guild.voiceAdapterCreator,
        });

        const player = Voice.createAudioPlayer();
        const resource = Voice.createAudioResource("https://live.radio1.si/Radio1");

        player.play(resource);
        connection.subscribe(player);

        player.on('error', error => console.error(error));

        await interaction.reply('Playing.');
    },
};
fiery blade
pseudo forum

I saw and I why this if statement didn't work ._.

spice flint

OMGGGG Intents.FLAGS.GUILD_VOICE_STATES this was the problem all along😭. Thank you all for help now it works

spice flint
dusty needleBOT

Tag suggestion for @spice flint:
Codeblocks:
```js
const Discord = require("discord.js");
// further code
```
becomes

const Discord = require("discord.js"); 
// further code

Inline Code:
`console.log('inline!');` becomes console.log('inline!');

hazy remnant
const player = new v.AudioPlayer();
        if(!message.member.voice) return message.channel.send(`${Client.emotes.error}・Nyan.. Keira needs you to be in a voice channel!`);
        if(!message.member.voice.channel) return message.channel.send(`${Client.emotes.error}・Nyan.. Keira needs you to be in a voice channel!`);
        const connection = v.joinVoiceChannel({
            channelId: message.member.voice?.channel?.id,
            guildId: message.guild.id,
            selfDeaf: true,
            adapterCreator: message.guild.voiceAdapterCreator
        });
        const ressource = v.createAudioResource("../../rickroll.mp3");
        player.play(ressource);
        connection.subscribe(player);
        player.on("stateChange", (oldState, newState) => {
            if(newState === v.AudioPlayerStatus.Idle) {
                connection.disconnect();
                player.stop();
            };
        });
        player.on("error", console.log);
        player.on("debug", console.log);

nothing playing, know why?

maybe wrong path but idk how

ah it's better with voice states intent

but still nothing plays:

17:39:08 - [KeiraBot / Commands] Info ▪ Classy-sama.js#8097 used rickroll in keira with bread
state change:
from {"status":"buffering","resource":true,"stepTimeout":false}
to {"status":"playing","missedFrames":0,"playbackDuration":0,"resource":true,"stepTimeout":false}
state change:
from {"status":"playing","missedFrames":0,"playbackDuration":0,"resource":true,"stepTimeout":false}
to {"status":"autopaused","missedFrames":0,"playbackDuration":0,"resource":true,"silencePacketsRemaining":5,"stepTimeout":false}
[VOICE] received voice state update: {"member":{"user":{"username":"KeiraBot","id":"982972481788842024","discriminator":"6836","bot":true,"avatar":"cdea72358caa1d8ac626017d8083b175"},"roles":["982974346396069921"],"premium_since":null,"pending":false,"nick":null,"mute":false,"joined_at":"2022-06-05T11:49:07.127898+00:00","hoisted_role":null,"flags":0,"deaf":false,"communication_disabled_until":null,"avatar":null},"user_id":"982972481788842024","suppress":false,"session_id":"78ee5bc71dfd3dab69d2e15449ddbcc6","self_video":false,"self_mute":false,"self_deaf":true,"request_to_speak_timestamp":null,"mute":false,"guild_id":"942926069357498460","deaf":false,"channel_id":"942926069986639875"}
[VOICE] received voice server: {"t":"VOICE_SERVER_UPDATE","s":7,"op":0,"d":{"token":"6c6f85ffd15174be","guild_id":"942926069357498460","endpoint":"rotterdam5901.discord.media:443"}}
state change:
from {"status":"autopaused","missedFrames":0,"playbackDuration":100,"resource":true,"silencePacketsRemaining":0,"stepTimeout":false}
to {"status":"playing","missedFrames":0,"playbackDuration":100,"resource":true,"silencePacketsRemaining":0,"stepTimeout":false}
state change:
from {"status":"playing","missedFrames":0,"playbackDuration":200,"resource":true,"silencePacketsRemaining":0,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}

oh i made it work

white talon

When using ytdl-core with @discordjs/voice it seems to randomly throw an error

Is it possible to fix this without having to try/catch it

next nacelle

aborted ECONNRESET?

any ideas?

fiery blade

If you convert a buffer into a readstream that works

fiery blade
white talon

AudioPlayerAborted IIRC

south lark

Has anyone who owns public Discord bots that use djs-voice experienced issues with memory (ram) usage? My bot uses what I feel is a ton of RAM for voice things and starts lagging pretty badly after a day of being online. How is everyone dealing with this and is there any fix?

median oar

Hello. I am making a soundboard command. I have two bots, one for developer use and one for regular, everyone use. The developer bot runs on windows while the regular bot runs on Linux. My issue is that the soundboard works fine on the developer bot but not the regular bot. Both are running the exact same code and have the exact same modules (well sort of, I'm pretty sure tweetnacl isn't the reason it's not working).

When the regular bot's command is run, it joins and leaves instantly without playing audio while the devbot Joins, plays the audio, and then leaves. Does anyone have a possible solution for this problem?

south lark

For voice receiving, what is the difference between EndBehaviorType Aftersilence and EndBehaviorType AfterInactivity?
Is there a benefit to using one over the other?

Additionally, I've been having problems where sometimes the same audio is received twice instead of once as well as audio being cut very quickly into short durations despite the user continuing to talk during the whole time. Any fix or reason as to why this may be happening?

waxen wedge
south lark

Cause I'm pretty in some examples for voice receiving, they do exactly that.

And by "dereference" do you mean destructuring or setting things as null once done with them?

waxen wedge

make sure the scope they are defined in ends with their use (including event listeners that get defined in their scope), …

brave tree

Hey!
I want to make an xp bot and I want it to give xp when users are also in voice. It seems to me that you have to use a Listener, right? Could you tell me how I can do this easily ?

fervent estuary

you can use voiceStateUpdate to track how long a member stays in a vc

south lark
waxen wedge

Like <AudioPlayer>.on etc.

south lark

Would would turning them off look like?

I apologize, probably a stupid question, but I'm not quite understanding what you are saying.

waxen wedge

<AudioPlayer>.off('eventName', functionName)

south lark

Oh, I don't think I'm doing that

Can you turn it off within the on area? Like on run?

Wouldn't nodejs warn me if I had too many listeners though?

slender sparrow

if you have nested listeners yes

fervent estuary

if u wish for a listener to only emit once use .once

south lark

Ah, yeah I'm doing that.

fervent estuary

no point in using .on and then .off right after

south lark
fervent estuary no point in using .on and then .off right after

So for example, should this me .on or .once?

voice_Connection.on(VoiceConnectionStatus.Disconnected, async e => {
                    try {
                        await Promise.race([
                            entersState(voice_Connection, VoiceConnectionStatus.Signalling, 1_000),
                            entersState(voice_Connection, VoiceConnectionStatus.Connecting, 1_000)
                        ]);
                        // Seems to be reconnecting to a new channel - ignore disconnect
                    } catch (error) {
                        // Seems to be a real disconnect which SHOULDN'T be recovered from
                        if (msg.guild.me.permissions.has("CHANGE_NICKNAME")) msg.guild.me.setNickname(null);
                        return functions.data(msg.guild.id).then(voice_Connection.destroy());
                    }
                });

I think .on 🤷‍♂️
But then do I need to do some .off stuff in the catch area?

fervent estuary

yeah sounds right

south lark
fervent estuary

iirc voiceConnection.destroy should remove all listeners

so that should work

south lark

Okay awesome

fervent estuary

just add a proper function in that .then at the end

south lark

wdym

fervent estuary

ur just passing the destroy function there now

then takes in a proper function that you can call destroy within

south lark

Wait what

I thought using <voice connection>.destroy() would just destroy the voice connection. Does it not?

They just show it like this in djs guide

fervent estuary

it does. just the way youre calling it in that .then isnt right

south lark

Oh I see

fervent estuary

you can just add a simple arrow function in front and should work just fine

south lark

Ah I see alright

south lark
fervent estuary

yeah just like that

south lark

Epic

Is voiceStateUpdate emmited when the bot disconnects?

slender sparrow

yes

south lark

Good to know, thanks

south lark

Would love some answers to the following questions when someone gets the chance:

south lark
south lark For voice receiving, what is the difference between EndBehaviorType Aftersilence...

For voice receiving, what is the difference between EndBehaviorType Aftersilence and EndBehaviorType AfterInactivity?
Is there a benefit to using one over the other?
Additionally, I've been having problems where sometimes the same audio is received twice instead of once as well as audio being cut very quickly into short durations despite the user continuing to talk during the whole time. Any fix or reason as to why this may be happening?

pliant lava

How can i get stream time?

brave tree
fiery blade
waxen wedge
south lark
south lark

No worries 👍

Hopefully someone else may know what is causing the problem 🙏

fervent estuary
pliant lava

How can i get progress of the audio?

keen flower

hey, how can i learn to use discord voice?

for example recording voice in channels

loud sinew
slender sparrow

its not against TOS if you doesnt abuse, for example you recording without telling the user that you are recording their voice

fiery blade
keen flower
loud sinew

if i destroy a VoiceConnection, does the player subscribed to it also get destroyed, or do i have to clean it up manually?

waxen wedge

The subscription gets destroyed too afaik. The player might be if there are no subscriptions to it but don’t quote me on that. I’d rather make sure and clean up after yourself

loud sinew

my bot always has only one player per connection btw

waxen wedge

That’s normal, it‘s more the question if you also only have one connection per player😉

loud sinew
mighty island

Will anyone teach me discord.js

zzz_teddyplsss

pseudo forum
mighty island

Vdo turorials are available??

pseudo forum
mighty island

Wht?

languid quail

guide is better than YouTube/video tutorials

native magnet

Hello, I'm making a bot play sounds in different guilds at the same time.
Problem is that when I get the player to work "per guild" I can't access the js player.on(AudioPlayerStatus.Idle

the way I managed to play different sounds in different guilds is to put the player as an object in the guild.

 client.guilds.cache.get(guild).musicPlayer = createAudioPlayer();

Is there a way to work this out better so I can access the events from the player?
Or to get a player per guild?

waxen wedge
native magnet

for every joined guild it will be created as the musicPlayer in the guild itself,

can I access the event for the musicplayer within the guild? 😖

Here is most of the play function I'm testing. *note that I'm not the best coder *😂

           getGuild.musicConnection = joinVoiceChannel({
                channelId: getGuild.musicChannel,
                guildId: guild,
                adapterCreator: await client.guilds.cache.get(guild).voiceAdapterCreator
            });

            var stream = await ytdl(q, { 
                highWaterMark: 1 << 25,
                filter: 'audioonly',
            });

            client.guilds.cache.get(guild).musicStream = stream;


            const resource = createAudioResource(client.guilds.cache.get(guild).musicStream, { inputType: StreamType.Opus });
            client.guilds.cache.get(guild).musicResource = resource;
            client.guilds.cache.get(guild).musicConnection.subscribe(player);
            client.guilds.cache.get(guild).musicPlayer = createAudioPlayer();
            //var player = createAudioPlayer();

            client.guilds.cache.get(guild).musicPlayer.play(client.guilds.cache.get(guild).musicResource); // play
subtle granite

opus support arch linux?

median oar

does voice even work on linux

south lark
stoic thunder

is there a v13 example of ytdl-core

fiery blade
south lark

How can I take the audio stream for voice receiving for like sending as a stream to an API?
Like where can I get the literal stream from the voice receiving part to be sent elsewhere?
Like the audio/ogg stream

halcyon ether

Any way to check if a voice channel has text chat in it? Would .isText() work for that? Iirc most servers for now have to turn it on explicitly and I don't want the bot to crash if it's not enabled, but I dunno how to check for that

fiery blade

i.e. guild.features, should be 8 since hasn't been added to the enum yet

halcyon ether

Can't see it ;/

fiery blade

Yeah I doubt ddocs is updated

halcyon ether

It's not in the Discord.js type either

fiery blade

That was also probably forgotten in 13.8

halcyon ether

Don't see it in v14 either, so no clue what to type so that it works

minor bison
halcyon ether

I'll try

spice flint

Is there still a way to play youtube url songs?

bold tinsel

Heya! I'm trying to make a music bot for my server and am relatively new to DJS, I am having problems connecting my bot to the voice channel.

Here is my code:

            try {
                console.log(": Beginning try statement");

                
                const connection = joinVoiceChannel({
                    channelId: voiceChannel,
                    guildId: interaction.guild.id,
                    adapterCreator: interaction.guild.voiceAdapterCreator,
                });
                
                console.log(": Initiated connection");

                //await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
                //connection.subscribe(player);


                queueConstruct.connection = connection;

                console.log(": Got to the end!");

            } catch (e) {
                console.log(e);
                interaction.reply(e);
            }

_ _
I don't get any errors but the bot doesn't join the channel

brazen siren

Does the bot have the permission to join said channel? Does the bot see the said channel?

bold tinsel
brazen siren

And it has intents?

bold tinsel
brazen siren And it has intents?
const { Client, Intents, CommandInteractionOptionResolver, MessageEmbed, Message, MessageAttachment, MessageActionRow, MessageButton, ButtonInteraction, } = require('discord.js');
const Discord = require("discord.js");
const { joinVoiceChannel, createAudioPlayer, createAudioResource, entersState, StreamType, AudioPlayerStatus, VoiceConnectionStatus } = require('@discordjs/voice')
const ytdl = require('ytdl-core');
const client = new Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES,
        Intents.FLAGS.DIRECT_MESSAGES,
        Intents.FLAGS.DIRECT_MESSAGE_TYPING,
        Intents.FLAGS.GUILD_INVITES,
        Intents.FLAGS.GUILD_MEMBERS,
        Intents.FLAGS.GUILD_VOICE_STATES
    ],
    partials: ['MESSAGE', 'REACTION', 'CHANNEL']
});

It should have everything, I'm using discordjs/voice

oop

brazen siren

GUILD_VOICE_STATES

bold tinsel

Yes, should I put that in intents?

brazen siren

Please try and let me know if it worked

bold tinsel
brazen siren Please try and let me know if it worked

I changed my intents around

const { Client, Intents, CommandInteractionOptionResolver, MessageEmbed, Message, MessageAttachment, MessageActionRow, MessageButton, ButtonInteraction, } = require('discord.js');
const Discord = require("discord.js");
const { joinVoiceChannel, createAudioPlayer, createAudioResource, entersState, StreamType, AudioPlayerStatus, VoiceConnectionStatus } = require('@discordjs/voice')
const ytdl = require('ytdl-core');
const client = new Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES,
        Intents.FLAGS.DIRECT_MESSAGES,
        Intents.FLAGS.DIRECT_MESSAGE_TYPING,
        Intents.FLAGS.GUILD_INVITES,
        Intents.FLAGS.GUILD_MEMBERS,
        Intents.FLAGS.GUILD_VOICE_STATES
    ],
    partials: ['MESSAGE', 'REACTION', 'CHANNEL']
});

Still isn't working, not getting any errors and it isn't connecting :/

hazy remnant

Better to use play-dl tho

bold tinsel
brazen siren
bold tinsel
brazen siren

You can do a quick sanity check before calling the command to ensure that the variable does have the value you expect it to have

bold tinsel
brazen siren

Let me spin up a bot real quick, I'll let you know if I encounter a similar issue

bold tinsel

alr, thanks so much

brazen siren

Alright got it to work, here is the code:

const { Client, Intents } = require('discord.js')
const { joinVoiceChannel } = require('@discordjs/voice')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_VOICE_STATES] })

client.on('ready', () => {
    const guild = client.guilds.fetch(guildID).then(guild => {
        const channel = guild.channels.fetch(channelID).then(channel => {
            const connection = joinVoiceChannel({
                guildId: guildID,
                channelId: channelID,
                adapterCreator: guild.voiceAdapterCreator
            })

            setTimeout(() => {
                connection.close()
                    .then(console.log)
                    .catch(console.error)
            })
        })
    })
})```
bold tinsel

mhm

brazen siren

Needless to say, guildID and channelID is where you put the specific guild and channel IDs respectively, whichever way you fetch it, interaction or w/e.
No special permissions required other than to see and be able to join the specific channel.

bold tinsel

hmm

Well I got almost the same code as you and I think it should be working, it's possible there is a problem somewhere else somehow

Actually nvm

It's annoying that there isn't any error logged

brazen siren

I don't have any special perms, only using the bot scope and voice permissions [connect, speak].
Since you gave your bot full admin access, it should have the ability to join the voice channel.
Can you verify that you have @discordjs/voice package installed?

Alternatively, you could be rate limited if your bot did some funky stuff, try again in some time and see if this persists.

subtle granite

Does anyone know how to make the bot catch the radio link?

brazen siren
subtle granite

if it will be defined directly in the bot via case 1 and link, do the same or somehow different?

brazen siren

I don't follow... if you have the specific link, since you defined it manually in the bot, then just use the same variable again?

subtle granite

ok, thanks

brazen siren

👍

cosmic sandal

I am using @discordjs/voice to allow my bot to connect and discord-tts (https://www.npmjs.com/package/discord-tts) to give it the ability to TTS in chat. I can get it to connect and speak just fine. Issue I am having is if someone else sends the speak command while the bot is already speaking, it throws an Abort error and crashes the bot.
Code:

        const audioResource=createAudioResource(stream, {inputType: StreamType.Arbitrary, inlineVolume:true});
        const connectionCheck = getVoiceConnection(message.member.voice.channelId)
        this.logger.info(connectionCheck);
        if(!voiceConnection || voiceConnection?.status===VoiceConnectionStatus.Disconnected){
            voiceConnection = joinVoiceChannel({
                channelId: message.member.voice.channelId,
                guildId: message.guildId,
                adapterCreator: message.guild.voiceAdapterCreator,
            });
            voiceConnection=await entersState(voiceConnection, VoiceConnectionStatus.Connecting, 5_000);
        }
        
        if(voiceConnection.status===VoiceConnectionStatus.Connected){
            voiceConnection.subscribe(audioPlayer);
            audioPlayer.play(audioResource);
        }

        audioPlayer.on(AudioPlayerStatus.Idle, () => {
            voiceConnection.destroy();
        })```

Error:
```{"error":{"code":"ABORT_ERR","name":"AbortError"},"level":"error","message":"unhandledRejection: The operation was aborted\nAbortError: The operation was aborted\n    at abortListener (node:events:842:14)\n    at EventTarget.<anonymous> (node:events:878:47)\n    at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:559:20)\n    at EventTarget.dispatchEvent (node:internal/event_target:504:26)\n    at abortSignal (node:internal/abort_controller:97:10)\n    at AbortController.abort (node:internal/abort_controller:122:5)\n    at Timeout.<anonymous> (/home/bots/ModBot/node_modules/@discordjs/voice/dist/index.js:2004:39)\n    at listOnTimeout (node:internal/timers:557:17)\n    at processTimers (node:internal/timers:500:7)","stack":"AbortError: The operation was aborted\n    at abortListener (node:events:842:14)\n    at EventTarget.<anonymous> (node:events:878:47)\n    at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:559:20)\n    at EventTarget.dispatchEvent (node:internal/event_target:504:26)\n    at abortSignal (node:internal/abort_controller:97:10)\n    at AbortController.abort (node:internal/abort_controller:122:5)\n    at Timeout.<anonymous> (/home/bots/ModBot/node_modules/@discordjs/voice/dist/index.js:2004:39)\n    at listOnTimeout (node:internal/timers:557:17)\n    at processTimers```

I snipped the second half of the error because it is just system information.

I think the voiceConnection status checker does not work. I tried to swap it for if(AudioPlayerStatus.Playing)return; but that causes the bot to always just not play audio even if it was already disconnected before

stoic thunder

how do i check if a audioplayer is playing

cosmic sandal

That is also my question I suppose, just mine was more long winded

stoic thunder

throw new Error("Cannot play a resource that has already ended."); Why does this exist?

bold tinsel
brazen siren

No, I ran the bot from my machine as well. You could simply be polling Discord APIs too fast and were placed on a timeout. Again, just a theory.

bold tinsel

Alr, I'll give it a break for the day and try again tmrw 😉
thanks so much

brazen siren

No worries, take it easy.

stoic thunder

how would i make a loop command

brazen siren
stoic thunder how would i make a loop command

Create a loop variable that will be set to true if some arbitrary command or interaction is executed.
Create a variable curRes that stores the current player resource.
Then,

player.on(AudioPlayerStatus.Idle, () => {
   // Edit: Probably should check if we're looping and execute that first
   // Instead of needlessly shifting tracks from the queue... my bad :D
   if(loop) {
      player.play(curRes)
   } else {
      const newRes = createAudioResource(tracksList.shift())
      if(newRes) {
         player.play(newRes)
         curRes = newRes
      } else {
         // You probably want to notify the user or log that there was an error creating an audio resource
      }
   }
})```
strong thorn
strong thorn
strong thorn

how to solve? this disconnects my bot from the channel and prevents it from streaming my playlist

brazen siren
strong thorn

It's a Discord API error, it took too long to send the request and it was aborted, hence the AbortError that was thrown.

stoic thunder

trying to make a ambience command that loops until somebody types /stop

or if there are no people in the voice channel

brazen siren
strong thorn

ty

brazen siren

No worries 😛

brazen siren
// Super mega cool ultra giga player 9000
player.on(AudioPlayerStatus.Idle, () => {
   const audioResource = createAudioResource(loop ? someStaticSongPathOrLastKnownSongPath : tracksList.shift())

   if(audioResource) player.play(audioResource)
   else console.log('funny stuff happening guys')
})```
stoic thunder

i did the latter and memory leaks every where

also how do you adjust the volume

brazen siren
stoic thunder

this is my code for reference

brazen siren
stoic thunder

@brazen siren i did this ```js
player.on(AudioPlayerStatus.Idle, () => {
let loop = createAudioResource(stream);
player.play(loop);
});

and it did not loop, i am also using ytdl-core ```js
(node:1760) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [PassThrough]. Use emitter.setMaxListeners() to increase limit

brazen siren

Put the player.on(event, cb) outside... you keep making new event listeners on each interactions, rather than having one global listener.
I tested it, it works just fine with no memory leaks.

shrewd compass

How can check that if player exist for a particular server or not

fervent estuary

depends on how you store players

shrewd compass
waxen wedge

That doesn’t store it outside of that scope. So you can’t access it anymore

shrewd compass

Like what if i store that things in a map? And use it can it be possible?

waxen wedge

Sure. Attach the map to the client and you‘ll always have it around everywhere

shrewd compass
waxen wedge

client.players = new Collection() somewhere after your client definition, client.players.set(guildId, player) when you created a player and client.players.get(guildId) to get one if it exists (Same way you interact with caches in djs, since they are Collection too)

shrewd compass
waxen wedge

And yes, you .delete(guildId) when you don’t need the player anymore

prime void

Hello, is possible somewhat to play a raw source of music? e.g. If I have a radio which is not providing an endless mp3 file, but a file without any extension.
For example, here is a link http://mp3.polskieradio.pl:8900/; (the semicolon belongs to this link)

when I try to use it as endless mp3 file, it just ends with Error: Cannot play a resource that has already ended.

finite grotto
prime void
prime void

and nothing seems to have a problem

south lark

How can I get the audio stream when receiving audio?
Like is there a .getAudioStream() or something 🤷‍♂️

south lark

Additionally, I need help with frameSize. I'm not exactly understanding what is supposed to go there and how I calculate it relative to bits and whatnot.

south lark

Does @discordjs/opus require frameSize when using pipeline with prism opus?

lilac quarry

Hello, this is going to be a stupid sounding question. I have my bot set up to play a track that is in the directory, called title.mp3. I have ffmpeg, ffmpeg-static, and libsodium-wrappers installed. I know I'm supposed to use @discordjs/opus but I can't do that on Replit so I opted to try an alternative I heard was supposed to work called opusscript. However, when I call the command, it successfully joins the channel, shows the green circle as if it is supposed to be talking, but does not actually play sound. I know this is supposed to be a problem with not having opus, but I cannot use @discordjs/opus. Does anyone know what I'm doing wrong/how to fix this? The source code is here if it helps https://replit.com/@Kestron/SMOMusicBot-1

brazen siren
spice bison

Hi,

After several tries, I still haven't managed to create the code I want. New to discordJS, I would like to be able to follow a code pattern.
Does anyone have code to do the following:

  • When writing "example" in a channel, the bot reacts to the word "example" then connects to the voice channel where the user is
  • It will play the music located in ./audio/try.mp3 and disconnect when the music is finished.

(can you tell me the requirements please thank you)

thank you !

eager lake
shrewd compass

Like do i have to use?
if (client.players.cache.get !=== guildid){interaction reply(lol)}

waxen wedge
waxen wedge

Or a guild from client.guilds.cache or a message from <Channel>.messages.cache, …

shrewd compass
waxen wedge

That doesn’t sound right does it?

shrewd compass
waxen wedge
shrewd compass

client.player is map and it is being cached

waxen wedge

You’d do const channel = client.channels.cache.get(channelId) and then check if channel is undefined. Same for your Collection

waxen wedge
shrewd compass

Oh sry i replaced collection to map

shrewd compass
waxen wedge
shrewd compass
waxen wedge

You need .cache in djs properties to get a Collection you can work with. You don‘t need it here as you already have a Collection

shrewd compass

Ohk ic

lilac quarry
brazen siren
lilac quarry
brazen siren
lilac quarry Okay, dang. I didn't know if bots were affected by being deafened, as this bot s...

discord.js voice module deafens by default, I assume this was a decision for privacy reasons or to prevent malicious collection of voice activity
spin up a digitalocean droplet, it's like $5 a month without any restrictions... if it's free, either you are the product(by selling your data), or it will be heavily limited in resources and ability

I suspect that replit does not allow wasm modules from being loaded, thus opusscript not working for your on replit. If the same code runs without issue on your local machine, then that suspicion is probably the reality.

lilac quarry
brazen siren
lilac quarry
brazen siren
lilac quarry
brazen siren
brazen siren
lilac quarry 👍

Alright, running this code, I've had no issues with the voice activity being heard by me.
Just declare guildID and channelID variables with where you want the bot to play the audio.
If it's still not working then I'm afraid it's something else.

const { Client, Intents } = require('discord.js')
const { createAudioPlayer, AudioPlayerStatus, NoSubscriberBehavior, createAudioResource, joinVoiceChannel } = require('@discordjs/voice')
const client = new Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_VOICE_STATES
    ],
    restRequestTimeout: 60000
})

const player = createAudioPlayer({
    behaviors: {
        noSubscriber: NoSubscriberBehavior.Play
    }
})

player.on(AudioPlayerStatus.Idle, () => {
    const song = createAudioResource('test.mp3')
    player.play(song)
})

client.on('ready', () => {
    const guild = client.guilds.fetch(guildID).then(guild => {
        const channel = guild.channels.fetch(channelID).then(channel => {
            let connection = joinVoiceChannel({
                guildId: guildID,
                channelId: channelID,
                adapterCreator: guild.voiceAdapterCreator
            })
            
            if(connection) {
                connection.subscribe(player)
            }
        })
    })
})```
lilac quarry
brazen siren
lilac quarry

It still didn't work so I'm going to uninstall all node stuff and reinstall the ones I need real fast

brazen siren
lilac quarry
brazen siren
lilac quarry
brazen siren
lilac quarry

Hmm

brazen siren

You can try debugging dependencies as well to ensure they are found:

const { generateDependencyReport } = require('@discordjs/voice')
console.log(generateDependencyReport())
lilac quarry

Noted! Will run in a second...

I tried uninstalling and installing a couple different libraries which is why this list will look different than originally stated.

brazen siren

try removing sodium and installing libsodium-wrappers

lilac quarry

Still nothing

brazen siren
lilac quarry Okay

Reinstalled it all, I changed the if(connection) block to this, see if that makes it work:

if(connection) {
  connection.subscribe(player)
  const song = createAudioResource('test.mp3')
  player.play(song)
}```
Core Dependencies
- @discordjs/voice: 0.10.0-dev
- prism-media: 1.3.2

Opus Libraries
- @discordjs/opus: not found
- opusscript: 0.0.8

Encryption Libraries
- sodium-native: not found
- sodium: not found
- libsodium-wrappers: 0.7.10
- tweetnacl: not found

FFmpeg
- version: 4.4.1-essentials_build-www.gyan.dev    
- libopus: yes
lilac quarry

It logged that it's playing, and shows the green circle still. I'm going to uninstall discordjs/opus and go back to opusscript

Still no sound

brazen siren
lilac quarry

WAIT! IT'S WORKING!

brazen siren

Woot woot! 😄

lilac quarry

No idea what changed, but it's going. Thanks for your help!

brazen siren
lilac quarry
solid sun

anyone know how to interact with new discord voice text channels?

radiant spindle

same way you do with regular text channels

spice bison

Hi guys,
I tried this and dosn't work, console said me "ReferenceError: message is not defined" ?

const { Client, Intents } = require('discord.js');
const { joinVoiceChannel } = require('@discordjs/voice');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_VOICE_STATES] });

client.on('ready', () => {
    console.log('Connexion réussie au bot!');
    const guild = client.guilds.fetch(guildID).then(guild => {
        const channel = guild.channels.fetch(channelID).then(channel => {
            const connection = joinVoiceChannel({
                guildId: guildID,
                channelId: channelID,
                adapterCreator: guild.voiceAdapterCreator
            })

            setTimeout(() => {
                connection.close()
                    .then(console.log)
                    .catch(console.error)
            })
        })
    })
});

const connection = joinVoiceChannel({
    channelId: message.member.voice.channel.id,
    guildId: message.guild.id,
    adapterCreator: message.guild.voiceAdapterCreator
});

const EXEMPLE = ['Exemple', 'EXEMPLE'];
const player = createAudioPlayer();
const resource = createAudioResource('./audio/essaie.mp3');

client.on('messageCreate', (message) => {
    if (message.author.bot) return false;
EXEMPLE.forEach((word) => {
    if (message.content.includes(word)) {
        player.play(resource);
            connection.subscribe(player);
        };
    });
});

client.login(process.env.TOKEN);
radiant spindle

you are creating the connection outside of any message context

solid sun
radiant spindle
solid sun

ok thanks

spice bison
radiant spindle
spice bison
radiant spindle

Thx but another error ; createAudioPlayer is not defined
( I have two const defined player/ressource for audio player ??)

brazen siren
bitter thunder

Hey folks. Not quite sure what's going on. I migrated my bot from discordjs-12 to discordjs-13 over the past few weeks. I got it all set up working with sound and everything. Had no issues since.

Tried using it today, and it joins, but never emits sound. No errors occur. No code changes have occurred, either. I'm able to reproduce both locally and on my remotely hosted instance of the bot

Not sure how to provide any debug logs since nothing is throwing an exception

modern lotus

is there anyway for me to queue.destroy() when the bot is disconnected from a voice channel

icy maple

You just want to detect when the bot gets disconnected?

modern lotus
icy maple

I’m not familiar w/ that package

modern lotus
icy maple

You would just listen to the connection.disconnected event

modern lotus

yeah i looked that up but it just tuned to a tutorial of a guy using databases and mongo and whatnot so im kinda confused af on that topic,

something about new state and old state event listners

icy maple

Could also use stateChange

modern lotus

im not familiar, havent seen that one in the docs any tips on using it?

or you know like what it is

icy maple

It fires when the connection changes state

You get the old and new state

Basically a catch all for the state changes, the individual events only check the new state providing the old state as the param

modern lotus
icy maple

You don’t need mongo

modern lotus

😅

bruh

slender sparrow

its djs-voice problem, not @discordjs/voice.

abstract kiln

How can I play a YouTube video from a specific timestamp?

waxen wedge
abstract kiln

There appears to be support for it in ffmpeg.

Don't know if it's possible to pass ffmpeg options in discord.js/voice.

I found this, but it seems outdated.

slender sparrow

see play-dl implementation

abstract kiln
abstract kiln

How can I adjust volume?

I was using resource.volume.setVolume(variable) before, but when I CTRL+F'd for volume in the play-dl documentation I came up blank.

waxen wedge

That’s how you do it in djs voice. And since you still use AudioResource from djs voice that’s still how you do it.

icy maple

I don’t think play-dl can adjust volume

waxen wedge

Just make sure to create the AudioResource with inlineVolume true

abstract kiln
obtuse hawk
const connection = joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
});

How do I got about making the bot be a speaker when joining a stage channel? I know it's to do with setsuppressed, but I can't figure how to do it with this?

stoic thunder

How do I make the bot leave when everybody is not in the vc?

waxen wedge
modern lotus




            let oldChannel = oldState.voiceChannel
            let newChannel = newState.voiceChannel

            if (oldChannel != newChannel) {

                console.log("user moved")

            }
        });

I'm using this but literally nothing happens..

i don't exactly get what's going wrong here

hazy remnant

Do you have the GUILD_VOICE_STATES intent activated?

modern lotus

yeah iv tried another method which worked but now its just really weird as i have the bot log whenever the bot is moved/added/removed from a call but whenever the bot is removed it just sends the same log twice

icy maple
stoic thunder

How can I get the members inside a voice channel after a voice state update?

I tried newState.channel.members.size

strong thorn

how to solve?

whole flare
stoic thunder
whole flare
stoic thunder

no ```js
bot.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.channelId !== oldState.guild.me.voice.channelId || newState.channelId) return;

const vc = newState.guild.channels.cache.get(newState.channel.id);
if (vc.members.size === 1) {
    bot.player.destroy();
}

});

I'm trying to make my bot automatically leave when it is the only one in the voice channel

whole flare
gentle gust

some kid told me they changed discord.js.Client.on() to discord.js.Client.once()

try using bot.once

whole flare
stoic thunder

^

stoic thunder

.on executes when the event happens

whole flare
gentle gust oh

You only should do that for events like ready that only get emitted once

gentle gust

yeah I got it
Client.on-> executes the event whenever it happens, regardless the amount of times it happened
Client.once-> executes the event whenever it happens, only once

zenith mountain
subtle granite

How can I know player is playing or not?

Does djs have such events, methods or properties?

subtle granite

My music bot isnt running lavalink so isnt outputting audio can someone either help get it workign or convert it to lavalink?
its running on replit

dusty needleBOT

Suggestion for @subtle granite:
guide Library: Life cycle
read more

subtle granite

ty

prime void

hello, @waxen wedge, I have got stream like this: http://mp3.polskieradio.pl:8900/; and I would like to play it in voice channel, if I set a raw type, it runs without error, but nothing will play

any ideas for solve?

waxen wedge
prime void

okay, sorry, I know, that you've helped me much in the past, so I tried to contact you

prime void
mystic oxide

can someone help me on this error? .on('playSong', (queue, song) =>
^

TypeError: Cannot read properties of undefined (reading 'on') the code is here if needed: https://sourceb.in/Yn97RXRvxz

Its from a plugin called 'distube'

finite grotto
final brook

is there a way to detect when an audio resource has been finished playing?

icy maple
mystic fable

not playing audio, any ideas?

 const player = createAudioPlayer({
            behaviors: {
                noSubscriber: NoSubscriberBehavior.Pause,
            },
        });
        const resource = createAudioResource('path/to/audio/1.mp3', {
            metadata: {
                title: 'Test song!',
            },
        });
        
        player.play(resource);
        
        player.on('error', error => {
            console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`);
            player.play(getNextResource());
        });
        player.on(AudioPlayerStatus.Playing, () => {
            message.channel.send({content: "Song started."})
        });

Dependencies Report

icy maple
mystic fable

yep, still not working

There was an uncaught error: Error: Cannot play audio as no valid encryption package is installed.

icy maple
mystic fable

I am just unable to install @discordjs/opus

I could install opusscript and sodium-native, but @discordjs/opus gives me that weird node-gyp error, because I am on windows

dusty needleBOT

Tag suggestion for @mystic fable:
• Run npm i windows-build-tools --production --vs2015 --add-python-to-PATH --global as admin.
• Restart your terminal or machine (if terminal is not sufficient).

mystic fable

getting errors

icy maple

Show it

mystic fable
icy maple

What error do you get from installing @discordjs/opus?

mystic fable

that node-gyp error

icy maple

Did you install the C++ thing it mentioned?

Or nvm, you just need to set the msvs_version

Run npm config set msvs_version 2022 and try installing it again

Seems like you conveniently have VS installed

mystic fable

that seemed to work, but it plays nothing

icy maple

Can you check if the player.idle event is running?

mystic fable

how to do that?

icy maple

player.on("idle", () => console.log("Done playing song"))

mystic fable

yeah it's idle

icy maple

The resource path is prob invalid

Did you provide a relative path, or absolute?

mystic fable
const resource = createAudioResource(__dirname + '../Audio/1.mp3', {

I tried like this now, not working
also tried

 const resource = createAudioResource('C:/Users/VLADY/Desktop/Discord/Drake 3/Audio/1.mp3', {
icy maple

I would use path.join for the former instead of string concatenation

mystic fable

oh, I figured it out and now it works. Thanks.
But I have one more question
how do I do to make commands like play, stop, pause to be corelated
like, to be the same connection as in play
if I do connection.destroy() in stop.js
to reffer to the same connection defined in play.js

icy maple

Use getVoiceConnection(guildId) to get the connection

mystic fable

that's it?

icy maple

The player is accessed by connection.state.subscription.player

Assuming the connection is connected, .subscription is undefined otherwise

mystic fable

and if I want to make an array of resources, from an array of files, do I do

resources.map(e => player.play(e))
connection.subscribe(player)

or?

icy maple

Calling player.play multiple times will just make the last one play

If you want a queue, you would have to implement that manually

mystic fable

like to make an array of resources and then

resources.map(song => connection.subscribe(song))

sorry for asking a lot of things, I am new to this

languid quail

that won't work...

mystic fable

github copilot gave me this

let resources = fs.readdirSync('C:/Users/VLADY/Desktop/Discord/Drake 3/Audio').filter((file) => file.endsWith(".mp3"));

        for (const song of resources)
        {
            const resource = createAudioResource(`C:/Users/VLADY/Desktop/Discord/Drake 3/Audio/${song}`);
            player.add(resource);
        }

yeah that doesn't work

icy maple

I wonder whose code it copied

mystic fable

I wonder too

icy maple

Just call createAudioResource on all resources to create a Resource

mystic fable
 let resources = fs.readdirSync('C:/Users/VLADY/Desktop/Discord/Drake 3/Audio').filter((file) => file.endsWith(".mp3"));
        let songs;
        for (const song of resources)
        {
            const resource = createAudioResource(`C:/Users/VLADY/Desktop/Discord/Drake 3/Audio/${song}`);
            songs = resource;
        }
        player.play(songs)
        connection.subscribe(player)

like this?

yeah...no

icy maple

I would just map the Array

mystic fable

yeah, then how to create resource from array?

icy maple

By mapping the Array

dusty needleBOT

mdn Array.prototype.map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

mystic fable

I know how to map
What I don't understand is how to add to the player

icy maple

You can only play one song at a time

Hint: use the player.idle event

mystic fable

hm, alright

 player.on("idle", () => message.channel.send({content: "Song ended."}), i = i + 1, player.play(createAudioResource(songs[i])), connection.subscribe(player));

tried like this, but doesn't seem to work

languid quail

songs is an array of what exactly?

mystic fable

paths to audio files

figured that out

 const connection2 = getVoiceConnection(message.channel.guild.id);
      if (connection2 == undefined)
        return message.channel.send({
          content: "Not connected to voice.",
        });
        else
        {
            connection2.pause();
            message.channel.send({content: "Paused."});
        }

how to pause or resume?

mystic fable

it's in another file, player not defined

const {
    VoiceConnectionStatus,
    entersState,
    joinVoiceChannel,
    getVoiceConnection,
    createAudioPlayer,
    NoSubscriberBehavior,
    createAudioResource,
    AudioPlayerStatus,
  } = require("@discordjs/voice");
  module.exports = {
    name: "pause",
    usage: "d2dev pause",
    description: "Debug",
    hidden: true,
    async execute(message, args, client) {
      const connection2 = getVoiceConnection(message.channel.guild.id);
      if (connection2 == undefined)
        return message.channel.send({
          content: "Not connected to voice.",
        });
        else
        {
            console.log(connection2.subscription)
            connection2.subscription.player.pause();
            message.channel.send({content: "Paused."});
        }
    }
  }
connection2._state.subscription.player.pause();

this works, but resume doesn't

mystic fable

because that's what logging connection2 gives

icy maple

state is prob a getter

You shouldn’t be using private props anyways

mystic fable
Unhandled promise rejection: TypeError 
TypeError: connection2.state.subscription.player.resume is not a function

could it be cause by this?

const player = createAudioPlayer({
        behaviors: {
          noSubscriber: NoSubscriberBehavior.Pause,
        },
      });
mystic fable

ohh..

icy maple
mystic fable

yeah, that worked

icy maple

Doesn’t seem like our ts docs supports getters yet

strong thorn

how to solve?

waxen wedge
rotund wave

guys, i cant install djs opus

subtle granite

wat do for these?

waxen wedge
subtle granite
subtle granite
waxen wedge
subtle granite

so what would i need to do then

waxen wedge

Or find out when the error gets thrown to get an idea in which event/command to look for it

subtle granite

its when i play a song when i got another one going to add it to the q

waxen wedge

Then look for the embed in all parts of your code that get called in that case (not just this one file in which it definitely didn’t happen)

subtle granite

13/06/2022, 17:41:27 -> {"channel":2064,"debugOutput":{"session":"main","output":" ^\r\n\r\nError: Cannot find module 'node:events'\r\nRequire stack:\r\n- /home/runner/lavamusic/node_modules/discord.js/src/client/BaseClient.js\r\n- /home/runner/lavamusic/node_modules/discord.js/src/index.js\r\n- /home/runner/lavamusic/src/structures/MusicClient.js\r\n- /home/runner/lavamusic/index.js\r\n\u001b[90m at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)\u001b[39m\r\n\u001b[90m at Function.Module._load (internal/modules/cjs/loader.js:667:27)\u001b[39m\r\n\u001b[90m at Module.require (internal/modules/cjs/loader.js:887:19)\u001b[39m\r\n\u001b[90m at require (internal/modules/cjs/helpers.js:74:18)\u001b[39m\r\n at Object.<anonymous> (/home/runner/lavamusic/node_modules/\u001b[4mdiscord.js\u001b[24m/src/client/BaseClient.js:3:22)\r\n\u001b[90m at Module._compile (internal/modules/cjs/loader.js:999:30)\u001b[39m\r\n\u001b[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)\u001b[39m\r\n\u001b[90m at Module.load (internal/modules/cjs/loader.js:863:32)\u001b[39m\r\n\u001b[90m at Function.Module._load (internal/modules/cjs/loader.js:708:14)\u001b[39m\r\n\u001b[90m at Module.require (internal/modules/cjs/loader.js:887:19)\u001b[39m {\r\n code: \u001b[32m'MODULE_NOT_FOUND'\u001b[39m,\r\n requireStack: [\r\n \u001b[32m'/home/runner/lavamusic/node_modules/discord.js/src/client/BaseClient.js'\u001b[39m,\r\n \u001b[32m'/home/runner/lavamusic/node_modules/discord.js/src/index.js'\u001b[39m,\r\n \u001b[32m'/home/runner/lavamusic/src/structures/MusicClient.js'\u001b[39m,\r\n \u001b[32m'/home/runner/lavamusic/index.js'\u001b[39m\r\n ]\r\n}\r\n"}}
13

dusty needleBOT

Tag suggestion for @subtle granite:
Codeblocks:
```js
const Discord = require("discord.js");
// further code
```
becomes

const Discord = require("discord.js"); 
// further code

Inline Code:
`console.log('inline!');` becomes console.log('inline!');

waxen wedge

But it looks like you should update node, you‘re on an old version djs doesn’t support

subtle granite

how do i update the node?

dusty needleBOT
subtle granite

its running on replit

waxen wedge

Definitely Not a good host for discord bots. but I‘m sure you can find out how to switch node version on replit, just not djs related anymore

subtle granite

this error again
DiscordAPIError: Invalid Form Body
embeds[0].description: This field is required
at RequestHandler.execute (/home/runner/lavamusic/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/lavamusic/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async TextChannel.send (/home/runner/lavamusic/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:172:15) {
method: 'post',
path: '/channels/972518177114296381/messages',
code: 50035,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [Array],
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}

final brook

i'm using ytdl-core with djs voice. However, when i try to stream links which's live. i get the error:
AudioPlayerError: Did not find the EBML tag at the start of the stream.

waxen wedge
waxen wedge
heavy sage

How do I fix The operation was aborted?

dusty needleBOT

Tag suggestion for @heavy sage:
AbortError: The user aborted a request.
A request took longer than the specified restRequestTimeout (15 seconds default), and was aborted to not lock up the request handler.
• This can be caused by an internal server error on Discord's side, or just a slow connection.
• In case of a slow connection, the restRequestTimeout option in ClientOptions can be increased to prevent future AbortErrors.

runic sundial

Hello I come here because my bot doesn't play the audio I give him even if it connects to the voice channel. Sadly I need to go bed soon and I hope I will not annoy anyone because I need to go.
Here is my code
https://pastebin.com/ynHvq8sn

Thank you in advance

finite grotto
runic sundial

One time I tried to open an mp3 and it didn't work so I think it's not that, there is absolutely no error...and I put console log everywhere and everything was executed so.... I can't find any solution...

finite grotto
runic sundial

Well if with an mp3 loaded with fs didn't worked I thought the problem couldn't be from the spdl module

The bot just doesn't play audio

finite grotto

mb I thought you meant you were checking that spdl worked by streaming to a file, then reading the file didn't work
how about the other questions then?

runic sundial

Well I already tried to solve any of those issues but.... nothing and sadly I need to go...

Thanks and good night

lyric sable

I have that same problem

lyric sable

i didn't get any errors

stoic thunder

How do I move people into a different voice chat?

finite grotto
dusty needleBOT

Documentation suggestion for @stoic thunder:
method VoiceState#setChannel()
Moves the member to a different channel, or disconnects them from the one they're in.

stoic thunder

That works, now how do I move everybody inside a voice channel to another one?

subtle granite

i addded
const player = createAudioPlayer();
and
player.play(stream, {seek: 0,volume:1})
but error
TypeError: Cannot read properties of undefined (reading 'once')

icy maple
dusty needleBOT
heavy sage
heavy sage

looks like it my host problem pikaOh

mystic fable

how to change volume of audiosource?

finite grotto
mystic fable

any idea why player stops even though the song is not over?

  player.on('idle', () => {
              console.log(queue.length)
              if (queue.length > 0) {
                let song = queue.shift();
                let createEmbed = 
...

it just randomly stops

zealous blade
    console.log("AAA")
})```
doesnt execute console.log("AAA"), when joining a channel
zealous blade

Thx

subtle granite
mystic fable
PlayerError: [PlayerError] Cannot play a resource that has already ended.

ideas?

fervent estuary

if u want to replay a song create a new resource

there youre trying to play an already played resource

subtle granite
const Discord = require('discord.js');
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const { joinVoiceChannel } = require('@discordjs/voice');
const { createAudioPlayer,createAudioResource } = require('@discordjs/voice');
const player = createAudioPlayer({
});


module.exports = {
    name: 'play',
    aliases: ['p'],
    run: async (client, message, args) => {
     const voicechannel = message.member.voice.channel;
     if(!voicechannel) return message.reply(`you must be in a voicechannel to use this commmand`)
     if(!args[0]) return message.reply(`Please provide link you want me to play`)
     const connection = await joinVoiceChannel({
        channelId: voicechannel.id,
        guildId: message.guild.id,
        adapterCreator: message.channel.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: 'audio'});
            resource = createAudioResource(stream, { inlineVolume: true });
            resource.volume.setVolume(100);
         player.play(resource)
        
            client.on('finish', ()=>{
                voicechannel.leave();
            });
            await message.reply(`:thumbsup: Now playing ***${video.title}***`)
        }else {
            message.reply(`No video was founded`)
        }
    }
  }```
 the error is that no errors in console  but not playing anything
waxen wedge
subtle granite

is it same as like ytdl?

whole flare
loud sinew

So i have a weird problem - i have a music bot that plays radio stations, it has 10 radio stations to choose from, but 2 of them don't play anything. The weird thing is that if i switch to a different radio station and then back to the bugged one, it starts playing. I'm very confused, is the link broken or what might be the issue? This is so weird i dont know how to even approach fixing this lmao

fervent estuary

does it happen when switching from certain stations or randomly?

loud sinew
fervent estuary

does that happen every time?

and when exactly is the first time? after every restart?

mystic fable
const track = await client.player.search(query, {
    requestedBy: message.author
}).then(x => {
  console.log(x.playlist != null)
  if(x.playlist == null) return x.tracks[0]
  else 
  {
    queue.addTracks(x.tracks);
    console.log(x.tracks.length)
    return x.tracks[0]
  }
});
if (!track) return await message.channel.send({ content: `❌ | Track **${query}** not found!` });

if(track.playlist == undefined || track.playlist == null) queue.play(track);
else queue.play()

what I have so far..

Playing a single track works, but when trying to add a playlist, it gives errors

pulsar agate

Hey, whenever i play a local mp3 file on Windows, it works as expected. However, when i try to run the same code from a Debian machine, the bot will join the channel and then immediately leave (its coded to leave when the audio is done playing). Both machines have ffmpeg installed and the same dependencies. What could be the problem? Thanks

Dependency report from the Debian machine:

--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.10.0-dev
- prism-media: 1.3.2

Opus Libraries
- @discordjs/opus: 0.7.0
- opusscript: 0.0.8

Encryption Libraries
- sodium-native: not found
- sodium: 3.0.2
- libsodium-wrappers: 0.7.10
- tweetnacl: 1.0.3

FFmpeg
- version: 4.3.4-0+deb11u1
- libopus: yes
--------------------------------------------------
loud sinew
calm solstice
spice flint

how to check if members in voice room on AudioPlayerStatus.Idle

south lark

When using voice receive, are there any issues I should be made aware of when trying to receive audio in a sharded bot with multiple servers receiving audio at the same time? I've had some issues with the bot only appearing to be able to listen to one voice at a time and rapidly switching between the multiple by quickly ending when the person is speaking despite them speaking continuously the whole time.

loud sinew
lyric sable

How I solve this

pseudo forum
lyric sable

thx

I suddenly got this error while playing the song:```
AudioPlayerError: aborted
at connResetException (node:internal/errors:692:14)
at TLSSocket.socketCloseListener (node:_http_client:414:19)
at TLSSocket.emit (node:events:539:35)
at node:net:709:12
at TCP.done (node:_tls_wrap:582:7) {
resource: AudioResource {
playStream: OggDemuxer {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_remainder: null,
_head: null,
_bitstream: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: [Function: bound onwrite]
},
edges: [ [Object], [Object] ],
metadata: null,
volume: undefined,
encoder: undefined,
audioPlayer: AudioPlayer {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_state: [Object],
subscribers: [Array],
behaviors: [Object],
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
},
playbackDuration: 44700,
started: true,
silencePaddingFrames: 5,
silenceRemaining: -1
}
}

calm solstice
loud sinew

also you should probably do player.stop() after destroying the connection

calm solstice
pseudo forum
calm solstice

was gonna say

loud sinew
loud sinew
pseudo forum why?

in his case he doesnt need the player to exist after the connection is destroyed, so you use .stop() to prevent memory leaks

pseudo forum
calm solstice
loud sinew
calm solstice

sorry

loud sinew
pseudo forum
calm solstice

ty

loud sinew

besides it wont run on the callback, it will run when the even listener is created

pseudo forum

didn't get wdym but I know that what I sent works

lyric sable
whole flare
lyric sable
ruby remnant

Disconnecting bot after done finished playing mp3 wav audio file

player.on(AudioPlayerStatus.Idle, () => {connection.disconnect()})
frank kelp

no

waxen wedge

Sure there is, just none djs itself supports

subtle granite
unreal pendant

Hey im trying to play audio in a voice channel, the bot is joining the channel but it is not playing anything, it has some mute icon that i cannot seem to get rid of.

Here is the code that i call when executing a slash command:

    const connection = joinVoiceChannel({
        channelId: channel.id,
        guildId: channel.guild.id,
        adapterCreator: channel.guild.voiceAdapterCreator,
    });

    const audioPlayer = new AudioPlayer();
    const stream = createReadStream(join(__dirname, 'audio.ogg'));
    const resource = createAudioResource(stream, {
        inputType: StreamType.OggOpus,
    });

    const subscription = connection.subscribe(audioPlayer);

    if (subscription) {
        audioPlayer.play(resource);
    }

    intr.reply('playing audio');

My dependency report looks like this:

--------------------------------------------------
Core Dependencies
- @discordjs/voice: 0.10.0-dev
- prism-media: 1.3.2

Opus Libraries
- @discordjs/opus: 0.7.0
- opusscript: not found

Encryption Libraries
- sodium-native: not found
- sodium: not found
- libsodium-wrappers: 0.7.10
- tweetnacl: not found

FFmpeg
- version: n5.0
- libopus: yes
--------------------------------------------------

I have the GUILD_VOICE_STATES Intent and i have the Connect and Speak voice permissions. I also dont get any errors and when i log the audio player state changes it switches to playing but it never goes back to idle

stoic sequoia

I don't see a mute sign it just deafen

unreal pendant

If i hover over it, it shows a tooltip "Input and Output disabled"

unreal pendant

So what fixed it was adding inlineVolume: true

const resource = createAudioResource(stream, {
    inputType: StreamType.OggOpus,
    inlineVolume: true
});

Does someone know why?

stoic sequoia

so volume wasn't there

fiery blade
unreal pendant
fiery blade
wicked gale

can i count voice chat time

fiery blade
solemn onyx

What is the group suppose to be in reference to the joinConfig?

fiery blade

default is "default" and I don't know if it's even useful

solemn onyx

So just setting it to "default" is enough?

fiery blade

yeah for anything you want to do

solemn onyx

Very blessed, thank you 🙏

fiery blade

i guess you could use it for tracking voice connections

south lark

Is voice receiving capable of working in multiple servers in multiple different channels at once? I'm having problems where it seems when more than one server is sending audio for the bot to receive at once things start to break and it starts to cut off receiving despite the user still talking and then restarts it again. I've been asking about this for a while, any solution?

wicked gale
rotund wave

I wrote a function with DiscordTTS. (DiscordTTS is the module that converts text to speech) when I run the function, speak("hi you can call me friday", user) hi you can call me friday is interrupted. (it works normally when I do it without function). what would be the reason?

async function speak(words, user) {
    const stream = discordTTS.getVoiceStream(words);
    const player = createAudioPlayer();
    const resource = createAudioResource(stream, {
        inputType: StreamType.Arbitrary
    });
    const connection = joinVoiceChannel({
        channelId: user.member.voice.channel.id,
        guildId: user.guild.id,
        adapterCreator: user.guild.voiceAdapterCreator
    });

    player.play(resource);
    connection.subscribe(player);

    player.on(AudioPlayerStatus.Idle, () => {
    })
}```
subtle granite

how can I server mute someone ?

dusty needleBOT

Documentation suggestion for @subtle granite:
method VoiceState#setMute()
Mutes/unmutes the member of this voice state.

ivory sage

Why is djs voice archived on Github?

waxen wedge
ivory sage
fiery blade

Because UDP is used for both receiving and transmitting voice data, your client must be able to receive UDP packets, even through a firewall or NAT (see UDP Hole Punching for more information).

fiery blade

Yes

static coral

I have the Intents.FLAGS.GUILD_VOICE_STATES, package installed, and the bot has administrator permissions

vagrant wagon

Hello guys, i want to make a function that if the bot gets disconnected from a voice channel it automatically does smth. But i don't get my Bot to run, can any1 help me?

dusty needleBOT

Tag suggestion for @vagrant wagon:
To help you we need more information:
• What are you trying to do?
• What is your code?
• What errors and debug logs do you have?

cursive sapphire

hey guys, i have no idea about how to play an audio in a voice channel😔can anyone gimme an example code or explain about that?

dusty needleBOT

Suggestion for @cursive sapphire:
guide Library: Voice Connections
read more

waxen wedge

Start here and follow that voice guide

open tulip

how can I disconnect from vc?

whole flare
cursive sapphire
open tulip how can I disconnect from vc?
const { getVoiceConnection } = require("@discordjs/voice"); // import the required module

let connection = getVoiceConnection("put your guild id here"); // get the connection of a guild

connection.destroy(); // so ".destroy()" will make the bot disconnect from the vc!```
fiery blade

For context: disconnect simply leaves the vc, and the connection can be used again while destroy will.. destroy the connection (and disconnect). Use destroy if you don't need to reuse the connection

jaunty fiber

Hello everyone, how I can use discordjs/voice with multiple bots? I have 2 discord clients( one for radio 24 / 7, second is music bot ) and when I use joinVoiceChannel it connects only the first one. There seems to be no way to choose which discord client should be connected

waxen wedge

And make sure to get the adapterCreator from the correct client

fiery blade

so? what's the issue

it's a logic error then

If you only care when it joins a stage channel (to make sure joining from a different channel works) , just remove the check for oldState here;

    if (!oldState.channelId && newState.channelId) {

Also you might aswell just do this when you actually call joinVoiceChannel, it seems like that would be easier

Oh dude
These params are backwards

it's (oldState, newState) not (newState, oldState)

toxic abyss

joinVoiceChannel.reciever.createStream isn't a function? Was it moved? v 13.8 with discordjs/voice

fiery blade

sounds like a function from v12 or something else

fwiw connection.receiver.subscribe(userid, { opts }) returns an audioreceivestream so maybe that's the equivalent?

south lark

How do larger bots which utilize voice (like music bots and other things) deal with scaling? I've been having some issues with scaling with my bots. The audio quality just seems to go downhill and lag and stutter no matter what I do. Any advice?

rose helm

The general rule when making integrated music bots is to shard and cluster sooner and smaller. ~1500 was usually the baseline to start sharding because that's roughly when you'd run into single core performance issues. This can be ignored when using an approach like LavaLink as you can spread the audio nodes across many servers and worry about only meeting the needs of your shards when they would normally run into single core performance issues unaffected by audio de/encode

south lark
rose helm

I'd still probably use something similar unless you're doing something like radio

You can only really optimize when you do something like radio when you have 1 resource player playing on multiple connections

south lark

I'm still a little unclear about what to do though. Do I need something to load it on an external thing and just send it to the bot somehow HmmSip
Any recommendations on where to start?

rose helm

It kinda falls under "music", so the basic concept is to just separate your audio streaming code from your bot code. Something like LavaLink might be a bit overkill and have too much overhead for what you want to do. You'd be better off making your own proprietary system where you tell a service to play audio. In this case though, you could really benefit from looking at Volcano's source code, specifically this:
https://github.com/AmandaDiscord/Volcano/blob/main/src/worker.ts
Not that you need to copy the whole thing, but a lot of the stuff is kinda stuff I had to do to get a stable experience. Might be a bit hard to traverse without comments

south lark

Thank you, I will take a look :)

violet nacelle

please, help me with this error while trying to install @discordjs/opus

finite grotto
violet nacelle
finite grotto
violet nacelle

and what year I need to put?

finite grotto
violet nacelle

okay, ty

the year is 2022 right?

finite grotto

yes

wraith karma

are there any up to date guides on how to make a music bot like rythm or fredboat? i have no clue how to make one myself

fiery blade

i think we dropped our music bot example so that people don't go breaking youtube tos following our lead, but it probably still works

wraith karma

i just want one for my server with me and my friends so that we only need 1 bot with all the features we want in our server

fiery blade

not sure what that has to do with what i said, music bots inherently break tos if they scrape youtube, so we don't support doing it, but the old example that was removed probably still works

wraith karma

oh

how is it against youtubes tos to play youtube videos from a discord bot? you can already play videos fine by just pasting the link in chat

fiery blade

"The following restrictions apply to your use of the Service. You are not allowed to... use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)"

I don't know fully, I didn't pay attention to the music bot drama, u can prob ask in general and get a better response

wraith karma

huh, mee6 still has a music addon and its not being banned or anything

shell fern

Hi, how do I detect if my bot has been forcefully disconnected by an admin?

finite grotto
shell fern

Ah

Ok thanks!

stoic thunder

is it possible to basically record a voice chat through the bot?

finite grotto

yes

stoic thunder

Don't worry this is consensual, it is for a DnD session for the recaps.

stoic thunder
finite grotto

not from a Jedi
<VoiceConnection>.receiver.subscribe(<userId>) returns an opus packet stream

stoic thunder

can i transcribe it into a mp3 and do discord bots have a upload limit?

and is userid to a specific user or is it just the bot's user id

fiery blade

specific, and yes they have an upload limit

stoic thunder

planning on doing a /recap command that just sends the recording of the session

finite grotto
stoic thunder

also is possible to record while the bot is playing music

fiery blade

ya

stoic thunder

ok, i know this sounds kinda sus but promise it is consensual

stoic thunder
finite grotto

should be able to record multiple users at a time

stoic thunder

cause vsc is telling me ```js
(method) VoiceReceiver.subscribe(userId: string, options?: Partial<AudioReceiveStreamOptions> | undefined): AudioReceiveStream
Creates a subscription for the given user id.

@param target — The id of the user to subscribe to

@returns — A readable stream of Opus packets received from the target

or is it a optional parameter?

finite grotto

it's not an optional parameter
you'd need to subscribe multiple times

fiery blade

that would return a different stream

stoic thunder

oh so like ```js
for (let i = 0; i < interaction.member.voice.channel.members.length; i++) {
connection.receiver.subscribe(interaction.member.voice.channel.members[i].id);
}

finite grotto

sure

stoic thunder

bit lost on this one but is there like a good sample i could follow?

fiery blade

ignore the install instructions, they're wrong, you need to use yarn if you want to use that

stoic thunder

alright

thanks, but can it record multiple people

fiery blade

yes and no

the issue with recording multiple people is that you can't just merge opus packets, so you have to get individual streams of people talking, then do stuff with that

"can it record multiple people" - it will record every time a subscribed users speaks, then pipe that stream into an ogg file when they stop speaking

and also it's a bit hard to tell if people aren't talking, i guess you'd need to append silence frames for every time they aren't in order to have it match up correctly? (unless you use manual end behavior)

hardest part might even be knowing when to merge them, because you'd have one user start speaking, then it'd create the stream for them, even if it's appending silence frames, when another user starts speaking ffmpeg won't know to merge them so that user1 starts speaking, stops, then user2 starts speaking, it would just merge them and they'd be beginning at the same time

ivory zinc
fiery blade

You need either ffmpeg (not npm) or ffmpeg-static (npm)

ionic eagle

how can i get a sound of user in vocal channel ?

fiery blade
subtle granite

i run /join to try make the bot join vc, it says "the application did not respond" goes offline then back online, eventually throws an abort error then goes offline?

nvm i realised the issue

waxen wedge
subtle granite

pretty sure i weren't trying to reply to /join, i can show the code if you want

waxen wedge

You need to acknowledge the command though. Else discord will always show the application did not respond

green vigil


} else if 
(commandName === 'dominiontheme') {
  interaction.channel.send('Joined Voice Channel')
  const connection = joinVoiceChannel({
  channelId: interaction.member.voice.channel.id,
  guildId: interaction.guild.id,
  adapterCreator: interaction.guild.voiceAdapterCreator

})
let resource = createAudioResource(("linkhidden"), { inlineVolume: true })
resource.volume.setVolume(1)

connection.subscribe(player);
player.play(resource);
interaction.channel.send("Now Playing: **Dominion Theme**")
console.log("Playing, Dominion Theme");

How can I make this so if the bot loses connection for playing audio it will resume playing

fiery blade

oh I get what you mean

yeah i'm not really sure that's possible without modifying internals of the library if it doesn't already resume audio. you'd need to persist resources and track when it actually dropped so you know where to begin playing again, then when the connection drops (and there isn't an event or anything for this) you start playing the resource again at a specified time

green vigil

Alright

Would hosting it on my computer be a issue, I got good network and all

fiery blade

No, hosting it yourself wouldn't be a problem, but if your computer does lose connection (whether it be powering off, or the internet drops) the bot will die too

sterile spire

Hi I have a question guys

I'm working on a discord bot which play radio stream and I'm using ffmpeg-static for it. Is there a way to set a bitrate or sound quality in audio resource in v13 ?

fiery blade

technically no, but you can do it with prism-media

sterile spire

okay I will that thank you

I will look*

fiery blade

If you create an opus stream using prism-media , it will have the method setBitrate

or, more correctly, if you pipe a stream into an opus stream

subtle granite

im trying to make the bot leave the vc its in, however its saying that connection.disconnect() isn't a function??

fiery blade
subtle granite

huh

fiery blade

what is channel.guildId coming from?

languid quail
fiery blade

nevermind, just check if connection exists before using the methods

subtle granite

alr ty

upbeat spindle

how to play mp3 file on the current voice channel of bot

fiery blade
upbeat spindle
upbeat spindle

ty

civic furnace

can someone point me to the "joinVoiceChannel" method in the docs?

dusty needleBOT

Documentation suggestion for @civic furnace:
method joinVoiceChannel
Creates a VoiceConnection to a Discord voice channel.

civic furnace

thank you! Idk why I couldn't seem to find it

fiery blade

you have to switch to "voice" on the top left

golden path
const connection = getVoiceConnection(interaction.guild.id);
connection.destroy();

returns:

TypeError: Cannot read property 'destroy' of undefined
fiery blade

check if it exists i guess

golden path

that part of the code only runs if it exists but logging it only returns undefined

fiery blade

well i doubt it only runs if it exists then

golden path

you've got a point there

I've tested it with audio playing from the bot when I check for a connection and still get nothing

fiery blade
fiery blade
golden path
fiery blade
golden path handled via distube

there's probably a distube method for that, but it looks like they changed the group to client.user.id so if you really must use this, you can use getVoiceConnection(guild.id, client.user.id)

i would recommend checking out their discord and asking if there's a native get connection method

golden path
fiery blade

expect it to break functionality though

storm gate
fiery blade

install those desktop build tools from vs

storm gate

thank you so much ily 😭 😍

long musk

The function <voiceChannel>.receiver.createStream(), is available in Discord.js v13?

pseudo forum
long musk
pseudo forum

it is but dunno how

long musk
subtle granite

I entered sound with module @discordjs/voice, but how do I turn on the microphone?

?????????????????????????????

radiant ocean

that will definitely not make anyone answer faster

heavy sage

Im trying to make a play command in lavalink using erela.js

module.exports = {
name: 'play',
developer: true,
run: async(client,message,args) => {
    const { channel } = message.member.voice;

    if (!channel) return message.reply('you need to join a voice channel.');
    if (!args.length) return message.reply('you need to give me a URL or a search term.');
    const player = client.player.create({
      guild: message.guild.id,
      voiceChannel: channel.id,
      textChannel: message.channel.id,
    });
    if (player.state !== "CONNECTED") player.connect();
    const search = args.join(' ');
    let res;
   
     res = await player.search(search, message.author);
      if (res.loadType === 'LOAD_FAILED') {
        if (!player.queue.current) player.destroy();
        throw res.exception;
      }
     player.queue.add(res.tracks[0])
         message.reply('Added track to the queue!')
            await player.play();
      }
}       

The thing is that it sends the track to the lavalink server and return it, add it to the queue but doesnt play music

I adddd the error event listener but no errors

sterile spire

@heavy sage firstly, channel must be message.member.voice.channel . Your code is getting the voice state of member and I don't know that you configure the players' functions correctly but you should use connection.subscribe to play something on voice channel.

lofty condor

How I get the current channel where the bot is in?
with the player

languid quail
lofty condor
languid quail

well that doesn't really make much sense

lofty condor

OR when I can check if the bot is connected?
When the player connects to the channel?

After createAudioResource or earlier

fiery blade

there is no player connecting, but there is a subscription event for connection and a playing status for the player

heavy sage

I dont know how im gonna do connection.subscribe with that player...

fiery blade

you are using methods that dont exist

sterile spire
storm gate

Is there any way to avoid lag when listening to music in my bot?

rose helm

use worker threads

haughty beacon

How can I change the volume of the stream during playing?

frosty dome

why my bot join to voice channel defined by defaultt

pseudo forum
haughty beacon

Is there a way to have the streamTime in d.js 13 ? (The image is d.js 12)

sweet valve

anyone knows how to fix this:
Error: Cannot perform IP discovery - socket closed

reject Promise

fiery blade
fiery blade
dreamy drum
subtle granite
client.guilds.cache.forEach((guild) => {
    if(guild.me.voice.channel){
      guild.me.voice.channel.leave()
    };
});```
I try to leave connect voice channel when i start my bot in all guilds, i have do this, but when my bot is in a voice channel and execute `guild.me.voice.channel.leave()` he return me `leave is not a function` but `guild.me.voice.channel` successfully returned the voice channel object.. how can i do ?
waxen wedge

How did your bot join the VC?

subtle granite

with a package discord-player to listen music

discord opus & ffmpeg

subtle granite

is not a problem with the package

is a problem when i try to simply leave the vc bc i try to execute this when my bot start

waxen wedge

Yes, but to leave a channel you‘d do the same as to join one, but since you apparently don’t join with djs functions it‘s not djs related

sterile spire
dark sinew

when i write /play, the bot joins the voice channel but it doesnt play anything. Why is that?```js
const player = createAudioPlayer();

const connection = joinVoiceChannel({
channelId: interaction.guild.members.cache.get(interaction.member.user.id).voice.channelId,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator
})

const resource = createAudioResource("C:\Users\jkant\OneDrive\Documents\Coding\discord\tc-bot\song.mp3");
player.play(resource);

connection.subscribe(player);```Discord is not showing any error

lapis prawn

pepeping

icy maple
dark sinew
icy maple
dark sinew

oh

so i use forward slashes?

icy maple

Escape the back slashes

waxen wedge

\\ instead of \

icy maple

I would prob just use path.join(__dirname, relativePath) instead of an absolute one

dark sinew

ohh

like this?js const resource = createAudioResource("C:\\Users\\jkant\\OneDrive\\Documents\\Coding\\discord\\tc-bot\\song.mp3");

icy maple

That should work

dark sinew

lemme try

dark sinew
icy maple

Nvm, I see it

dark sinew

yea...

icy maple

Can you log fs.existsSync(…) using the path you provided?

dark sinew

sure

bro it worked :_)
it was cause i was stupid and took out the connection.subscribe

icy maple

Well, it shouldn’t change anything, you can remove the log

Oh

dark sinew
subtle granite

How to record voice from vc after user uses record command.

viral coral

I'm using a really basic portion of code to join a VC but I can't seem to figure out what's the issue. The bot has admin permissions. I get an err: TypeError: Cannot read properties of undefined (reading 'set') on the line where I define the connection.

        const channel = msg.member.voice.channel
        const connection = joinVoiceChannel({
            channelId: channel.id,
            guildId: channel.guild.id,
            adapterCreator: channel.guild.voiceAdapterCreator,
        });
fiery blade
viral coral
fiery blade
viral coral
fiery blade Then I guess it could be from an internal function, what's the entire error?
TypeError: Cannot read properties of undefined (reading 'set')
    at C:\Users\ryanv\music bot\node_modules\discord.js\src\structures\Guild.js:1380:34
    at new VoiceConnection (C:\Users\ryanv\music bot\node_modules\@discordjs\voice\dist\index.js:1377:21)
    at createVoiceConnection (C:\Users\ryanv\music bot\node_modules\@discordjs\voice\dist\index.js:1671:27)
    at joinVoiceChannel (C:\Users\ryanv\music bot\node_modules\@discordjs\voice\dist\index.js:1694:10)
    at Object.execute (C:\Users\ryanv\music bot\commands\play.js:17:28)
    at Client.<anonymous> (C:\Users\ryanv\music bot\index.js:49:66)
    at Client.emit (node:events:390:28)
    at MessageCreateAction.handle (C:\Users\ryanv\music bot\node_modules\discord.js\src\client\actions\MessageCreate.js:26:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\ryanv\music bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\ryanv\music bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31) ```
Promise {
  <rejected> TypeError: Cannot read properties of undefined (reading 'set')
      at C:\Users\ryanv\music bot\node_modules\discord.js\src\structures\Guild.js:1380:34
      at new VoiceConnection (C:\Users\ryanv\music bot\node_modules\@discordjs\voice\dist\index.js:1377:21)
      at createVoiceConnection (C:\Users\ryanv\music bot\node_modules\@discordjs\voice\dist\index.js:1671:27)
      at joinVoiceChannel (C:\Users\ryanv\music bot\node_modules\@discordjs\voice\dist\index.js:1694:10)
      at Object.execute (C:\Users\ryanv\music bot\commands\play.js:17:28)
      at Client.<anonymous> (C:\Users\ryanv\music bot\index.js:49:66)
      at Client.emit (node:events:390:28)
      at MessageCreateAction.handle (C:\Users\ryanv\music bot\node_modules\discord.js\src\client\actions\MessageCreate.js:26:14)
      at Object.module.exports [as MESSAGE_CREATE] (C:\Users\ryanv\music bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
      at WebSocketManager.handlePacket (C:\Users\ryanv\music bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
``` (full err)
fiery blade
viral coral
fiery blade
viral coral 13.7.0

🤔 are you changing anything about the client? the error is implying one of the client managers is undefined

or perhaps, is this sharded?

viral coral
fiery blade

Wtf lol

try logging client.voice just before you try to make a connection

viral coral
fiery blade

hmm that's not right

viral coral
viral coral

Alright I'm gonna sleep on this, hopefully find a solution with a fresh mind, thanks for your help up until now

fiery blade

When you come back feel free to ping but: are there any other dependencies that could be causing a clash? npm list discord.js anything that modifies voice like another npm package such as discord-player, and whatever the other ones are

subtle granite

Kk

dusty needleBOT
viral coral
shrewd compass

How do ik if any player exist or not in that guild when i have declared player anywhere else which isn't accessible in a different thing?

Like can I get player as we get connection?

const connection = getVoiceConnection(interaction.guildId);

SO

const player = getVoicePlayer(interaction.guildId);

Is this valid case?

pseudo forum

check the doc

shrewd compass

I can't find anywhere there

pseudo forum

yes, getVoicePlayer doesn’t exist

pseudo forum
shrewd compass

Oh ic

Thanks it works!

serene bronze

For some reason my bot isn't joining voice and is printing no errors...

const { SlashCommandBuilder } = require('@discordjs/builders');
const dcVoice = require('@discordjs/voice');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('join')
        .setDescription('Join your voice channel.'),
    async execute(interaction) {
        channel=interaction.member.voice
        const connection = dcVoice.joinVoiceChannel({  
            channelId: channel.id,  
            guildId: interaction.member.guild.id,  
            adapterCreator: channel.guild.voiceAdapterCreator  
        });
    },
};
nova rampart

(I’m on mobile so formatting is bad, sorry)

Also make sure you have the right intents

serene bronze

It works now

olive musk

i'm trying to pipe the discord voice channel to an express server, how can i do that ? i've tried this but it didn't work```app.get(/, async (req,res) => {
try {
const channel = await client.channels.cache.get('818300593058611203');
const connection = joinVoiceChannel({
channelId: channel?.id,
guildId: channel?.guild?.id,
selfDeaf: false,
selfMute: true,
adapterCreator: channel?.guild?.voiceAdapterCreator,
});

const receiver = connection.receiver.subscribe();
receiver.pipe(res); })```

please ping me if you know how

like i need the connection.receiver.subscribe to return a stream

dark sinew

why am i getting this error?Error: Cannot perform IP discovery - socket closed

i suspect it is coming from this js const resource = createAudioResource((path.join(__dirname, "..", "..", "songs") + `/${id}.mp4`));

slender sparrow

how that is related, you are trying to join voice channel not creating resource. the problem is you cant perform ip discovery. most likely your firewall issue

hearty whale

Can someone explain me how does @discord.js/opus work, please? 🙂

clever mortar

Can someone help me make a voice bot/music bot that would join vc channels and play music of the user choice

using slash commands

shrewd compass
shrewd compass
pseudo forum
subtle granite

why isnt the voice documentation loading?

everything else works perfectly fine

languid quail
subtle granite
fiery blade
elfin kayak

What is wrong with this code? the bot is connecting to the voice channel but it doesn't play anything or gives an error

fiery blade
elfin kayak

can you show me how to do this?

icy maple

connection.subscribe(player)

acoustic kestrel

yt-dlp-wrap execStream() error
problem:

error on second and above songs, (first song without errors)
code:

resourse() {
    this.soundStream = yt_dlp.execStream([
        "-f", "bestaudio[acodec=opus]/worst[acodec=opus]",
        "-c", "",
        "-i", "",
        "--audio-quality", "0",
        "-r", "100K",
        "-R", "infinite",
        "-o", "-",
        "--ffmpeg-location", "C:\\ffmpeg\\bin\\ffmpeg.exe",
        "ytsearch:", this.songs[0].url
    ]);
}
stream() {
    if (this.isPlaying == false) {
        this.isPlaying = true;
    }
    this.resourse();
    this.soundStream.on("error", e => {
        console.log(e);
    });
    this.audioPlayer.play(createAudioResource(this.soundStream));
    this.audioPlayer.on("idle", () => {
        this.songs.shift();
        if (this.songs.length == 0) {
            this.soundStream.destroy();
            // this.soundStream.kill();
            this.disconect();
        } else {
            this.soundStream.destroy();
            this.resourse();
            this.audioPlayer.play(createAudioResource(this.soundStream));
            this.controller("update");
        }
    });
}

error code:

R [Error]:
Error code: 1

Stderr:
ERROR: [generic] '' is not a valid URL. Set --default-search "ytsearch" (or run  yt-dlp "ytsearch:" ) to search YouTube
ERROR: [generic] '' is not a valid URL. Set --default-search "ytsearch" (or run  yt-dlp "ytsearch:" ) to search YouTube
[generic] ytsearch:: Requesting header
WARNING: [generic] Could not send HEAD request to ytsearch:: <urlopen error unknown url type: ytsearch>
[generic] ytsearch:: Downloading webpage
ERROR: [generic] Unable to download webpage: <urlopen error unknown url type: ytsearch> (caused by URLError('unknown url type: ytsearch'))
[youtube] QJJYpsA5tv8: Downloading webpage
[youtube] QJJYpsA5tv8: Downloading android player API JSON
[info] QJJYpsA5tv8: Downloading 1 format(s): 251
[download] Destination: -
[download] 100% of 3.44MiB in 00:35

    at YTDlpWrap.createError (...)
    at ChildProcess.<anonymous> (...)
    at ChildProcess.emit (node:events:537:28)
    at maybeClose (node:internal/child_process:1091:16)
    at ChildProcess._handle.onexit (node:internal/child_process:302:5) {
  resource: T {
    playStream: OggDemuxer {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      _remainder: null,
      _head: null,
      _bitstream: null,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: [Function: bound onwrite]
    },
    edges: [ [Object], [Object] ],
    metadata: null,
    volume: undefined,
    encoder: undefined,
    audioPlayer: B {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      _state: [Object],
      subscribers: [Array],
      behaviors: [Object],
      debug: [Function (anonymous)],
      [Symbol(kCapture)]: false
    },
    playbackDuration: 35100,
    started: true,
    silencePaddingFrames: 5,
    silenceRemaining: -1
  }
}

libs:

@discord.js/Voice
yt-dlp-wrap

echo sorrel

How do I get it to automatically exit when finished playing mp3?

                if (msg.member.voice.channel) {
                    //join
                    const conn = joinVoiceChannel({
                        channelId: msg.member.voice.channelId,
                        guildId: msg.guildId,
                        adapterCreator: msg.guild.voiceAdapterCreator
                    });
                    playSound(msg, conn);
function playSound(msg, conn) {
    const player = createAudioPlayer();
    const resource = createAudioResource(sounds[msg.content]);
    conn.subscribe(player);

    const dispatcher = player.play(resource);
    dispatcher.on("speaking", speaking => {
        if (!speaking) {
            conn.destroy()
        }
    });
}
foggy terrace
fringe forum

basically how do get it to just join a voice channel
via an eval command?

cyan bloom

I'm installing I'm but it stayed like this, is it normal? it takes about 1 or 2 minutes

loud dome

Hello I am having troubles using the @discordjs/voice module

Error: Cannot find module '/home/user/Desktop/cringe-main/node_modules/@discordjs/voice/dist/index.js'

young sail
small raptor

is it possible to have the AudioPlayerStatus default to idle? if not, what is the default?
(From what I can tell Idle isnt the default)

icy maple

What is it then?

loud dome
icy maple

Have you logged the status?

loud dome
young sail
young sail
loud dome

oops

loud dome
small raptor
icy maple Have you logged the status?

I must be logging it wrong, because this is what console.log(AudioPlayerStatus) returns:

{
  Idle: 'idle',
  Buffering: 'buffering',
  Paused: 'paused',
  Playing: 'playing',
  AutoPaused: 'autopaused'
}
loud dome

it worked @young sail

icy maple

Or idk

That’s the enum

I thought you were checking the player.state.status?

small raptor

I just did that rn, default is idle, so I guess some part of my code is faulty

fiery blade
small raptor

yea its Idle. but its kinda acting a bit weird, because e.g.

player.on(AudioPlayer.Idle, () => console.log("idle"));

doesn't work and neither does

player.on(player.state.status === "idle", () => console.log("idle"));
icy maple

The former is correct

It only runs when the player becomes idle

As in the player was in a different state before becoming idle

small raptor

well that sucks

for what im doing rn atleast lmao

icy maple

I mean, you can just run whatever you want to run when you create the player

cyan bloom

hello, i can´t download @discordjs/opus

help xd

waxen wedge
echo sorrel
subtle granite

any ideas on how i would go about getting audio from the person speaking, and logging it in the bots console as text?

fervent warren

If I am getting an audiostream from a users microphone as MediaStream and I then want to pipe it into a voice channel, do I have to re-encode it with prism FFMPEG or can I just pipe it to prism as well?

small raptor

Hey, Im having a bit of an issue here, hope someone can help me

// add to queue if already playing something
if(state === 'idle' && fileContent !== '[]' || state === 'playing') {
  // add new requests to queue
  [...] 

  i.reply({ content: 'added to queue', ephemeral: true });
}

// this right here logs once for every /play done until current track finished
player.once(AudioPlayerStatus.Idle || AudioPlayerStatus.Buffering, () => console.log('next'));

I'm trying to add URLs to a queue, which by itself works fine, let me explain:
if you do /play <url> the url will get added to the queue, you get a reply and once the player turns to "idle", the next url will be played.

the problem:
for every /play done, until the currently running resource is over, it will log "next" one time (so, if the command was run 5 times, it will get logged 5 times), I have tried adding return in front of the the i.reply(...) in the above if clause, but then it never gets to the player.once part.
Whats the best way to go from here?

I currently have all of this inside of my play.js file.

Edit: Tried the discord-player npm package instead of creating queue by myself , but seems to have the same outcome

loud dome

message.member.voice.channel.join();

why does this not work

polar mesa

Im having a issue with my bot randomly disconnecting after 10-30 seconds while it still playing muisic. Im using discord-player and this is the code ```js
if (!interaction.member.voice.channelId) return await interaction.reply({ content: "You are not in a voice channel!", ephemeral: true });
if (interaction.guild.me.voice.channelId && interaction.member.voice.channelId !== interaction.guild.me.voice.channelId) return await interaction.reply({ content: "You are not in my voice channel!", ephemeral: true });
const query = interaction.options.get("query").value;
const queue = player.createQueue(interaction.guild, {
metadata: {
channel: interaction.channel
}
});

    try {
        if (!queue.connection) await queue.connect(interaction.member.voice.channel);
    } catch {
        queue.destroy();
        return await interaction.reply({ content: "Could not join your voice channel!", ephemeral: true });
    }

    await interaction.deferReply();
    const track = await player.search(query, {
        requestedBy: interaction.user
    }).then(x => x.tracks[0]);
    if (!track) return await interaction.followUp({ content: `❌ | Track **${query}** not found!` });

    queue.play(track);

    return await interaction.followUp({ content: `⏱️ | Loading track **${track.title}**!` });
waxen wedge
polar mesa

then what should i use to play music?

waxen wedge

Whatever you want. But ask that library‘s support for support, not us

polar mesa

alright mb thanks

toxic minnow
if (this.isPlaying == false) {
    this.isPlaying = true;
}

is literally the same thing as this.isPlaying = true

nocturne igloo

the voice docs isnt opening

fiery blade
nocturne igloo

alright thanks

wicked aurora

i'm running voice in the node:latest docker container, i've added the ffmpeg package, and i'm getting this error: Error: FFmpeg/avconv not found!

wondering if there's anything else i need to do in order to make ffmpeg available to node

wicked aurora

nvm, rebuilt the container again and it worked

eager lake

Does anyone know why the AudioReceiveStream doesn't emit end/close or anything like that when I pass

end: {
    behavior: EndBehaviorType.AfterSilence,
    duration: 3000,
}

to the subscribe method?
After I stop speaking and wait 3 seconds, nothing happens. When I speak again it throws

Error [ERR_STREAM_PUSH_AFTER_EOF]: stream.push() after EOF
    at new NodeError (node:internal/errors:371:5)
    at readableAddChunk (node:internal/streams/readable:277:30)
    at AudioReceiveStream.Readable.push (node:internal/streams/readable:228:10)
    at AudioReceiveStream.push (C:\Users\soere\dev\voice\node_modules\@discordjs\voice\dist\index.js:1148:18)
    at VoiceReceiver.onUdpMessage (C:\Users\soere\dev\voice\node_modules\@discordjs\voice\dist\index.js:1324:16)
    at VoiceUDPSocket.emit (node:events:390:28)
    at VoiceUDPSocket.onMessage (C:\Users\soere\dev\voice\node_modules\@discordjs\voice\dist\index.js:311:10)
    at Socket.<anonymous> (C:\Users\soere\dev\voice\node_modules\@discordjs\voice\dist\index.js:293:48)
    at Socket.emit (node:events:390:28)
    at UDP.onMessage [as onmessage] (node:dgram:939:8) {
  code: 'ERR_STREAM_PUSH_AFTER_EOF'
}
small lantern

How would I determine that the bot has been disconnected from a voice channel

Ignore: just found what I needed in the guide

lilac rover

is there something to see the status of the player

like player.status or something to see if idle/playing or paused

nvm

slim jay

Hey, I've had a user request support for stage channels. Is this difficult to implement if I already support regular voice channels? I'm not seeing much in the docs

fervent estuary

Only thing youll have to do with stages is whether ur bot is a speaker or in the audience

other than that its identical

waxen wedge

And StageChannels don’t have TiV feature

fiery blade
toxic minnow

getVoiceConnection() doesn't work after a bot restart, is there something i can do to fix this

waxen wedge
toxic minnow

sounds about right, thx

eager lake