#archive-voice

30636 messages · Page 29 of 31

finite grotto

autogenerated docs don't like top level functions :/
just follow the info in the guide

clever siren
        const { joinVoiceChannel } = require("@discordjs/voice");
        const fs = require("fs");

        var voiceChannel = message.member.voice.channel;
        var writeStream = fs.createWriteStream("test.pcm");

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

Hello why i have this error please : 

```\node_modules\@discordjs\voice\dist\index.js:1377
    const adapter = adapterCreator({
                    ^

TypeError: adapterCreator is not a function```
finite grotto
icy maple

Isn’t voiceAdapterCreator on VoiceChannel?

Nvm

harsh kite

not getting any errors but the bot goes through my function all the way down to sending the embed but never joins the channel

it even gives the confirmation log that its playing music but it never joined the channel at all

Nvm fixed it, had ID capatilized

manic kettle

does anyone know how i can fetch a connection with the guild id?

subtle granite

mainChannel = ....channels.cache.get(...)

-TypeError: Cannot read properties of undefined (reading 'permissionOverwrites')
waxen wedge
subtle granite

um i fixed thx

players.set(interaction.guildId, player);
players.get(interaction.guildId).play(resource);```

Why do the players still share the same audio in different guild?
waxen wedge
subtle granite

So i must create new player?

waxen wedge

If you want to have seperate players playing different Audio, yes

subtle granite

well... i'll figure it out, thank you

manic kettle
waxen wedge
manic kettle

i tried const connection = getVoiceConnection(message.guild.id)

manic kettle

undefined

waxen wedge

Then you didn’t joinVoiceChannel on that guild yet

manic kettle
waxen wedge
manic kettle

after that the client.voice.adapters returns 0 entries in the map

waxen wedge

You‘d need to call joinVoiceChannel again then, because the VoiceConnection object doesn’t exist anymore

manic kettle

but what if i use the command if the bot is not in the voice channel

then it will just join and then leave

waxen wedge

Okay, where’s the problem?

quiet smelt

how can you set the timestamp of an audio resource/stream

lean osprey

How would I listen for a resource having finished playing?

brittle basin

I made so the bot to leave the voice channel when there is nobody in it, but if you have joined and the person that has been in it when the bot has joined leave, the bot does not detect you as a member and it leaves too, any ideas how to make it to continue being in the voice channel, this is the code that I have made:

client.on('voiceStateUpdate', (oldState, newState) => {
    const { getVoiceConnection } = require('@discordjs/voice')
    const connection = getVoiceConnection(oldState.guild.id)
    
        // if nobody left the channel in question, return.
        if (oldState.channelId !==  oldState.guild.me.voice.channelId || newState.channel)
          return;
  
        // otherwise, check how many people are in the channel now
        if (oldState.channel == null) return;
        if (!oldState.channel.members.size - 1) 
          setTimeout(() => {
            try {
            if (connection) connection.destroy()
            } catch (error) {
              console.log(error);
            }
           }, 1000); // (1 sec in ms)

});
tidal canyon

Hey! Im having an issuse, i try to take interaction.member.voice.channel and it returns me undefined. member.voice exists and its with my id, also have GUILD_VOICE_STATES in my flags.

waxen wedge
waxen wedge
eager parrot

Does someone have an example for receiving an opus stream from a vc using @discordjs/voice?

ionic turret
signal depot

u want it to keep playing music that no one can hear, using bandwidth and cpu resources for no reason.. ?

ionic turret

yes!

signal depot

discord.js v12 is unsupported and will stop working btw

subtle granite
vital nova

I havent really seen anything online about this, so I guess Ill ask it here.

How am I able to ask if there is no one in the voice channel then say to disconnect upon having 0 people in the channel.

slender sparrow

listen to voiceStateUpdate and check for voice members size

vital nova
slender sparrow

are channel.members.size valid? check docs if that doesnt valid

vital nova

Will do

slender sparrow

and also filter to user only. exclude bot

vital nova
slender sparrow
  • 1 to exlude your bot and allow other bot
vital nova
slender sparrow - 1 to exlude your bot and allow other bot

If I try

 if (voiceConnection.channel.members.size === -1) {
         voiceConnection.disconnect()
       }
``` I get the error of members is not defined

if I do 
```js
 if (voiceConnection.members.size === -1) {
         voiceConnection.disconnect()
       }
``` I get size is not defined
slender sparrow

not like that

vital nova
slender sparrow
if(!(VoiceChannel.members.size - 1)) {

}```
VoiceChannel here is an instance of VoiceChannel

as i said before. it should placed at voiceStateUpdate event

vital nova
slender sparrow

can you log voiceConnection?

why dont use oldState.channel.members.size ? if you on voiceStateUpdate event. (use optional chaining if you didnt catch the error properly)

subtle granite
(node:3061) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 disconnected listeners added to [VoiceConnection]. Use emitter.setMaxListeners() to increase limit```👀
slender sparrow

you have nested listeners

subtle granite
eager lake
subtle granite
pine mulch
subtle granite

Check if the connection exists before you try to destroy it

eager parrot

Does ssomeone know why node-gyp fails when installing discordjs/opus? Using yarn pnp and node 17.9.0

subtle granite

You can use opusscript instead

eager parrot

Results in prism not finding opus

rose helm

prism supports opusscript

eager parrot
subtle granite
Name: Best Music Mix ♫ No Copyright EDM ♫ Gaming Music Trap, House, Dubstep
    at Function.getInfo (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\prism-media\src\core\FFmpeg.js:143:11)
    at Function.create (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\prism-media\src\core\FFmpeg.js:156:38)
    at new FFmpeg (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\prism-media\src\core\FFmpeg.js:45:27)
    at new DisTubeStream (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\DisTubeStream.js:70:23)
    at Function.YouTube (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\DisTubeStream.js:88:16)
    at DisTubeHandler.createStream (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\DisTubeHandler.js:335:37)
    at QueueManager.playSong (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\manager\QueueManager.js:83:41)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async QueueManager.create (C:\Users\Leon\Desktop\Lion-Host Bot\node_modules\distube\dist\core\manager\QueueManager.js:45:25)
This is logged because <Queue>.textChannel is undefined
————————————————————————————————
Anti-Crash System
————————————————————————————————
reject
[object Promise]
Error: Cannot perform IP discovery - socket closed
————————————————————————————————

What is the problem?

waxen wedge

Ask distube support, not djs related

fickle gate

why is discordjs/voice repo archived?

waxen wedge
agile apex

Hey guys, how can i make my bot enter in a voice channel? I'm trying to use message.member.voice.channel.join but it's not the correct way (the error say that is not a function)

icy maple
south glade

anyone have a youtube tutorial or a website guide on how to have my bot join a vc and play a local mp3 file then disconnect once finished?

quasi turtle

Is there a way to check what someone is saying in a voice chat without a third party package

Like a speech recognition system for discord

waxen wedge
subtle granite
AudioPlayerError: Audio Codec is not OPUS ```
golden dagger

so, my bot joins the vc but isn't playing anything

    const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
    const resource = createAudioResource('/waiting.mp3')
    const connection = joinVoiceChannel({
        channelId: '964076671898644491',
        guildId: '903564467323932712',
        adapterCreator: client.channels.cache.get("964076671898644491").guild.voiceAdapterCreator,
    });
    const player = createAudioPlayer();
    player.play(resource);

    connection.subscribe(player);

no errors are showing at all

quasi turtle

You didn’t provide the directory correctly

createAudioResource(“./file”);

golden dagger

alr thanks

verbal trail
waxen wedge
ionic eagle

how can My bot join au stage vocal in speaker ?

midnight gust

@pearl iron help this guy please

ionic eagle

FS_bear_please

pearl iron

sup

subtle granite
Error [ERR_STREAM_WRITE_AFTER_END]: write after end ``` 
What’s this err ![A_thinking](https://cdn.discordapp.com/emojis/800332510981521408.webp?size=128 "A_thinking")
quasi turtle

Does @discordjs/opus require Visual Studio to work?

Because I am getting a problem that says that Visual Studio not found

finite grotto
quasi turtle

ok

Do I just install node-gyp?

finite grotto

you don't have to, I've just linked the prerequisites to use node-gyp

quasi turtle

I don't understand; how can I fix the problem?

finite grotto

are you on windows?

quasi turtle

yes I am using windows 11 home

finite grotto

then look at the section "On Windows" on the node-gyp installation page

quasi turtle

ok

verbal trail
verbal trail
waxen wedge
waxen wedge
stark spear

Does discord.js use ffmpeg for anything related with voice receiving?

rose helm
hardy veldt

can i destroy player like connection?

shrewd compass

How do I make bot leave vc after 5 mins of inactivity ?

pseudo forum
icy maple
verbal trail
hardy veldt
outer crown

Has anyone ever experienced a bug where playing audio from a local file works amazing but remote url playback doesn't always work?

Playing from a remote url with content type audio/mpeg works for a few hours! But after few hours of playback it stops on a few shards?

I see that it goes to ready, and starts buffering, but never starts playing?
vs the shards or local file that works it goes to ready, buffering, playing?

it's weird because its the same code running but on some servers it doesn't work and some servers work, also playing grom local files always works on all servers

not working

Connection transitioned from ready to ready
Audio player transitioned from idle to buffering
The audio player has started buffering!

working example

Audio player transitioned from idle to buffering
The audio player has started buffering!
Audio player transitioned from buffering to playing
The audio player has started playing!
outer crown
outer crown Has anyone ever experienced a bug where playing audio from a local file works am...
    const discordPlayer = createAudioPlayer();

    const voiceChannelConnection =
        getVoiceConnection(voiceChannel.guild.id) ||
        initConnection({ voiceChannel });

    await entersState(
        voiceChannelConnection,
        VoiceConnectionStatus.Ready,
        30e3,
    );

    const voiceChannelConnectionSubscription =
        voiceChannelConnection.subscribe(discordPlayer);

    discordPlayer.on(AudioPlayerStatus.Playing, () => {
        console.log('The audio player has started playing!');
    });

    discordPlayer.on(AudioPlayerStatus.Buffering, () => {
        console.log('The audio player has started buffering!');
    });

    discordPlayer.on("stateChange", (oldState, newState) => {
        // TODO: check if we need this
        if (newState.status === "idle") {
            voiceChannelConnectionSubscription.unsubscribe();
            // voiceChannelConnection.destroy()
        }

        console.log(
            `Audio player transitioned from ${oldState.status} to ${newState.status}`,
        );
    });

    discordPlayer.play(audioResource);
};``` code example
golden dagger

how do I listen into a voice channel with my bot?

the reason for this is because I wanna make a bot to make a transcript of every admin meeting in my server

finite grotto

<VoiceConnection>.receiver.subscribe(<UserId>)
returns an opus stream

golden dagger

thanks

potent oar

Hello,
I am making a 24/7 command but the bot keep stopping without any errors, and I should rerun the command to proceed with the music.

 const connection = await joinVoiceChannel({
            channelId: channel.id,
            guildId: interaction.guild.id,
            adapterCreator: interaction.guild.voiceAdapterCreator
        })
        var stream = await ytdl(`https://www.youtube.com/watch?v=36YnV9STBqc`, {
            highWaterMark: 1 << 5,
        })
        const player = createAudioPlayer();
        const resource = createAudioResource(stream, { inputType: StreamType.Opus })
        connection.subscribe(player);
        player.play(resource);
        player.on('error', error => {
            console.error(error);
        });
        client.on("voiceStateUpdate", async (oldState, newState) => {
    if (newState.channelId && newState.channel.type == "GUILD_STAGE_VOICE" && newState.guild.me.voice.suppress) {
        try {
            await newState.guild.me.voice.setSuppressed(false);
        } catch (e) {
            console.log(e)
        }
    }
})

Anyone got an idea why this is happening?

plain pulsar

is it possible to encode / embed an mp3 file within a JS file? i'm making a very simple bot that joins a voice channel and plays a sound when a certain condition, but is it possible to include the mp3 file within my singular js file so that i don't have two files?

and yes, i am fully aware that this is very stupid

also, i'd like to avoid just having an array of bytes and dumping it into a temp file and then opening that

finite grotto

the answer is yes, it's entirely possible
but the answer is also do that last thing you said (except instead of dumping into a temp file, you hard code it as a buffer in your js file)
all in all, it's a terrible idea, don't do it

harsh ocean

does anyone know what I should search up on the docs on creating a music bot?

shrewd compass

BTW this is timer

pseudo forum
subtle granite
subtle granite
potent oar
sick gazelle

how can u play a audio mp3 file uploaded by a person in vc without having audio file saved in local folder?

outer crown
sick gazelle how can u play a audio mp3 file uploaded by a person in vc without having audio ...

it's supposed to be like this ```const playSoundUrl = async ({ voiceChannel, audioUrl }) => {
const audioResource = createAudioResource(audioUrl, {
inputType: StreamType.Arbitrary,
});

console.log("Playback_sound", audioUrl)
try {
    await playSound({ voiceChannel, audioResource });
    console.log('Played_successfully!', audioUrl);
} catch (error) {
    /**
     * The song isn't ready to play for some reason :(
     */
    console.error("Failed_to_play ", audioUrl, error);
}

};``` plus this #archive-voice message but sometimes it stops working for me

outer crown
gleaming dew

If the music crashes in the middle, it comes from the connection, you must host the bot on a vps and it will work perfectly

subtle granite

How do I find out the name of the channel, and not the mention via ${oldChannel}

waxen wedge
subtle granite
elder crystal
function play(){
        const player = voiceDiscord.createAudioPlayer();
        const resource = voiceDiscord.createAudioResource('https://cdn.discordapp.com/attachments/879189880259870763/973195346941448262/bf1d69a1e5edf061.mp3');
        const connection = voiceDiscord.joinVoiceChannel({
            channelId : voice_channel.id,
            guildId : message.guild.id,
            adapterCreator : message.guild.voiceAdapterCreator,
        });
        
        player.play(resource);
        connection.subscribe(player);
        
        player.on(voiceDiscord.AudioPlayerStatus.Idle, () => {
            connection.destroy();
        });
        };
        play();

The bot join to the channel but I can't hear any sound

waxen wedge
elder crystal ```js function play(){ const player = voiceDiscord.createAudioPlayer(); ...

Why do you make a function out of it, don’t pass any arguments and use variables defined outside of it? Looks like unnecessary function here…
put some console.log in your code to find out if the connection gets destroyed prematurely or the player does start playing but you can’t hear it, or if it doesn’t find the resource, all the stuff you do when debugging

subtle granite

How do I check the category for empty voice channels?
If the channel is empty, then delete it.

languid quail
subtle granite

i am trying to get data from one user (one vc) and send it to another vc (on another guild) till know i created only how i can get the stream, but what do i do with it next?
how can i send the stream? is this even possible? please ping me

subtle granite

:c

gleaming dew

Is it possible to change the volume of an createAudioPlayer()?

waxen wedge
gleaming dew

With ffmpeg we can edit the volume thinkW

waxen wedge
gleaming dew

We can do something like resource.setVolume(0-100) or thinkW ?

gleaming dew

Im gonna try, thanks!

gleaming dew

It doesn't work pas @waxen wedge Kappa

waxen wedge

10 would mean 10 times as loud in this case, so you probably want 0.1

gleaming dew

The function doesn't exist x)

waxen wedge

Says the bot while running or your IDE?

gleaming dew

ide only

Oh it's work xD

stonks thanks !

fringe epoch

TypeError: Cannot read properties of null (reading 'voice')
I am using v13 functions, by the way

finite grotto

is this <GuildMember>.voice?

solar scaffold

hey sorry to bring this back after over a week but i fetched the channel with the other client and then used that for the adapter but the bots still wont play simultaneously

if i start it on one bot, then start the next, the initial one disconnects, even though i am creating a new player and connection each time

finite grotto

can you show the code where you connect?

finite grotto
solar scaffold

after some testing I've found you need to declare separate groups for each connection

finite grotto
solar scaffold

Noted thanks

gleaming dew

We can't play a "resource" that has already been played, we have to duplicate it before starting to play it the first time?

finite grotto
gleaming dew

I test and it's crash so I think we need to do that (for loop music) KappaOk thanks

elfin lynx

is there a "debug" mode for djs voice? I got some weird issue sometimes the bot join VC but not playing anything

gleaming dew

Okay so the solution is to create 2 AudioRessource xd

gleaming dew

But when I do that, the audio crash after 3s lmao

fringe epoch

Hey, how could I make my bot join (already done) and disconnect after some seconds with a wait function?

feral coral

how to I check if my bot failed to join a vc? it just forces my bot offline and the console doesnt show an error despite no error handling.

even if I error handle it just forces the bot offline

fringe epoch

Thats odd

feral coral

very

I can get connection status with getconnection and see it signalling but after it doesn't tell me if it failed just sits there

fringe epoch

;-;

you execute the cmd and it just crashes without log?

feral coral

yup

gleaming dew
feral coral

it goes offline before the while loop which seems to be right as it runs joinvoicechannel

while loop still runs despite that but after counting to 3 and sending sorry couldnt join the bot is dead.
console tells me nothing and I cant ping pong the bot

gleaming dew

  const connection = ...
    .catch((e) => {
      console.log(e)
  }
```We will have the error
feral coral

I get catch is not a function

is this catch correct?

gleaming dew

Im so stupid oops

feral coral

kinda hard to catch an error when there isnt one

gleaming dew

from the moment you define joinVoiceChannel, the bot is supposed to join directly so the problem comes from there (except if it can't pass the tests, a console.log(true) to check just above the connection can be interesting)

feral coral

I might have to check the ID provided instead then

gleaming dew

And what's vcID & guildID ?

feral coral

purposes is to simply join vc I tell it to

gleaming dew

Are you sure to give the right ids x) ?

feral coral

i'm intentionally not as to error check, it works as expected when real IDs are provided

now im wondering if I can crash someones bot by deleting the vc 10ms after sending a ;;play command

timing would be close but i'm betting its possible

welp i'm gonna try

icy maple
frigid wedge

Hello, I'm new in making discord bots and I have issue with voice connection.
I used discord.js v13 and discordjs/voice 0.9, code is on typescript. So I'm trying to make connection method, but I can't get what I have to put in adaptorCreator.
Also I would be glad if you can advice me some good guides to make musical bot.

pseudo forum

@frigid wedge ^

frigid wedge
karmic burrow

Is there a way to destroy a connection but keep the bot in VC?

slender sparrow

no

waxen wedge
subtle granite

Can I have help please?

waxen wedge
karmic burrow

I want to recreate that for the bot but have no idea how

waxen wedge

Set status to invisible (appear offline)

karmic burrow

Not the online status. Just the connection

subtle granite

Hey guys, i am trying to connect my bot to a voice channel but i am having some issues.
i keep getting this error:

node:internal/modules/cjs/loader:488
      throw e;
      ^

Error: Cannot find module '**path**/node_modules/@discordjs/voice/dist/index.js'
    at createEsmNotFoundErr (node:internal/modules/cjs/loader:954:15)
    at finalizeEsmResolution (node:internal/modules/cjs/loader:947:15)
    at resolveExports (node:internal/modules/cjs/loader:482:14)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (**path**/bot_voice.js:21:15)
    at Module._compile (node:internal/modules/cjs/loader:1099:14) {
  code: 'MODULE_NOT_FOUND',
  path: '**path**/node_modules/@discordjs/voice/package.json'
}

I think there is an issue with the discordjs/voice package, but i cant understand whats wrong 😦

Has anyone ever been through this problem? Or, does anyone know how i can solve this?

icy maple
subtle granite
subtle granite

When connection to a voice channel, i wait for the connection to be created using await entersState(connection, VoiceConnectionStatus.Ready, 30e3); but the connections never gets ready, and ends up aborting and crashing my bot dispite this being inside a try catch:

connection = joinVoiceChannel({
            channelId: channel.id,
            guildId: channel.guild.id,
            adapterCreator: channel.guild.voiceAdapterCreator,
        });
        try {
            await entersState(connection, VoiceConnectionStatus.Ready, 10e3);
            return connection;
        } catch (error) {
            connection.destroy();
            throw error;
        }

After the time runs off, i get this message:

node:events:970
      reject(new AbortError(undefined, { cause: signal?.reason }));
             ^

AbortError: The operation was aborted
finite grotto
subtle granite
mossy crag

Hello guys! Maybe someone met the same problem of switching between two players on one connection. I'm developing a bot that plays music from a URL (via .play <URL> command) and handles voice state changes (like join, leav, mute, etc.) with playing sound. I use two player for music and sounds. If voice change handled while music is playing I try to paused music player, then creating new player for sound and subscribe connection for that. When sound layer become idle I try to subscribe connection for music player and unpaused that.
Separately, these two parts work fine. But if I try to play sound while music is playing, my temporary sound player heangs in buffering state. However if i try to play music (by .play command) during the sound is playing, it's work fine.
You can find my code here:
For .play command https://github.com/rofl3228/discord-voice-bot/blob/main/src/actions/play.js
For handling voice state changes https://github.com/rofl3228/discord-voice-bot/blob/8e3134ff65a0df4f6e44fff5c8e82739a115c775/src/core/bot.js#L81
Thanks for your attention and sory for my english)

shrewd arch

How do I control a resource. I want to change the volume while it's playing but when I create the resource and write .volume.setVolume(1) at the end then it tells me that the resources has already been ended. Also I want to somehow loop songs/queues

fervent estuary

There is not way to replay a resource. You will have to create a new resource to play it again

fickle quartz

hello, i wanted to add a pause command to my bot using .pause() but it dont work :/ can someone help me pls ?

const { joinVoiceChannel, createAudioPlayer, createAudioResource} = require('@discordjs/voice');
const player = createAudioPlayer();

 if(message.content.startsWith(prefix + 'pause')){
            player.pause(true);
        }
fervent estuary

if thats all of your code im not surprised. You arent playing anything on that player

fickle quartz
fervent estuary

send it here

fickle quartz

there is a lot

fervent estuary

a resource cant be paused

how exactly didnt it work for u?

fickle quartz

when i use the !skip or !pause command the song dont stop or pause

without pausing the ressource it dont work to

subtle granite
const audio = discordTts.getVoiceStream("Hallo")
    const audioResource = createAudioResource(audio, {inputType: StreamType.Arbitrary, inlineVolume: true})
    if(!voiceConnection || voiceConnection?.status === VoiceConnectionStatus.Disconnected) {
        const channel = client.channels.cache.get("906641697507774515")
        voiceConnection = joinVoiceChannel({
          channelId: channel.id,
          guildId: channel.guild.id,
          adapterCreator: channel.guild.voiceAdapterCreator
        })
        voiceConnection = await entersState(voiceConnection, VoiceConnectionStatus.Connecting, 5_000)
    }
    if(voiceConnection.status === VoiceConnectionStatus.Connected) {
        voiceConnection.subscribe(audioPlayer)
        audioPlayer.play(audioResource)
    }

reject
[object Promise]
AbortError: The operation was aborted
What is the problem?

waxen wedge
subtle granite
waxen wedge
subtle granite
waxen wedge
subtle granite no

Then you have your own error handler somewhere and it doesn’t log the full error

waxen wedge
subtle granite
waxen wedge
subtle granite
waxen wedge
shrewd arch

I know that it is possible to set it while it is playing

fervent estuary

did u enable volume when creating the resource?

shrewd arch
shrewd arch

it always tells me: This resource has already ended. Even if I set the volume instant at the creation of the resource

fervent estuary

🤔

is the resource being played at that time?

shrewd arch

like I said. Directly at the creation it gives me an error. Also it wouldn't be a problem when it is playing

fervent estuary

id assume thats the reason

the resource needs to be played in order to change volume

shrewd arch

It works now

Thanks

fervent estuary

👍

last nexus

Hi mates, does anyone know how to fix this? I'm using typescript@4.6.4 and @discordjs/voice@0.9.0

rose helm

The error is on djs voice's end

also, that error doesn't stop tsc from working. It's just ignored.

subtle granite

can i do anything

waxen wedge
subtle granite

A_thinking

limber ferry

I'm trying to get the decibel level (or some measurement of loudness) of any given member in a voice channel. My bot already joins voice channels, and is able to read the raw data from other users with this test code

let connection = joinVoiceChannel({
                channelId: channel.id,
                guildId: channel.guild.id,
                adapterCreator: channel.guild.voiceAdapterCreator as DiscordGatewayAdapterCreator,
            });
            for(const member of channel.members) {
                let sub = connection.receiver.subscribe(member[1].id)
                sub.on('data', data => {
                    console.log(data)
                })
            }

How can I convert this data into something I can use?

finite grotto
gray lily
    const joinchat = client.channels.cache.get("976225179090944050");
    joinchat.join();
});```
Why is joinchat.join() not a function?
dusty needleBOT
stoic sequoia
jolly zenith

does anyway know why im getting FFmpeg not found even thought i have it installed

jolly zenith

just had to restart my pc and manually installing it worked

spark dock

const connection = getVoiceConnection(myVoiceChannel.guild.id);

What do i need to put for myVoiceChannel since it is giving me the error that it is not defined

honest orchid
spark dock

how can i pass on channel here since it is saying channel is not defined

```   if (commandName === 'join') {
        await joinVc();
    } else if (commandName === 'stop') {
        await LeaveVc();
    }
});

function joinVc() {
connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
let resource = createAudioResource(createReadStream(join(__dirname, '.mp3')), {
inlineVolume : true
});
resource.volume.setVolume(0.2);
console.log(join(__dirname, '.mp3'));
const player = createAudioPlayer();
connection.subscribe(player);
player.play(resource)
console.log("done");
}

function LeaveVc() {

}```

torn marlin

Fetch the link and check response content type

wheat relic

How can i fetch the player for the guild?

limber ferry

How can I use ffmpeg (with fluent-ffmpeg)'s volumedetect filter on an AudioRecieveStream from a person in a voice channel? My goal is to get the mean_volume value returned from ffmpeg

stark spoke

how do I make a bot automatically become a speaker when joining a stage channel assuming it has permission to do so?

stoic sequoia
stark spoke
dusty needleBOT
stoic sequoia
stark spoke
stark spoke
eager lake

then whatever channel you have there isnt a stage channel

stoic sequoia
stark spoke

I didn´t sleep much today, still having issues that I don´t know how to solve

    if (channel.type == 'GUILD_STAGE_VOICE') {

      let stageName = message.guild.members.cache.get(client.user.id).nickname;
      if (stageName == null) stageName = client.user.username;

      message.guild.stageInstances.create(channel.id, {
        topic: `🎶 ${stageName}`,
        privacyLevel: 'GUILD_ONLY'
      });
        
      message.guild.me.voice.setSuppressed(false);
    }
stoic sequoia

what are they?

eager lake

well, did you even join the stage at that point

stark spoke

Yes

eager lake

at what point did you do that

dusty needleBOT
stark spoke
    const channel = message.guild.channels.cache.get(args[0]);

    const connection = voiceDiscord.joinVoiceChannel({
      channelId: channel.id,
      guildId: message.guild.id,
      adapterCreator: message.guild.voiceAdapterCreator,
      selfDeaf: true,
    });
      
    const player = voiceDiscord.createAudioPlayer();
    const resource = voiceDiscord.createAudioResource(radio[args[1]]);

    player.play(resource);
    connection.subscribe(player);
      
    player.on(voiceDiscord.AudioPlayerStatus.Idle, () => {
      connection.destroy();
      message.reply(`:x:**¡La estación de radio no funciona!**`)
    });
    
    if (channel.type == 'GUILD_STAGE_VOICE') {

      let stageName = message.guild.members.cache.get(client.user.id).nickname;
      if (stageName == null) stageName = client.user.username;

      message.guild.stageInstances.create(channel.id, {
        topic: `🎶 ${stageName}`,
        privacyLevel: 'GUILD_ONLY'
      });
        
      message.guild.me.voice.setSuppressed(false);
    }

Probably here are very important mistakes 🤷

stoic sequoia
stark spoke
eager lake

my guess would be you didnt wait til the bot actually connected and is ready to be unsuppressed

also why do you destroy the connection when the audioplayerstatus is idle

the audioconnection literally starts in idle

Idle - the initial state of an audio player.

stoic sequoia
stark spoke
eager lake

in the Ready state, set suppressed to false

stark spoke
subtle granite
waxen wedge
stark spoke
eager lake

check stagechannel.stageInstance I suppse?

stark spoke

Okey, I should learn how to read the docs xD, very thankful for ur time

gaunt basin

how do make my bot stay in voice channel like 24/7 , for ex
bot will join the defined channel when its on
idk much about voiceStateUpdate so anyone / docs can help me ?

west basalt
gaunt basin

and its not music bot

true schooner

is there a way to make the bot leave vc once a sound has finished playing? when i set a timeout, it leaves after about under a second or a second idk....
but when the timeout isn't there, it plays the sound like normalitty
(question originally posted in #djs-help-v14 because i'm dumbjoe)

true schooner
waxen wedge
true schooner
waxen wedge
true schooner

wait i see the problem now

damn it i needed * 1000

subtle granite

is it possible to recieve audio with a bot, or is that not an option right now?
i see that it was possible previously, but also that it's not supported, so i assume it's prone to breakage.

subtle granite
icy maple It's possible

thank you very much, but i've run into another issue. it says that it cannot find module 'node-crc' here, and when i try to install it, it says that it can't find the rust executable (even though i just installed rust and restarted my computer)

subtle granite

ok, that works now, i just had to restart again. i blame windows updates.
now, though, i'm getting this error on the same line

limber ferry

I'm trying to get the relative volume of a given user in a voice channel, and I'm having some issues (I've tried ffmpeg, it can distinguish between whispering and talking, but not talking and screaming). I'm trying to use AudioContext now, by interpreting the first answer from this post https://stackoverflow.com/questions/33322681/checking-microphone-volume-in-javascript

Is there a way to somehow convert/cast from an AudioRecieveStream/Readable to a MediaStream? (which is required to use AudioContext#createMediaStreamSource())

pulsar dew
waxen wedge
pulsar dew
waxen wedge Look at the next section of that guide and your questions get answered😉

Well, that's what I tried: ```ts
client.guilds.cache.map(guild => {
const vcConnection = getVoiceConnection(guild.id);

    console.log(guild.id, vcConnection);

    for(const vcListenerConfig of vcListenerConfigs) {
        vcConnection?.on(vcListenerConfig.name as VoiceConnectionStatus, vcListenerConfig.execute as any);
    }

    console.log(`Loaded ${vcListenerConfigs.length} voice listeners for guild ${guild.id} `)
})

But, `vcConnection` is always empty 🤔
dusty needleBOT

Suggestion for @pulsar dew:
guide Library: Cheat sheet - Creation
If you try to call joinVoiceChannel on another channel in the same guild in which there is already an active voice connection, the existing voice connection switches over to the new channel.
read more

pulsar dew

But, I don't want the bot to join a channel. I want to track member join/leave events etc. Or am I looking in the wrong place then? 😅

dusty needleBOT

Documentation suggestion for @pulsar dew:
event (event) Client#voiceStateUpdate
Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.

pulsar dew
hazy temple

hi
in my music bot i have a error
can you help me?

Error: aborted
    at connResetException (node:internal/errors:691:14)
    at TLSSocket.socketCloseListener (node:_http_client:402:19)
    at TLSSocket.emit (node:events:538:35)
    at node:net:687:12
    at TCP.done (node:_tls_wrap:580:7) {
  code: 'ECONNRESET'
}```

v16.14.2
neon ibex

What is difference between <VoiceConnection>.destroy() and guild.me.voice.disconnect()?

waxen wedge
neon ibex

Thanks!

visual temple

I have a command to join a voice channel and play an audio file (attached to a slash command); TypeScript is giving me this error, but otherwise it works if it is ignored

icy maple

You can safely ignore it. I believe it’s fixed in v14

frank heath

Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist

Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist

Last metadata expiration check: 0:12:41 ago on Sun 22 May 2022 10:27:48 AM GMT.

No match for argument: ffmpeg

Error: Unable to find a match: ffmpeg

then anyone know how to install ffmpeg on oracle linux?

frank heath

Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist

Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist

Last metadata expiration check: 0:17:54 ago on Sun 22 May 2022 10:27:48 AM GMT.

epel-release-latest-8.noarch.rpm                                     29 kB/s |  23 kB     00:00
Package epel-release-8-15.el8.noarch is already installed.

Dependencies resolved.

Nothing to do.

Complete!

[opc@rais-bot ~]$ sudo yum-config-manager --enable powertools

Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist

Invalid configuration value: failovermethod=priority in /etc/yum.repos.d/nodesource-el8.repo; Configuration: OptionBinding with id "failovermethod" does not exist

Error: No matching repo to modify: powertools.

[opc@rais-bot ~]$```

Error: No matching repo to modify: powertools.

  - nothing provides libSDL2-2.0.so.0()(64bit) needed by ffmpeg-4.2.6-1.el8.aarch64
(try to add '--skip-broken' to skip uninstallable packages or '--nobest' to use not only best candidate packages)```
icy maple

Pretty much just comment out all failovermethod

frank heath
 Problem: conflicting requests
  - nothing provides libSDL2-2.0.so.0()(64bit) needed by ffmpeg-4.2.6-1.el8.aarch64
(try to add '--skip-broken' to skip uninstallable packages or '--nobest' to use not only best candidate packages)```
that's the only other thing I have a problem with
frank heath
fickle quartz

Hello, when I try to stop my bot from playing using player.stop it does not stop it but it dont give me an error
It's like nothing happen
I'm 100% player.stop is executed by my code and i try different things without succes
If someone could help me that would be great
Here my code

Client.on("messageCreate", message => {
try {
const { createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice');
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
if (message.content.startsWith(prefix + "joue")){
if(!message.member.voice.channel){
message.reply("Vous n'êtes pas dans un channel vocal");
return;
}
var lien = message.content.substring('!joue '.length);
if(message.member.voice.channel){
          if(lien.startsWith('https://www.youtube.com/watch?')){
                const ytdl = require("ytdl-core");
                const { joinVoiceChannel, createAudioResource } = require('@discordjs/voice');
const connection = joinVoiceChannel(
                    {
                    channelId: message.member.voice.channel.id,
                    guildId: message.guild.id,
                    adapterCreator: message.guild.voiceAdapterCreator
});
message.channel.send('Lecture en cours');
const stream = ytdl(lien);
const ressource = createAudioResource(stream);
const { AudioPlayerStatus } = require('@discordjs/voice')
player.on(AudioPlayerStatus.Playing, () => {
console.log('Lecture en cours');
});
player.play(ressource);
connection.subscribe(player);
player.on(Discord.AudioPlayerStatus, () => {
connection.destroy();
});
 };
};
if(message.content.startsWith(prefix + 'pause')){
player.pause();
message.channel.send("Vidéo mise en pause");
}
if(message.content.startsWith(prefix + 'unpause')){
player.unpause();
message.channel.send("Vidéo relancé");
}
if(message.content.startsWith(prefix + 'skip')){
player.stop();
message.channel.send("Vidéo skip");
}
};
} catch (error) {
console.log('Erreur : ' + error);
return
};
});
runic sundial

The player is only declared in the messageCreate event; I think you have to put

let player

before this part and then use the variable.

And you are lucky mine doesn't want to play audio at all. I tried everything

fickle quartz
subtle granite

What's the error?

fickle quartz

and it doesnt play the youtube link

subtle granite

Check your brackets... you might be closing them at the wrong place or so because you didn't initiate player before you call player.stop()

fickle quartz

okay bro thx i'll try

rugged sky
rugged sky
hazy temple

hi
in my music bot i have a error
can you help me?

Error: aborted
    at connResetException (node:internal/errors:691:14)
    at TLSSocket.socketCloseListener (node:_http_client:402:19)
    at TLSSocket.emit (node:events:538:35)
    at node:net:687:12
    at TCP.done (node:_tls_wrap:580:7) {
  code: 'ECONNRESET'
}```

v16.14.2
quick phoenix

Hi ! I came here to ask for advice from people who already tried to play local sounds with @discordjs/voice. I am trying to do that with my bot but no sound is coming out. I debugged a bit and found out the AudioPlayer's state kept being in buffering after loading the resource. I tried a lot of things I found in the doc or SO, but nothing worked so far. :/

My code:

const { createAudioPlayer, NoSubscriberBehavior, createAudioResource } = require("@discordjs/voice");
const { createReadStream } = require("fs");

const voicePlayer = createAudioPlayer({
    behaviors: {
        "noSubscriber": NoSubscriberBehavior.Pause
    }
});

function addAudioRessource(ressource) {
    voicePlayer.play(createAudioResource(createReadStream("./assets/sounds/" + ressource)));
    console.log(voicePlayer.state.status) // buffering after playing the resource 
}

function stopVoicePlayer() {
    voicePlayer.pause();
}

module.exports = { voicePlayer, addAudioRessource, stopVoicePlayer };
const { joinVoiceChannel } = require("@discordjs/voice");
const { ButtonInteraction } = require("discord.js");
const { bot } = require("..");
const { GUILD_ID, VOICE_CHANNEL } = require("../../config");
const { voicePlayer } = require("../core/voice");

/**
 * 
 * @param {ButtonInteraction} interaction 
 */
function joinVocal(interaction) {
    const guild = bot.guilds.cache.get(GUILD_ID);

    let voiceConnection = joinVoiceChannel({
        guildId: GUILD_ID,
        channelId: VOICE_CHANNEL,
        adapterCreator: guild.voiceAdapterCreator
    });
    
    voiceConnection.subscribe(voicePlayer);

    bot.voiceConnection = voiceConnection;

    interaction.reply({ content: "J'ai rejoint le salon vocal !", ephemeral: true });
}

module.exports = { joinVocal };

Not best practices, but it's only a small bot not designed for public use.

If someone has a fix or a working code snippet, I'd be glad to hear it ^^

Also my dependencies:

{
  "dependencies": {
      "@discordjs/opus": "^0.5.3",
      "@discordjs/voice": "^0.9.0",
      "discord.js": "^13.7.0",
      "ffmpeg-static": "^4.4.1"
    }
}
waxen wedge
quick phoenix

I tried the __dirname variable

Didn't change much, I can still try again though

quick phoenix
waxen wedge
quick phoenix

I tried first, didn't work, so I tried the readStream

Tried again, same result

waxen wedge

Which of the optional packages do you have installed?

sodium, discordjs/opus and ffmpeg-static?

waxen wedge
quick phoenix

Nope, I should try and install it then ?

waxen wedge
quick phoenix
pseudo forum
quick phoenix

Thank you, I'm going to try that

quick phoenix
waxen wedge
quick phoenix

Tried the regular sodium too, still buffering

quick phoenix

Any idea ?

edgy saffron

Gosh, I'm having absolutely no luck converting the voice stream to a different format. Is anybody free who could potentially help?

pseudo forum
quick phoenix

Doesn't seem to work even with sodium installed

subtle granite

Do you get any errors?
Is your VOICE_CHANNEL variable a channelId?

Also your log only logs the state at that specific moment.. you might wanna listen to the statechange event and log the player's state

quick phoenix
atomic pagoda

Hey, so I'm not too sure where to ask this so I apologise if this is in the wrong place. I have a youtube dl downloader from a URL, taken I think, from one of the discord js examples. But how would I change this into an AudioResource with a URL with just an audio file on it. Say url.com/song.mp3

return new Promise((resolve, reject) => {
            const process = ytdl.exec(video_url, {
                o: '-',
                q: '',
                f: 'bestaudio[ext=webm+acodec=opus+asr=48000]/bestaudio',
                r: '100K',
            }, {
                stdio: [
                    'ignore',
                    'pipe',
                    'ignore'
                ]
            });
            
            ......

            process.once('spawn', () => {
                demuxProbe(stream).then((probe) =>
                    resolve(createAudioResource(probe.stream, {
                        metadata: this,
                        inputType: probe.type
                    }))
                ).catch(onError);
            }).catch(onError);
});```

Thank you for any help!
quick phoenix
subtle granite

Could that be because of the nosubscriberbehaviour?

quick phoenix

Removed the behavior but still the same

subtle granite

Guide says

AutoPaused - the state a voice connection will enter when the player has paused itself because there are no active voice connections to play to. This is only possible with the noSubscriber behavior set to Pause. It will automatically transition back to Playing once at least one connection becomes available again.

Make sure your bot actually enters the voice channel so it can play sound there

quick phoenix

It is

I put these lines to debug the states of the AudioPlayer

voicePlayer.on("subscribe", () => console.log("subscribe"))
voicePlayer.on("unsubscribe", () => console.log("unsubscribe"))

voicePlayer.on("stateChange", (oldState, newState)=> console.log(oldState.status + " " + newState.status))

There is a subscriber so nothing coming from here

subtle granite

Log the statechange event for the connection as well and see if it becomes ready

timid pulsar

Dependency Report:

Core Dependencies
- @discordjs/voice: 0.9.0
- prism-media: 1.3.2

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

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

FFmpeg
- version: 3.4.10
- libopus: yes
--------------------------------------------------```

Relevant Code:

```const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_VOICE_STATES] });
const { createAudioPlayer, createAudioResource, joinVoiceChannel, getVoiceConnection } = require('@discordjs/voice');
const audioPlayer = createAudioPlayer();

client.guilds.fetch(guildId).then(guild => {
  joinVoiceChannel({
    channelId: channelId,
    guildId: guildId,
    adapterCreator: guild.voiceAdapterCreator
  });
  const audioConnection = getVoiceConnection(guildId);
  const audioSubscription = audioConnection.subscribe(audioPlayer);
});

if(...) audioPlayer.play(createAudioResource('sound.mp3'));```

Basically I'm trying to play a simple 3 second mp3 file in a voice channel. When I was hosting off glitch.me, everything worked fine. But I recently upgraded to VPS hosting and transferred everything over. Now no sound plays, but AudioPlayerStatus.Playing does trigger without any errors. I've tried to include the full filepath to the file. And I'm on CentOS which seems to be unable to install @discordjs/opus and sodium. Any idea what the problem could be?

Does not go into the AutoPause state either.

arctic ridge

I have a slight problem with one of the codes, that if I tell the bot to play a song, it won't stop repeating it

quick phoenix

Thank you for the advice

spark spindle

I know this is v12 code but I'm really stuck
why doesn't message.guild.voice.connection.dispatcher.resume() work?

waxen wedge
bright wigeon

So, i'm developing a music bot, how do i do the bot detect that it been kicked out of the voice channel and then destroy the queue?

fickle quartz
timid pulsar

Immediately goes to Idle state after Playing state

icy maple
timid pulsar

CentOS 7 on a VPS
Tried using the mp3 as a local file with relative/absolute paths, uploading it, and also posting it on discord and using the cdn.discord link

icy maple

Did you use path.join(__dirname, relativePath)?

timid pulsar

tried that too, yes

directly and with createReadStream

icy maple

Could you log fs.existsSync(path.join(…))?

timid pulsar

sure give me a second

icy maple

I’m not sure how you managed to fetch a guild before even logging in

Can you also move the code into the ready event?

timid pulsar

i logged in, just didn't include that code since discord character limit

icy maple

Is the code in a client event?

timid pulsar

the fetch + declaring connection/subscription happen in the client ready event

play happens elsewhere

icy maple

Use pastebin next time

timid pulsar
icy maple

Are you sure the audio isn't 1 second long?

Or said it was 3 seconds

timid pulsar

its ~3 seconds long, but goes idle in like 0.1 seconds
it worked perfectly with the same code (changed paths ofc) when i was hosting on glitch
problem only started once i migrated to a vps

icy maple

I’m assuming ur testing on ur host rn?

timid pulsar

correct

bot is joining the channel just fine, and the event to play the sound is triggering (tested through logging + player enters playing state)

timid pulsar

Did more testing
path.resolve didn't fix anything
When I split audioPlayer.play(createAudioResource('sound.mp3')); into two lines var audioResource = createAudioResource('sound.mp3'); and audioPlayer.play(audioResource);, it immediately errors Cannot play a resource that has already ended. even on the first time playing

icy maple

Use const instead of var for good measure too

timid pulsar

sure
also its seeming like the resource is ending as soon as it's created
i assume that just means error loading it so it's read as 0s length, therefore already ended?

timid pulsar

could it not error out because the resource played so soon after it's created?

timid pulsar
timid pulsar

How about a CentOS 7 issue?

icy maple

It’s not reusable

timid pulsar

Yeah it was only for testing purposes

Was trying everything since I have no idea what’s causing it

timid pulsar

so it goes buffering -> playing -> idle, never paused/autopaused

timid pulsar

Audio Resource logs

also ran ffmpeg as ffmpeg -i ping.mp3 2>&1|grep Duration to verify that the mp3 file is 2.59s long, not 0s

just tried with a ~4 min webm in case it was the format or short duration messing with it, same result

icy maple

Gonna try that one first bc opus is deprecated

timid pulsar

tried using python3 and python3.10 + upgrading a few other things i forget

i think i found someone saying its broken on CentOS

icy maple

Oh great, g++ issue

npm ERR! g++: error: unrecognized command line option '-std=gnu++14'

Can you run g++ -v?

timid pulsar

4.8.5

unless you want the whole thing

icy maple

Nah, that’s good

timid pulsar

very last resort i can swap OSes

icy maple
timid pulsar

alright imma try that

icy maple

I believe you need at least v5, but the latest is v12

timid pulsar

that worked

had to retry it a few times but i got it

seems the sound is still not playing though

time to try to install sodium?

replaced opusscript with @discordjs/opus and tweetnacl/libsodium-wrappers with sodium

not working yet but i feel it's a step in the right direction

timid pulsar

well now im extra confused

here's the output for the working version hosted on glitch

timid pulsar
dusky portal

New here: is the voice guildMemberSpeaking event reliable or still experimental (or basically fighting whatever support Discord may have dropped for speaking bits)?

How to run the voice basic-example.ts? I clone the repo, cd to voice\examples\basic, and then ts-node basic-example.ts but get lots of tsc errors.

waxen wedge

That solution is actually independent of py or js. Did you try doing what they suggest?

prime elbow

How do I fetch an Audio Stream (online radio station. It's outputting an mp3) and then play it back through a Discord bot

This is assuming it's at all possible

dusky portal

The demo could have stayed in a skunkworks type of deprecated folder for reference and future revival

ornate minnow

Tell me the module to search for tracks on spotify. I suspect my module is out of date

kekw 😄

prime elbow
supple dust

Some body know why I have this error with my music bot ?
R [Error]: aborted
The Error stop the current music and skip some music after

The full error :

Part one

R [Error]: aborted
    at connResetException (node:internal/errors:692:14)
    at TLSSocket.socketCloseListener (node:_http_client:414:19)
    at TLSSocket.emit (node:events:539:35)
    at node:net:709:12
    at TCP.done (node:_tls_wrap:582:7) {
  resource: T {
    playStream: Encoder {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      encoder: null,
      _options: [Object],
      _required: 3840,
      _buffer: null,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: [Function: bound onwrite]
    },
    edges: [ [Object], [Object], [Object] ],
    metadata: null,
    volume: VolumeTransformer {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      _readInt: [Function (anonymous)],
      _writeInt: [Function (anonymous)],
      _bits: 16,
      _bytes: 2,
      _extremum: 32768,
      volume: 1,
      _chunk: null,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: [Function: bound onwrite]
    },

Part two

encoder: Encoder {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      encoder: null,
      _options: [Object],
      _required: 3840,
      _buffer: null,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: [Function: bound onwrite]
    },
    audioPlayer: B {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _state: [Object],
      subscribers: [Array],
      behaviors: [Object],
      debug: [Function (anonymous)],
      [Symbol(kCapture)]: false
    },
    playbackDuration: 69120,
    started: true,
    silencePaddingFrames: 5,
    silenceRemaining: -1
  }
}

And here the function play :

async function play(guild, song) {
    var serverQueue = queue.get(guild.id); // On récupère la queue de lecture
    if (!song) { // Si la musique que l'utilisateur veux lancer n'existe pas on annule tout et on supprime la queue de lecture
            setTimeout(function() {
                var serverQueue = queue.get(guild.id);
                if(serverQueue.songs < 1) {
                    var connection = getVoiceConnection(serverQueue.guildID);
                    queue.delete(guild.id);
                    connection.destroy();
                }
            }, 300000)
            return;
        }

    if(serverQueue.loop === true) {
        serverQueue.songs.push(song);
    }
    // On lance la musique
    var connection = await getVoiceConnection(serverQueue.guildID);
    if(serverQueue.connection === null) {
        serverQueue.connection = createAudioPlayer({
            behaviors: {
                noSubscriber: NoSubscriberBehavior.Pause,
            }
        });
    }

    serverQueue.ressource = new createAudioResource(await ytdl(song.url),{ 
        inlineVolume: true,
        inputType: StreamType.WebmOpus
    });
    serverQueue.ressource.volume.setVolume(serverQueue.volume); // On définie le volume
    await serverQueue.connection.play(serverQueue.ressource);
    await connection.subscribe(serverQueue.connection);
        serverQueue.connection.on(AudioPlayerStatus.Idle, () => { // On écoute l'événement de fin de musique   
                serverQueue.songs.shift();
                play(guild, serverQueue.songs[0]);
        });
        serverQueue.connection.on("error", error => console.error(error));

    serverQueue.textChannel.send({ content: `Démarrage de la musique: **${song.title}**`});
}
timid pulsar

@icy maple i found the solution
ffmpeg installation doesn't matter, it needs ffmpeg-static

jolly zenith

will using worker threads stop random audio lag spikes/stutters and is there any examples

novel gorge

Someone known what is this error?

dusky portal
finite grotto

well the solution on stackoverflow looks pretty universal and unrelated to discord.py or any code for that matter
but also I imagine this issue could be solved with different dependencies

the issue could also lie elsewhere ¯_(ツ)_/¯
I've personally had no issues like this on heroku (though I will say heroku isn't the best for bot hosting)

dusky portal

Can anyone help me with what the minimum steps are needed to get the discord.js/packages/voice/examples/basic/basic-example.ts example to work?
I'm running in to all kinds of tsc errors.

finite mortar

It's designed for hosting websites. For small bot applications there's no real issues, but it's not designed to handle more complex bots

subtle granite
supple dust
dusky portal
subtle granite
supple dust

May be it's for that it work

subtle granite

The djs dev version of v13 worked with node v14... I'm not sure about v13.0.0 itself although the guide says v16 is needed... just try it then lol

Also v13.3 is the at least recommend version of djs currently I think

pseudo forum

better to have the latest (13.7.0)

supple dust

What major changes between 13.0.0 and 13.7.0 ?

pseudo forum
vocal cypress
granite python

TypeError: message.member.voice.channel.join is not a function
at execute (/home/runner/NodeDisBot/index.js:83:56)
at runMicrotasks (<anonymous>)
/home/runner/NodeDisBot/node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^

DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/runner/NodeDisBot/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/NodeDisBot/node_modules/discord.js/src/rest/RequestHandler.js:51:14) {
method: 'post',
path: '/channels/964318578650279979/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}

This is what I'm getting can anyone help me with it?

when I do -play

hazy remnant
  1. Voice system completely changed
  2. Don’t send an empty message
dusty needleBOT

Documentation suggestion for @granite python:
class AudioPlayer (extends AudioPlayerEvents)
Used to play audio resources (i.e. tracks, streams) to voice connections.

granite python

How would I define channel

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

hazy remnant

?

granite python

ReferenceError: channel is not defined

hazy remnant

message.channel

granite python

not that...

hazy remnant

const channel = message.channel;

granite python

thats the wrong snippit its supposed to have the whole thing

hazy remnant

?

granite python

nvm

granite python

what has play in serverQueue.connection
.play(ytdl(song.url)) changed to?

finite grotto
dusty needleBOT

Suggestion for @granite python:
guide Library: Cheat sheet - Playing audio
read more

granite python
granite python

can I do player.onfinish

player.on("finish", () => {
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})

play(a,b); is a custom method

nvm I can just do this

player.on(AudioPlayerStatus.Idle, () => {
player.play(getNextResource());
});

vocal cypress

My bot dosnt play the resource i gave it. It just joins the channel and thats it. But for some reason it still logs the Audio player is in the Playing state! message. Code: https://pastebin.com/00tVBW0R

subtle granite

Also you don't need to get the guild and member from the cache... just interaction.guild and interaction.member would just work fine

vocal cypress

when i put the intent in the list, it returns this: RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number: undefined. Intent line: const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.GUILD_VOICE_STATES] });

subtle granite

You miss the FLAGS

vocal cypress

oh yea. oops. thx

thx it works now :)

is there a way to stream live stream audio to the voice channel?

peak bridge
async joinVoice(channelId, guildId) {
    try {
        console.log('channel', channelId)
        const { voiceAdapterCreator: adapterCreator } = await this.client.guilds.fetch(guildId);
        console.log('attempting connection')
        const connection = joinVoiceChannel({
            adapterCreator,
            channelId,
            guildId,
        });
        console.log('connection success')
        const player = createAudioPlayer();
        await connection.subscribe(player);
        console.log('player subscribed')
        return {
            connection,
            player,
        }
    } catch (err) {
        console.log('joinVoice error', err);
    }
}
async playAudio(player, stream) {
    try {
        const resource = createAudioResource(stream);
        await player.play(resource);
        console.log('playing music');
    } catch (err) {
        console.log('playAudio error', err);
    }
}

So ive been debugging, and everything works fine, except that the bot wont actually play the audio? what could be the probable cause?

vocal cypress
peak bridge
vocal cypress could i get some more code? seeing this its prob something when calling the func...
async exec(msg, args) {
    console.log('init play');
    
    const results = await this.youtube.search(args);
    const result = results.pop();
    console.log('result', result.title);
    
    const voiceChannel = msg.member.voice.channel;
    const { connection, player } = await this.music.joinVoice(
        voiceChannel.id,
        voiceChannel.guild.id
    );
    const stream = await this.youtube.stream(result.id);
    await this.music.playAudio(player, stream);
}

heres the main execution, and the youtube is basically just a ytdl stream

vocal cypress
peak bridge
vocal cypress

hmm. then i dont know

peak bridge
harsh jacinth

Is the voice recording reliable? I have read it's quite unstable

A parameter to check would be somewhat like a conversation bot, where you can speak to it, and it can reciprocate with context

vocal cypress
vernal plover

Is it possible to run multiple JoinVoiceChannel() on 1 process? That is, so that 3 bots enter the voice from 1 code, for example

rotund turret

what is the "voiceAdapterCreator"?

vague summit

Hi! need help with my bot... after a few minutes it disconnect without reason (let's call it "ghost disconnect")... I verified and doesn't throw any error... Some days ago I just updated all the resources of the project (due I needed to implement modals and just in case)...

Also, I tried adding to verify with voicestateupdate for reconnect but, this only works if you (or someone) disconnect the bot, if was the ghost disconnect, it doesn't do anything

the dependencies, the script of events/ready.js and events/voiceStateUpdate.js are here (for avoid a looooong message):

https://gist.github.com/imkuroneko/755388f87da54f54f637692e2dfb1bea

dusty needleBOT

Suggestion for @vague summit:
guide Library: Handling disconnects
read more

finite grotto

how does this method fare for you? (the important part being, does the connection follow its lifecycle as expected?)

vague summit
haughty ingot
let channel = client.channels.cache.get(CHANNEL_ID) || await client.channels.fetch(CHANNEL_ID)

    if (!channel) return;
    const player = createAudioPlayer();
    const resource = createAudioResource('https://cdn.discordapp.com/attachments/877988588233580598/892818202399219763/bruh.mp3');

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

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

I am using this code but its not playing audio and their is no error

waxen wedge
waxen wedge
crisp glade
    try {
      const PremiumPlan = await Premium.findOne({ Id: message.author.id });
      if (PremiumPlan && PremiumPlan.isPremium) {
        //if user Premium code down here
        const player = message.client.manager.get(message.guild.id);

        if (!player.queue.current) {
          let thing = new MessageEmbed()
            .setColor(ee.embed.wrongcolor)
            .setDescription("There is no music playing.");
          return message.channel.send({ embeds: [thing] });
        }

    // Check that user is in the same voice channel
    if (message.member.voice.channel.id !== player.voiceChannel) {
    let thing = new MessageEmbed()
            .setColor(ee.embed.wrongcolor)
            .setDescription("User is in the same voice channel");
          return message.channel.send({ embeds: [thing] });
        }
        player.setNightcore(!player.nightcore);
        const msg = await message.channel.send(`Turning ${player.nightcore ? 'ON' : 'OFF'} **nightcore**. This may take a few seconds...`);
        let thing = new MessageEmbed()
        .setColor(ee.embed.color)
        .setTimestamp()
        .setDescription(`Turned ${player.nightcore} **nightcore**"`);
        await bot.delay(5000);
        if (player.nightcore) player.speed = 1.2;
        return msg.edit({ content: '​​ ', embeds: [thing] });
      } else {
        //if not user Premium code down here
        let thing = new MessageEmbed()
          .setColor(ee.embed.wrongcolor)
          .setDescription(`*You need to be a premium to use this command.*`);

        return message.channel.send({ embeds: [thing] });
      }
    } catch (err) {
      console.log(err);
      message.channel.send({
        content: `Something went wrong, try again later.`,
      });
    }```
Error
```json
TypeError: player.setNightcore is not a function```
subtle granite

It's erela.js not discord.js/voice

crisp glade
wary rain

what does it mean? everything worked fine before

slender sparrow

this is not play-dl support

karmic burrow
open heart

is it normal that in my node_modules i have '@discordjs' and discord.js

pseudo forum

yes

open heart

I'd like to uninstall just the 12.5.1 version

anyone know how to?

lilac beacon
open heart

oh... i see. the light uses 12.5 huh

I'm using a bot template (for command handling and everything) the guy used discord.js-light... can I replace all of his 'discord.js-light' imports with normal discord?

pseudo forum
open heart

thanks!

abstract acorn

wait

so
ytdl-core is kinda broken (as oflast time i checked)
play-dl is now dead
what's next??????

waxen wedge
abstract acorn

🙂

wary rain

what library would you recommend to use for music

pseudo agate

I'm just tinkering with discordjs 13 and I'm just trying to get it to join a voice channel.
I'm using the following to get it to just simply join the channel but it says
voice.channel.joinVoiceChannel() is not a function. Here is the section thats giving me an error

client.on('messageCreate', (message) => {
    if(message.content === '.join') {
        const { voice } = message.member

        if(!voice.channelId) {
            message.reply('You must be in a voice channel')
            return
        }

        voice.channel.joinVoiceChannel()
    }
})
frank kelp

joinVoiceChannel() is a function that is exported from @discordjs/voice

its not a method from voice.channel

next nacelle

"Audio players can be used to play audio across voice connections. A single audio player can play the same audio over multiple voice connections." but a bot can only be in one voice channel at a time, right?

waxen wedge
next nacelle

o that's what it meant. thank you!

next nacelle

everything was imported correctly.

var channel = message.member.voice.channel;
joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer({
    behaviors: {
          noSubscriber: NoSubscriberBehavior.Pause,
    },
});
const resource = createAudioResource(message.attachments.first().url);
player.play(resource);```
doesn't do anything. how can i play a .mp3 file attached to a message?
waxen wedge
subtle granite
 const moment = require("moment")

var temporary = [];
client.on('voiceStateUpdate', async (oldMember, newMember) => {
    const guild = client.guilds.cache.get("979260496098238504");

    const user = await client.users.fetch(newMember.id)
    let voiceCH = client.channels.cache.get("979260496098238508");
    let category = voiceCH.parent
    let wfschannel = client.channels.cache.get("979341639959072798");
    if (newMember.channel == voiceCH) {
        await newMember.guilds.channels.create(`『📞』𝐀𝐮𝐭𝐨𝐌𝐨𝐯𝐞`, {
          permissionOverwrites: [
            {
                id: newMember.id,
                allow: ["VIEW_CHANNEL"]
            },
            {
                id: newMember.guild.id,
                deny: ["VIEW_CHANNEL"]
            },
            {
                id: "979286838365782080",
                allow: ["VIEW_CHANNEL"]
            }
        ],
            type: 'voice', parent: category, userLimit: 10
        }).then(async (channel, error) => {
            temporary.push({ newID: channel.id, guild: channel.guild });
            await newMember.setChannel(channel.id).catch()
            const roleslist = ((newMember.member.roles.cache.filter((roles) => roles.id !== guild.id).sort((a,b) => b.position - a.position))).map((role) => role.toString()).join()
            const size = newMember.member.roles.cache.size - 1 

anyone know why the bot doesnt create a new private vc

and pull the person that joined the specific channel

subtle granite
wary rain

what library would you recommend to use for music

pseudo forum

play-dl (even if it's no longer maintained)

wary rain

play-dl

So I'm looking for another one

paper knoll

Hey, does anyone know if it is possible to access audio from voice channel with a bot that uses lavalink?

paper knoll

Sorry, I forgot

mystic oxide

Hi how do i fix this error:

`const subscription = connection.subscribe(player);
^

ReferenceError: connection is not defined
at video_player (C:\Users\Administrator\Desktop\Simba\discordbotz\commands\play.js:99:26)
at Object.execute (C:\Users\Administrator\Desktop\Simba\discordbotz\commands\play.js:69:21)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

Node.js v17.0.1`

finite grotto

define connection 🙂
joinVoiceChannel returns a VoiceConnection

mystic oxide

thanks

mystic oxide

I have managed to fix everything but when it joins a vc it doesn't play anything and theres no errors in the logs

subtle granite

How can i play audio?

dusty needleBOT

Suggestion for @subtle granite:
guide Library: Voice Connections
read more

whole compass

Hello, I'm trying to play an mp3 file. The bot is joining the channel but not playing anything.

const connection = joinVoiceChannel({
    channelId: "782730481904254987",
    guildId: "762075402570825748",
    adapterCreator: client.guilds.cache.get("762075402570825748")?.voiceAdapterCreator,
});

const player = createAudioPlayer();
const resource = createAudioResource(path.join(__dirname, "../assets/elevator_music.mp3"));
player.play(resource);

const subscription = connection.subscribe(player);
if (subscription) {
    setTimeout(() => subscription.unsubscribe(), 5_000);
}

I have discordjs/opus and ffmpeg-static installed

slender sparrow

do u have voice state intents?

whole compass
next nacelle
const player = createAudioPlayer();
const resource = createAudioResource('/home/user/voice/track.mp3');
const connection = joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
});
player.play(resource);
connection.subscribe(player);

is there a way to add a .mp3 to queue without using any external library other than @discordjs/voice?

slow osprey

Someone help me please?

exports.disconnect = (interaction) => {
    return new Promise(async (resolve, reject) => {
        console.log(await (await interaction.guild.members.fetch()).find(user => user.id ===             interaction.user.id));
        const user = await (await interaction.guild.members.fetch()).find(user => user.id ===            interaction.user.id);
        console.log(user.voice.channel);
        if (user.voice.channel == null) return resolve("You must be in a voice channel to use            this command!");
        user.voice.disconnect();
        resolve("You have been disconnected!");
    });
}

It doesn't refresh the interaction value if i leave or join a vc. No Error it just executes the same thing until i reload the bot.

stable rover

Hi folks, is there a guide for "receiving audio" in v13 as were in v12? I cant find it on the linked guide

stable rover
icy maple
muted mist

can i make a bot join a voice channel using the same structure as this one?

`bot.on('message', function (user, userID, channelID, message, evt) {

// Our bot needs to know if it will execute a command

// It will listen for messages that will start with !

if (message.substring(0, 1) == '!') {

var args = message.substring(1).split(' ');

var cmd = args[0];


args = args.splice(1);

switch(cmd) {

   // !ping

    case 'cf':

        bot.sendMessage({

            to: channelID,

            message: 'sunt viu, dude!'

        });

    break`
finite grotto
muted mist

i mean, by following the structure

`case 'cf':

        bot.sendMessage({

            to: channelID,

            message: 'sunt viu, dude!'

        });

    break`

to make it join in the same voice channel as the member is joined

finite grotto
muted mist

yes

finite grotto

then yes, you can do that whenever you want as long as the client is ready

muted mist

if i can use case to make it join

obtuse cradle

I was using ytdl-core to download my music and it was working fine, when i switched to the discord-ytdl-core (It returns an FFmpeg stream instead of an normal one) the player don't play anything, even if I pass through the demuxer, is there an special way to make the FFmpeg stream works?

finite grotto
obtuse cradle

Well, when I console.log the Ytdl-core stream, the constructor class is an Stream and when I do this with the discord-ytdl the class is called FFmpeg

slow osprey
obtuse cradle
obtuse cradle
finite grotto
obtuse cradle
celest plover

Hey there!

this.client.voice.adapters.set(this.id, methods);

TypeError: Cannot read properties of undefined (reading 'set')

Somebody knows how to fix this issue?

client.channels.fetch("946890839475515486")
        .then((channel) => {

            joinVoiceChannel({
                channelId: channel.id,
                guildId: channel.guild.id,
                adapterCreator: channel.guild.voiceAdapterCreator
            });
        });
languid quail
celest plover
pseudo forum
celest plover

@discordjs/voice@0.9.0

celest plover

pls

thorny quest

lol

lavish ice
export const playAudio = async (interaction)=>{
    const voiceChannel = interaction.member.voice.channel;
    if(!voiceChannel) return ;
    try {
        const connection = joinVoiceChannel({
            channelId:voiceChannel.id,
            guildId: interaction.guild.id,
            adapterCreator:interaction.guild.voiceAdapterCreator,
            selfDeaf:false,
            selfMute:false,
        })
        interaction.channel.send(`${interaction.client.user.username} has joined the voice channel`)
    } catch (error) {
        await interaction.channel.send("Unable to join voice channel")
    }
}
```for some reason this function does not run the same time all the time. It sometime connects to the voice channel but sometimes doesnt. Any reason why that i'm missing?
icy maple
dusty needleBOT
lean storm

how to join a voice channel

dusty needleBOT

Suggestion for @lean storm:
guide Library: Voice Connections
read more

lean storm
mighty lotus

client.on('message', message => { connection = joinVoiceChannel({ channelId: message.member.voice.channel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator, }) })

waxen wedge
mighty lotus
trim iris

The Voice Channels Data isn't getting updated when i move the bot from Voice 1 to Voice 2 when i try to eval bots voice channel it returns voice 1 instead of voice 2
can anyone help me with this?
Note: i have already added GUILD_VOICE_STATES Intent

subtle granite

Try <guild>.me.voice.channel

trim iris

like it joined vc 1 eval shows vc 1 then i shifted the bot to vc 2 and evaled then it also returns vc 1

lean storm
TypeError: Cannot read properties of undefined (reading 'once')
    at AudioPlayer.play (E:\discord bot\node_modules\@discordjs\voice\dist\index.js:964:25)
    at Object.execute (E:\discord bot\commands\say.js:32:20)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) unhandledRejection
    ```
radiant spindle
lean storm
radiant spindle
lean storm
radiant spindle what does buffer log as?
<Buffer ff f3 44 c4 00 11 98 e1 b8 01 49 48 00 9c e7 44 01 40 40 90 b8 00 0c 26 17 04 cd a4 83 10 20 41 8b 8a c1 32 74 81 32 75 02 84 89 85 c3 6f 23 27 9d 41 ... 6958 more bytes>
radiant spindle

right

lean storm
radiant spindle

looks like docs says AudioPlayer.play expects a type AudioResource so that's probably a hint towards what is wrong here

radiant spindle

Buffer is not a AudioResource no

lean storm
radiant spindle
lean storm
radiant spindle i'm not sure what to expect but try using `createAudioResource` from voice
Error: FFmpeg/avconv not found!
    at Function.getInfo (E:\discord bot\node_modules\prism-media\src\core\FFmpeg.js:143:11)
    at Function.create (E:\discord bot\node_modules\prism-media\src\core\FFmpeg.js:156:38)
    at new FFmpeg (E:\discord bot\node_modules\prism-media\src\core\FFmpeg.js:45:27)
    at Object.transformer (E:\discord bot\node_modules\@discordjs\voice\dist\index.js:1780:27)
    at E:\discord bot\node_modules\@discordjs\voice\dist\index.js:1936:58
    at Array.map (<anonymous>)
    at createAudioResource (E:\discord bot\node_modules\@discordjs\voice\dist\index.js:1936:39)
    at Object.execute (E:\discord bot\commands\say.js:27:28)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) unhandledRejection

lavish ice
export const playAudio =  async (interaction)=>{
    const voiceChannel = interaction.member.voice.channel; // check if user is in voice channel
    if(!voiceChannel){
        return await interaction.reply({content:"You must be in a voice channel to use this command"})
    }
    try{
        const connection = joinVoiceChannel({
            channelId:voiceChannel.id,
            guildId: interaction.guild.id,
            adapterCreator:interaction.guild.voiceAdapterCreator,
            selfDeaf:false,
            selfMute:false,
        })
        let url = interaction.options.getString("query")
        let vid = ytdl(url)
        const resource = createAudioResource(vid)
        const player = createAudioPlayer()

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


    }catch(e){
        await interaction.reply(`Un able to play youtube video`)
    }
}
``` for some reason my audio resource is not running, i get no errors in the catch block as well.

any idea why?

lavish ice
lean storm

so tht u get to know where is the problem\

signal depot

and you should google your error (Thomas Shelby)

pseudo forum
lean storm
pseudo forum `npm i ffmpeg-static@latest`
TypeError: Cannot read properties of undefined (reading 'once')
    at AudioPlayer.play (E:\discord bot\node_modules\@discordjs\voice\dist\index.js:964:25)
    at Object.execute (E:\discord bot\commands\say.js:34:20)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) unhandledRejection

pseudo forum
lean storm
pseudo forum show your code and do `npm ls discord.js` / `npm ls @discordjs/voice`
    at new NodeError (node:internal/errors:371:5)
    at _write (node:internal/streams/writable:312:13)
    at Socket.Writable.write (node:internal/streams/writable:334:10)
    at pump (node:internal/streams/pipeline:150:21)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  resource: AudioResource {
    playStream: OggDemuxer {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      _remainder: null,
      _head: null,
      _bitstream: null,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    edges: [ [Object], [Object] ],
    metadata: null,
    volume: undefined,
    encoder: undefined,
    audioPlayer: AudioPlayer {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      _state: [Object],
      subscribers: [],
      behaviors: [Object],
      debug: [Function (anonymous)],
      [Symbol(kCapture)]: false
    },
    playbackDuration: 0,
    started: false,
    silencePaddingFrames: 5,
    silenceRemaining: -1
  }
} uncaughtException
lean storm
pseudo forum show your code and do `npm ls discord.js` / `npm ls @discordjs/voice`
const { MessageEmbed } = require('discord.js');
const {joinVoiceChannel} = require("@discordjs/voice");
const tts = require('google-translate-tts');
const { createAudioPlayer, NoSubscriberBehavior , createAudioResource } = require('@discordjs/voice');

module.exports ={
    name: `say`,
    permissions: [],
    cooldowns: 0,
    description: `bj`,
     async execute(client, message, args, Discord, profileData , LevelData) {
        args = args.join(" ");
        let  voiceChannel  = message.member.voice.channel;
        if(!args)message.reply("Tell me something to say")
        else if(!voiceChannel) message.reply("Please Join a voice channel")
        else if(voiceChannel){
            const connection = joinVoiceChannel({
                channelId: voiceChannel.id,
                guildId: message.guild.id,
                adapterCreator: message.guild.voiceAdapterCreator,
            });
            const buffer = await tts.synthesize({
                text: 'Hello, world!',
                voice: 'en',
                slow: false // optional
            });
            let resource = createAudioResource(buffer);
            const player = createAudioPlayer({
                behaviors: {
                    noSubscriber: NoSubscriberBehavior.Pause,
                },
            });
            console.log(buffer);
            player.play(resource);
        }
    },
};
lean storm
radiant spindle
lean storm

before this it joined channel but did not play nothing

radiant spindle

don't think that's voice causing it, something something network settings + i cant replicate

lean storm
radiant spindle

yes, voice is throwing the error, but the error is thrown probably because of your network settings

lean storm
radiant spindle

because that's when it begins to create the socket

lean storm

doesnt log anything

radiant spindle

because it crashes

lean storm
radiant spindle

okay well the error is because it can't perform ip discovery

only thing i can say is its probably a firewall setting to discord

lean storm

now it has no error but doesnt play anything

radiant spindle

i doubt that changes anything

lean storm
radiant spindle

what is your code now

lean storm
radiant spindle what is your code now
const { MessageEmbed } = require('discord.js');
const {joinVoiceChannel} = require("@discordjs/voice");
const tts = require('google-translate-tts');
const { createAudioPlayer, NoSubscriberBehavior , createAudioResource } = require('@discordjs/voice');

module.exports ={
    name: `say`,
    permissions: [],
    cooldowns: 0,
    description: `bj`,
     async execute(client, message, args, Discord, profileData , LevelData) {
        args = args.join(" ");
        let  voiceChannel  = message.member.voice.channel;
        if(!args)message.reply("Tell me something to say")
        else if(!voiceChannel) message.reply("Please Join a voice channel")
        else if(voiceChannel){
            const connection = joinVoiceChannel({
                channelId: voiceChannel.id,
                guildId: message.guild.id,
                adapterCreator: message.guild.voiceAdapterCreator,
            });
            const buffer = await tts.synthesize({
                text: 'Hello, world!',
                voice: 'en',
                slow: false // optional
            });
            const { Readable } = require("node:stream");
            const bufferToStream = (binary) => {
            const readableStream = new Readable({
                read() {
                this.push(binary);
                this.push(null);
                }
            });
            return readableStream;
            };
            const resource = createAudioResource(bufferToStream(buffer));
            const player = createAudioPlayer({
                behaviors: {
                    noSubscriber: NoSubscriberBehavior.Pause,
                },
            });
            player.play(resource)
        }
    },
};```
radiant spindle

you never subscribed the connection to the player

lean storm
radiant spindle

connection.subscribe(player)

lean storm

wht does it do

radiant spindle
lean storm wht does it do

for simplicity i'd say it just makes the connection follow the audio player, multiple connections can follow an audio player but multiple audio players cant be fed into one connection, when the audio player actually plays, the connection will "stream" that

lean storm

ok . is there any way to know that the audio playing is complete or should we just code it on our own

radiant spindle
lean storm

i tried voiceChannel.disconnet() and voiceChannel.leave() i doesnt work

lean storm
languid quail

because it started playing audio twice?

lean storm

no its playing only once

lean storm
subtle granite

Because you attached the same listener twice probably

subtle granite

Hello someone have a join voice channel code v13?

subtle granite
prime mulch
mystic oxide

I have been making a music bot for my discord server and the bot joins the vc but It doesn't play anything and it doesn't log an error

subtle granite

Do you have the voice states intent?

mystic oxide

Is it the guild_voice_states if its that yes

mystic oxide

Or I think I can find it hold on

radiant spindle

Yeah I cant read that

mystic oxide

I'll send a better version when I get home

ashen wave

Hi, I'm trying to implement a /seek command. It does work - the audioresource does in fact skip forward to w/e specified time, but when I log the playbackDuration, it starts from 0 rather than the seek forwarded time.

In this screenshot, the expected result was supposed to be like 200000 for 200s

Anyone know how to fix?

icy maple
ashen wave

Lol, I was thinking of doing that, but I assumed I was just doing something wrong for the timestamp being wrong, lol.

Is playbackDuration working as intended? Or could there be a possibility that the method itself is broken?

icy maple

That’s how it works

It’s the amount of time it actually played/consumed

It doesn’t consider the skipped time, pretty sure it doesn’t even know

ashen wave

I see. Fair enough. I guess I'll do the add amount skipped bit, ty. blobthumbsup

shrewd compass

Witht this code, if exists vc if forst interaction timeout is over but during this i use 2nd command but its timeout isnt considered what can i do?

setTimeout(() => {
  const connection = getVoiceConnection(interaction.guildId);
  connection.destroy();
}, 1* 60 * 1000)   
radiant spindle
shrewd compass

Did you understood now?

radiant spindle

so basically you use this command and then another command which interrupts the timeout?

shrewd compass
radiant spindle

no, but you should handle the case that the connection is already destroyed or store the response from setTimeout (an id to clear) so that you can clear it when you want, like when you begin the second command

waxen wedge
shrewd compass

I have never worked with storing things can you help me?

waxen wedge

Easiest way is to attach it to the client, like client.vcTimeout = setTimeout(…) and then use that to clearTimeout(client.vcTimeout). If your bot is in more than one VC at a time you’d need to make it a collection instead and get the appropriate timeout ID from it

shrewd compass
waxen wedge
shrewd compass
shrewd compass
shrewd compass
waxen wedge Yes

Like ofc bot would be in more than 1 vcs but when i do interaction.guildId i would only clear the timeout for that particular guild right?

waxen wedge
shrewd compass
dusty needleBOT

Documentation suggestion for @shrewd compass:
class Collection
A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has an ID, for significantly improved performance and ease-of-use.

zealous blade

The relevant code

const player = createAudioPlayer();```


__**The error:**__
```ReferenceError: createAudioPlayer is not defined
    at Client.<anonymous> (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\src\index.js:248:20)
    at Object.onceWrapper (node:events:642:26)
    at Client.emit (node:events:527:28)
    at WebSocketManager.triggerClientReady (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:17)
    at WebSocketManager.checkShardsReady (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketManager.js:367:10)
    at WebSocketShard.<anonymous> (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketManager.js:189:14)
    at WebSocketShard.emit (node:events:527:28)
    at WebSocketShard.checkReady (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)  
    at WebSocketShard.onPacket (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketShard.js:447:16)    
    at WebSocketShard.onMessage (C:\Users\emre2\OneDrive\Desktop\Coding\Visualstudiodateien\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)   
[nodemon] app crashed - waiting for file changes before starting...```

Anyone know why this error occurs?

cosmic lagoon

createAudioPlayer doesnt exist on @discordjs/voice

zealous blade
zealous blade

Yeah it exists, anyone knows why this happens?

eager lake

show src\index.js:248:20

zealous blade

I use createAudioPlayer in onReady. And require it at the beginning of the code.

cosmic lagoon
zealous blade
zealous blade
eager lake

nope, sorry

zealous blade

It works on my server.

waxen wedge
zealous blade

It functions now, took old code and just copy pasted the new code into it. It somehow works ¯_(ツ)_/¯

shrewd compass
waxen wedge
dusty needleBOT

Suggestion for @shrewd compass:
guide Additional Information: Collections
read more

shrewd compass
waxen wedge
shrewd compass

cookieCat

sudden hawk

is there a way to "receive" audio with discordjs/voice?

waxen wedge
shrewd compass

The code

waxen wedge

So .set(interaction.guildId, setTimeout(…)) and clearTimeout(…get(interaction.guildId)

shrewd compass
waxen wedge
shrewd compass
shrewd compass

i replaced the guildID with interaction.guildId

waxen wedge
shrewd compass okay i came up with this now

You still have the hardcoded string 'guildId' instead of the actual ID as key… also you don’t need to assign the setTimeout to another var, because you already put it into the collection now

shrewd compass
waxen wedge
shrewd compass
waxen wedge The var from timeout or directly put the setTimeout in the set. Matter if coding...
  clearTimeout(client.vcTimeout);
  vcTimeout =   setTimeout(() => {
  const connection = getVoiceConnection(interaction.guildId);
  connection.destroy();
}, 1 * 60 * 1000) 

        });
           client.vcTimeouts = new Collection();
           client.vcTimeouts.set(interaction.guildId,  client.vcTimeout =   setTimeout(() => {
  const connection = getVoiceConnection(interaction.guildId);
  connection.destroy();
}, 1 * 60 * 1000) );
          console.log(client.vcTimeouts.get('interaction.guildId'));

see i have this anything to add or anything to remove?

ig i have to remove vcTimeout part from this?

waxen wedge
shrewd compass
shrewd compass
shrewd compass

New Code

   clearTimeout(client.vcTimeouts);
let vcTimeout =   setTimeout(() => {
  const connection = getVoiceConnection(interaction.guildId);
  connection.destroy();
}, 1 * 60 * 1000)
           client.vcTimeouts = new Collection();
           client.vcTimeouts.set(`${interaction.guildId}`,  vcTimeout =   setTimeout(() => {
  const connection = getVoiceConnection(interaction.guildId);
  connection.destroy();
}, 1 * 60 * 1000) );
waxen wedge
shrewd compass
shrewd compass
waxen wedge
shrewd compass
waxen wedge
shrewd compass
waxen wedge
shrewd compass
client.vcTimeouts.set(`${interaction.guildId}`,  vcTimeout =   setTimeout(() => {
  const connection = getVoiceConnection(interaction.guildId);
  connection.destroy(); //this is line 92
}, 1 * 60 * 1000) );
shrewd compass
waxen wedge
shrewd compass
shrewd compass
fervent estuary

just check if the connection has already been destroyed before destroying it

shrewd compass
pseudo forum

if (connection) connection.destroy()

shrewd compass
waxen wedge
shrewd compass
pseudo forum
shrewd compass
shrewd compass

notLikeCrawl

waxen wedge
waxen wedge
shrewd compass
sudden hawk
waxen wedge
shrewd compass
waxen wedge Yes

Okay it works but i am on mobile couldn't verify for multiserver thing i will let yk tmrw thanks for spending time and letting me know interesting things :)

waxen wedge
sudden hawk
forest lantern

hi, i have an issue with the installation of discordjs/opus, should i ask it here?

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

module.exports = {
    name:"play",
    description: "Connects and Plays music",
    data: new SlashCommandBuilder().setName('play').setDescription('Connects and plays audio')
        .addStringOption(option=>option
            .setName('query')
            .setDescription('string that is the youtube url')
            .setRequired(true)),

    async execute(interaction){
        const voiceChannel = interaction.member.voice.channel;
        if(!voiceChannel){
            await interaction.reply("You must be in a voice channel to use this command") // triggered if interaction is used when user is not in a voice channel
            return;
        } 

        try{
            const connection  = joinVoiceChannel({
                guildId: interaction.guild.id,
                channelId: voiceChannel.id,
                adapterCreator: voiceChannel.guild.voiceAdapterCreator,
                selfDeaf:false,
                selfMute:false,
            })
            const youtubeVid = ytdl( interaction.options.getString('query'),{filter: 'audioonly'}) // returns internal.readable 
            const resource = createAudioResource(youtubeVid);
            player.play(resource)
            connection.subscribe(player)
        }catch(err){
            interaction.reply(`There was an-error during the connection and playing of music ${err}`)
        }

    },
}
``` for some reason my bot will not play music i run this.

it connect to the voice channel but nothing is played

the slash command takes in a youtube url as an argument

white talon
Uncaught Exception Thrown
AudioPlayerError: aborted
    at connResetException (node:internal/errors:691:14)
    at TLSSocket.socketCloseListener (node:_http_client:402:19)
    at TLSSocket.emit (node:events:538:35)
    at node:net:687:12
    at TCP.done (node:_tls_wrap:580:7) {
  resource: AudioResource {
    playStream: OggDemuxer {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      _remainder: null,
      _head: null,
      _bitstream: null,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: [Function: bound onwrite]
    },
    edges: [ [Object], [Object] ],
    metadata: null,
    volume: undefined,
    encoder: undefined,
    audioPlayer: AudioPlayer {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      _state: [Object],
      subscribers: [Array],
      behaviors: [Object],
      debug: [Function (anonymous)],
      [Symbol(kCapture)]: false
    },
    playbackDuration: 25740,
    started: true,
    silencePaddingFrames: 5,
    silenceRemaining: -1
  }
}

Anyone know why this happens?

soft silo

does anyone know how to install opus on linux

radiant spindle
soft silo

no it creates an error

radiant spindle

which is?

shrewd compass

Why this thing isn't working

const subscription = connection.subscribe(player);
if (subscription) return interaction.reply({
             ephemeral:true,
             content: 'Lol No!'
           }); 
uneven pendant

how do i create a listen stream for a voice channel and/or person in vc?

fervent estuary
vale eagle

How could I merge two opus streams into one or play 2 opus streams simultaneously in one vc?

shrewd compass

Or regardless case1 or case2 it semds only case1 msg

(and ping me pls lol)

uneven pendant

what is the default encoding for a receiver audio stream? im trying to know the encoding format etc since im trying to use google's speech to text api. Do i need to use prism media to encode it/re encode it?

waxen wedge
shrewd compass

I am making a tts bot the problem is whenever a command is used regardless the previous tts comamnd is over it starts the new one.

For eg-
/smr: something big sentence (First tts command is going on but i use second command)
/smr some thing new big sentence
(it stops the first tts and plays second) how do i prevent this thing? Someone knows? Like i dont wanna make queue i want like if bot is speaking something in vc then just send emprehal msg that a tts is going on pls wait how can i do that?
I used voice channel state it don't seem to work and also I tried this but it always shows the emprehal msg tho if it is case2 or case 1

Code-

const subscription = connection.subscribe(player);
if (subscription) return interaction.reply({
             ephemeral:true,
             content: 'Lol No!'
           }); 

Using discord.js latest version

And by using promise resolve it doesn't get that the content was Sayed out in VC or not it only checks till bot joined VC and started speaking

waxen wedge
shrewd compass
waxen wedge
shrewd compass
waxen wedge
shrewd compass
if (!player.state === Idle) return interaction.reply({
             ephemeral:true,
             content: ''somethin
           });
            ```
Like this? I think  you meaned this?
waxen wedge
shrewd compass
shrewd compass
shrewd compass
waxen wedge
shrewd compass
odd hull

I am not sure it is related with discord.js, but after playing music for some minutes this error pop up:
Error: aborted
at connResetException (node:internal/errors:692:14)
at TLSSocket.socketCloseListener (node:_http_client:414:19)
at TLSSocket.emit (node:events:539:35)
at node:net:715:12
at TCP.done (node:_tls_wrap:582:7)
[ERROR] 18:45:08 Error: aborted

This only happens when the bot is playing music.

waxen wedge
pseudo forum
odd hull

oky, i was just writing that my resources is from ytdl-core, XD

thank you

shrewd compass
vale eagle

How would I merge two opus streams
I need to play 2 or more opus streams together in a vc

languid quail
subtle granite

Error: Cannot find module '/home/container/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm64-glibc-2.31/opus.node'

Help me

subtle granite

solved

toxic solar

so, running into an odd issue, not sure if it's actually a bug in voice or not

if I play an audio stream over a connection, i'm no longer able to play any resource created with a file path, only able to play streams after that (even creating a new audio player and new audio resource)

waxen wedge
toxic solar
fickle quartz

How can I make my bot search a youtube video only via the title of the video pls ?

finite grotto
fickle quartz

i just dont know how to do it but i know it's possible

fickle quartz
finite grotto
finite grotto
icy maple

Reinstall the voice package

next nacelle

what's meant by "clean them up"?

fervent estuary

deleting/erasing every instance of the connection you have stored in ur code

zealous blade
    const music = path.join(__dirname, 'Warteschleifeend.mp3' )
    const resource = createAudioResource(music, { inlineVolume: true })
    resource.volume.setVolume(0.5);
    player.play(resource)
    

    const channel = client.channels.cache.get(queue);
    const connection = joinVoiceChannel({
    channelId: queue,
    guildId: serverid,
    adapterCreator: channel.guild.voiceAdapterCreator,
    
})
const subscription = connection.subscribe(player)

player.on(AudioPlayerStatus.Playing, () => {
    console.log("The music is now playing.")
} )
player.on('error', error => {

    console.error(`Error: ${error.message}`)
    
})
player.on('idle', idle => {

    console.log(`Starte neu`)
    client.user.setActivity("im Support");
    const resource = createAudioResource(music, { inlineVolume: true })
    resource.volume.setVolume(0.35);
    player.play(resource)
}) ```

This is the code of my bot that normally plays 24/7 music, it worked before, but I programmed some new stuff and now it doesnt function anymore:

It still gives out: "The music is now playing.", but it doesnt.
But beforehand it gave it out twice, now it gives it out only once

What is odd is that both input and output are deactivated. How do i activate them?

waxen wedge

selfMute: false and selfDeaf: false

zealous blade

Ok unmuted, but still not playing

zealous blade
waxen wedge
waxen wedge
zealous blade

I restarted my bot a lot today, and really quickly. Is there a way to clear the player and everything?

ReferenceError: createReadstream is not defined, even though I require it. @waxen wedge

waxen wedge
zealous blade
uneven pendant

i havent done much with audio

waxen wedge
next nacelle
const { createAudioPlayer } = require('@discordjs/voice');
let player = createAudioPlayer({
    behaviors: {
        maxMissedFrames: 5 // by default
    }
})```
if i change `maxMissedFrames` to say 20, does this make the bot hang longer at the end of a song? what does it do?
crude stream

HELP ME

dusty needleBOT

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

waxen wedge
zealous blade

The bot joins the channel, but doesnt play anything. Also the bot was working beforehand.
And I also use them gor other code, so yes they are correct

waxen wedge
zealous blade
waxen wedge
zealous blade
zealous blade
zealous blade

resource: [Circular *1],

Is it normal that resource is this, when logging my resource?

fiery blade
spice flint
        channelId: interaction.member.voice.channel.id,
        guildId: interaction.guild.id,
        adapterCreator: interaction.guild.voiceAdapterCreator,
      });
      const resource = createAudioResource("test.mp3");
      connection.subscribe(player);
      player.play(resource);
      await interaction.reply('Playing.');```My bot joins the channel but I just can't get it to play audio
loud sinew
spice flint
loud sinew

hmm

spice flint
loud sinew hmm

But I know that its using my test.mp3 while running, because I can't tamper with it between.

loud sinew

do you have all the dependencies listed in the guide?

spice flint
loud sinew

no i meant your package.json

spice flint
loud sinew

install libsodium-wrappers and try it then

spice flint
loud sinew
spice flint
loud sinew oh fuck i forgot you also need ffmpeg to play mp3 files ``` npm i ffmpeg-static ...

my package.json "dependencies": { "@discordjs/opus": "github:discordjs/opus", "@discordjs/rest": "^0.5.0", "@discordjs/voice": "^0.10.0", "discord-api-types": "^0.33.3", "discord-buttons": "^4.0.0-deprecated", "discord-voice": "^2.0.6", "discord.js": "^13.7.0", "ffmpeg": "^0.0.4", "ffmpeg-static": "^4.4.1", "fs": "^0.0.1-security", "libsodium-wrappers": "^0.7.10", "stream": "^0.0.2", "ytdl-core": "^4.11.0", "ytdl-core-discord": "^1.3.1" }

loud sinew

still doesnt work?

spice flint
loud sinew

hmm im comparing my music bot to yours right now, and as far as i can see you have the same dependencies and also your code is the same, so i have no idea why it doesnt work

spice flint

any idea?

fiery blade
spice flint

Like this player.play(resource); connection.subscribe(player); Doesn't work

fiery blade
spice flint
waxen wedge