#archive-voice

30636 messages · Page 27 of 31

twilit horizon

Hello, I want my bot to play music but I'm getting this error what should I do?

dreamy drum

pass intents array to main client object

twilit horizon
slender sparrow

show your client options

twilit horizon
slender sparrow

client options

sullen yacht

How do I get the docs for the joinVoiceChannel method?

dusty needleBOT

Tag suggestion for @hasty bough:
Frequently Asked Questions: learn more

hexed mesa

Hey everyone! Need a lil help help here.
So, I want to make a bot that when he startup he direct connect to a channel, without command or anything. So, I wrote this :

    console.log("Pret")
    joinVoiceChannel({
            channelId: Channel,
            guildId: Guild,
})});```
 

Channel and Guild are defined in a const. 
But, When I start the bot, it crash with this (see image)...This error code is not really useful. Yeah, "o" is not a function. And what.
Thanks for your answer, if you answer.
rose helm

what is it

worn kraken
    at Socket.<anonymous> (/home/container/node_modules/@discordjs/voice/dist/index.js:1:6361)
    at Object.onceWrapper (node:events:639:28)
    at Socket.emit (node:events:532:35)
    at socketCloseNT (node:dgram:763:8)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)```

what can i do?

severe shale
worn kraken

That has nothing to do with it, I've had it for weeks

rugged sky
hexed mesa

Okay, thanks, I will try that. Thanks you !

violet sierra

can someone help me with my music command

my bot joins the voice channel and sends which video is playing it just doesnt play anything

const ytdl = require('ytdl-core');
const ytsearch = require('yt-search')
const Discord = require('discord.js')
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]})
const {
    joinVoiceChannel,
    createAudioPlayer,
    createAudioResource,
    NoSubscriberBehavior
} = require('@discordjs/voice');


module.exports = {
    name: "play",
    description: "play test",

    async execute(message, args) {

        const voiceChannel = message.member.voice.channel;
        if (!voiceChannel) return message.channel.send('Please connect to a voice channel!');
        if (!args.length) return message.channel.send('Please Provide Something To Play!')

        const connection = await joinVoiceChannel({
            channelId: message.member.voice.channel.id,
            guildId: message.guild.id,
            adapterCreator: message.guild.voiceAdapterCreator
        });
        const videoFinder = async (query) => {
            const videoResult = await ytsearch(query);
            return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;


        }
        const video = await videoFinder(args.join(' '));
        if (video) {
            const stream = ytdl(video.url, { filter: 'audioonly' });
            const player = createAudioPlayer();
            const resource = createAudioResource(stream)

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




            await message.reply(`Now Playing ***${video.title}***`)
            
        } else {
            message.channel.send('No video results found');
        }



    }
}```

here is my code

also no errors when using the command

summer crow

my bot is inside a voice channel and still the

const connection = getVoiceConnection(message.guildId!)!;
``` returns `undefined`
why so?
slender sparrow
violet sierra
slender sparrow
violet sierra

thanks

violet sierra
summer crow

the getVoiceConnection isn't working for me

hexed mesa
rugged sky
hexed mesa

So I just type adapterCreator:voiceAdapterCreator ?

rugged sky
hexed mesa

Ohhhhhhhhhhhhhhhhh

Like
adapterCreator: 565599771872722944.voiceAdapterCreator ?

rugged sky
hexed mesa

Hmm
I admit I am a little confused (in addition that I'm french so it's not easy...) I will try what you wrote later, my server is down
Anyways, thanks for the help dude.

dreamy drum
dreamy drum
rose helm

No. Streams do not save data they emit, so if the stream has already started or ended, you cannot reuse it

zenith lichen

Hey, can anyone help me figure out what's wrong with my code.
So i am making a bot that can record voice channels. Though the bot is working fine, Just that when each individual recording mixed with other people's recording things dont sync up.

i suspect that there is some issue with start and end events.

Here's my recording logic btw

tender root

How do I get user voice data(speaking, stop speaking, voice data/recording)? (just need the stream, not a file or anything)

zenith lichen

subscribe to the userId of the user you want data of

hexed mesa
frank kelp
hexed mesa

Hmm...
I...don't know what is it, sorry..

frank kelp

const guild = await client.guilds.fetch("565599771872722944")

hexed mesa

SyntaxError: await is only valid in async functions and the top level bodies of modules

I think I need more experience with JS. If I don't even know why I'm using this function I'm not advancing.

dusty needleBOT

_ async function
An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

hexed mesa

Yeah, I figured out how to start it.

The bot started
He didn't crashed
But he didn't joined the channel

frank kelp

what does your code look like now

hexed mesa
Client.on("ready", async () => {
    console.log("Pret")
    const guild = await Client.guilds.fetch("565599771872722944");
    joinVoiceChannel({
            channelId: 950804559146672168,
            guildId: 565599771872722944,
            adapterCreator: guild.voiceAdapterCreator,
})});

Maybe he join the channel and directly left it

frank kelp

ids are strings (in joinVoiceChannel())

you have to wrap them in " like you did in client.guilds.fetch()

hexed mesa

Oh thanks god it works. Thank you so much. Sometimes coding is really just about how much important are symbols...

hexed mesa

If it was the last problem...
Now my code is that.


Client.on("ready", async () => {
    console.log("Pret")
    const guild = await Client.guilds.fetch("565599771872722944");
    joinVoiceChannel({
            channelId: "950804559146672168",
            guildId: "565599771872722944",
            adapterCreator: guild.voiceAdapterCreator,
})
    const { getVoiceConnection } = require('@discordjs/voice');
    const connection = getVoiceConnection('950804559146672168');
    const { createAudioPlayer } = require('@discordjs/voice');
    const player = createAudioPlayer();
    const subscription = connection.subscribe('player');
    const { VoiceConnectionStatus } = require('@discordjs/voice');
    connection.on(VoiceConnectionStatus.Ready, () => {
    console.log('The connection has entered the Ready state - ready to play audio!');
    const resource = createAudioResource('opbajvpc.mp3');
    player.play(resource);
})});``` 

And I get this when I start it. 
Yeah, I understand. "Subscription" has to be defined. But with what ?
rugged sky
hexed mesa If it was the last problem... Now my code is that. ```d Client.on("ready", as...

It's actually connection that has to be defined. JS is weird like that, but here it's trying to read subscribe as a property of connection which it's then saying is undefined. The actual connection object is a return value of the joinVoiceChannel() function so you can just store that in a variable instead of using getVoiceConnection() that should work just fine.

On a separate note, you should refer to the player object instead of 'player' as a String in the parameter of the .subscribe() method. I would really recommend following an online course or something on Javascript before undergoing a project like this because errors like these will be common and are easily avoidable.

hexed mesa

Thanks you!

round grail

What are the ways to make the quality of the audio better. Without the connection issues

summer crow

which audio format would be played directly into discord voice channel without any converting?

tame ember

Guys ls help i am trying to make a bot that plays an mp3 file when it joins the voice channel. It does join but then doesnt play the mp3 file

client.on('message', message => {
  if (isReady && message.content === 'a')
  {
  isReady = false;
  var voiceChannel = message.member.voice.channel;
  voiceChannel.join().then(connection =>
  {
     const dispatcher = connection.playFile('./song.mp3');
     dispatcher.on("end", end => {
       voiceChannel.leave();
       });
   }).catch(err => console.log(err));
   isReady = true;
  }
});

error:

(node:1686) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined
round grail
tame ember
rugged sky
rose helm
round grail What are the ways to make the quality of the audio better. Without the connectio...

If you're on mobile, there's nothing that can be done since the clients compress the audio a ton for whatever stupid reason. Otherwise, the voice channel bitrate needs to be the desired amount and you should be fetching audio which matches that bitrate or is higher and it'll be compressed down to the max bitrate of the channel. If you can't get any higher quality audio, then you're SOL

rose helm

There is no code that's universal that just magically makes your audio sound better. It's a concept you have to apply yourself

round grail

ooh ok

round grail
rose helm

No

it could even make it worse

round grail

ooh I see

Thank you I will see what I can do - Thanks alot

round grail
rose helm

Gotta store your stuff in some form of persistent storage, rejoin voice channels, create connections and stuff through djs voice, seek to last known position + some compensation since it takes time to do all that in resource and that's it

round grail

hmm oks - Thanks

lyric merlin

What is the equivalent of connection.receiver.createStream function, but in @discordjs/voice?

cosmic prawn

hi
is playing songs on one player better
or making new player and destroying old player whenever song changes is better

violet sierra
const ytsearch = require('yt-search');
const Discord = require('discord.js')
const {
    joinVoiceChannel,
    createAudioPlayer,
    createAudioResource,
    NoSubscriberBehavior
} = require('@discordjs/voice');


module.exports = {
    name: "play",
    description: "test command",

    async run(client, message, args) {

        const voiceChannel = message.member.voice.channel;
        if (!voiceChannel) return message.channel.send('Please connect to a voice channel!');
        if (!args.length) return message.channel.send('Please Provide Something To Play!')

        const connection = await joinVoiceChannel({
            channelId: message.member.voice.channel.id,
            guildId: message.guild.id,
            adapterCreator: message.guild.voiceAdapterCreator
        });
        const videoFinder = async (query) => {
            const videoResult = await ytsearch(query);
            return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;


        }
        const video = await videoFinder(args.join(' '));
        if (video) {
            const stream = ytdl(video.url, { filter: 'audioonly' });
            const player = createAudioPlayer();
            const resource = createAudioResource(stream)

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




            await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
            
        } else {
            message.channel.send('No video results found');
        }



    }
}

why does this code not work (the bot joins the channel and sendss which video but doesnt play it)

cosmic prawn
subtle granite
TypeError: o is not a function
    at new G (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\@discordjs\voice\dist\index.js:8:7254)
    at Oe (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\@discordjs\voice\dist\index.js:8:12358)
    at Object.gt (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\@discordjs\voice\dist\index.js:8:12577)
    at Client.<anonymous> (C:\Users\Administrator\Desktop\uwu\musicfly\index.js:41:37)
    at Client.emit (node:events:390:28)
    at WebSocketManager.triggerClientReady (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:17)
    at WebSocketManager.checkShardsReady (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\discord.js\src\client\websocket\WebSocketManager.js:367:10)
    at WebSocketShard.<anonymous> (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\discord.js\src\client\websocket\WebSocketManager.js:189:14)
    at WebSocketShard.emit (node:events:390:28)
    at WebSocketShard.checkReady (C:\Users\Administrator\Desktop\uwu\musicfly\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
client.on("ready",async () => {
    console.log("ready")
    const connection =Discordvoice.joinVoiceChannel({
    channelId: "932427071911780372", guildId: "870706429995130882",
    adapterCreator:client.guilds.cache.get("870706429995130882")?.voiceAdapterCreator as Discord.InternalDiscordGatewayAdapterCreator
})
frank kelp

the guild probably wasnt found in the cache. try removing the optional chaining on the client.guilds.cache.get(). it doesn't really matter if you use it or not since it wont work either way, and it will make the error more readable

covert sigil

what format does AudioPlayer.play()'s resource use? I'm trying to use TTS and I'm confused by what I should be converting it to

rose helm
covert sigil what format does `AudioPlayer.play()`'s resource use? I'm trying to use TTS and ...

If you're using v12 or below voice, it's deprecated and shouldn't be used. If you're using @discordjs/voice, then It accepts an AudioResource and an options Object. Read the docs for more info regarding what props are required for the options. You can pipe any audio stream into the AudioResource and if required, it'll pipe it through ffmpeg to be opus encoded, which is what Discord only accepts.

grizzled jacinth

i know how to know if the bot is in a vc or not, but how do i know if the bot is alone in the vc or not

dusty needleBOT

Documentation suggestion for @grizzled jacinth:
_ VoiceChannel#members
The members in this voice-based channel

junior glen

For voice recording to be perfect, I have to use worker threads for each user but now I have two options on how to implement that

  1. Each worker thread creates his own bot instance and listens to one specific user
  2. Each worker thread just receives the user stream buffer from the main thread

Each worker thread relies on timestamps and the time when a user chunk is received should be as correct as possible

I can't just provide the VoiceReceiver of the connection to the worker thread because it is copied and then it isn't a reference anymore (even though, the copy process fails so nvm that)

What would you suggest?

rose helm

As an aside, worker_threads do not share the same require.cache, so memory usage will spike pretty harshly per worker_thread you spawn. If you don't import many modules in a thread, you can get away with it, but definitely a concern

junior glen

@rose helm thx. So basically: don't use the discord.js library, use the endpoints directly to reduce all the overhead

rose helm

There is no need to use anything Discord REST related in the worker threads. You can just work with djs voice and that's it in a thread. The main thread should be joining the voice channels on behalf of the threads and the child threads emit errors to the main thread.

The basic concept is to just forward the necessary data to the threads and each do their own thing

You will be fighting against memory usage if you spawn a thread per user. You can easily cluster those together since there will not be that much cpu usage as the audio is already opus encoded unless you need to do heavy audio processing. Even then, it's smarter to just cluster it all together

junior glen

ok, thx
will try that out

junior glen

@rose helm and of course it's a lot of memory, if I would import the whole library instead of just the things I need like you did in your example 😅

subtle granite

basically my bot leaves the vc after a while. no clue why

i have ffmpeg installed

junior glen
rose helm
junior glen
rose helm Are you making sure that the types you're passing to the lib satisfy the type co...
this.client.ws.on('VOICE_SERVER_UPDATE', async (info: GatewayVoiceServerUpdateDispatchData) => {
    ...
});
this.client.ws.on('VOICE_STATE_UPDATE', async (info: GatewayVoiceStateUpdateDispatchData) => {
    // filter on clientID
    ...
});

this is 1:1 the object that should be set for onVoiceServerUpdate and onVoiceStateUpdate. I don't use any or unknown at all in my application, so there should never be a type mismatch

in the worker thread:

const _this: IVoiceRecorderData = workerData;
out = new ReplayReadable(_this.maxRecordTimeMs, _this.sampleRate, _this.channelCount, _this.options);
const connection = joinVoiceChannel({
    channelId: _this.channelId,
    guildId: _this.serverId,
    group: _this.clientId,
    adapterCreator: voiceAdapterCreator()
});
if (adapterMethods) {
    console.log('methods available. setting server and state update')
    adapterMethods.onVoiceServerUpdate(_this.serverConnectionInfo);
    adapterMethods.onVoiceStateUpdate(_this.stateInfo);
}

const opusStream = connection.receiver.subscribe(_this.userId, {
    end: {
        behavior: EndBehaviorType.AfterSilence,
        duration: _this.maxRecordTimeMs,
    },
}) as unknown as ReadStream;

opusStream.on('data', () => {
    console.log('data received')
})
rose helm

ok. What state does the connection get into

junior glen

well... signalling

well.... just switched the order of onVoiceServerUpdate and onVoiceStateUpdate and now it is working 😅

junior glen

@rose helm thanks for the solution with the custom adapter!

junior glen

well... F
I can only have one connection that means only one thread can have one... else it's, thread x needs it, thread y needs it...

fierce coral

any idea how i can debug this ?
On my docker machine it doesnt give any sound (locally it works)
I have ensured that the file is correctly loaded, my fstat does give the correct file and file infos
Happens in a docker container (streaming works tho)

this log is from my docker machine, so the file is correct 🤔

junior glen
fierce coral

Maybe, but locally it works with the stream and local file 😄

junior glen

try using createFileStream(yourPath) instead of providing the file via path only

subtle granite
junior glen

*createReadStream

@fierce coral createReadStream from fs

fierce coral

Got it but i cant just pass it to the audioplayer ?

junior glen
fierce coral

now it doesnt play the local file at all 🤔

junior glen

this is weird

fierce coral
subtle granite
fierce coral

I have them as mp3 maybe thats why ?

junior glen

I'm also using mp3 and it works with Docker
I've also set the streamOptions to {inlineVolume: true, inputType: StreamType.OggOpus}

everything else should be the same I guess

fierce coral

Oh wow just defined it with the OggOpus got @discordjs/opus missing Error
Tried to manually install 😄 Maybe some M1 issue ?

junior glen

maybe some missing C++ stuff? Because node-gyp tries to compile the opus stuff which is C++

fierce coral

cant get smarter from this 🤷🏽‍♂️

Okay fixed it through "@discordjs/opus": "^0.6.0",

fierce coral

It stopped playing local files at all after updating the packagss

obtuse rock

How can i make joining the bot an voice channel

dusty needleBOT

_ discordjs.guide results:
• Getting Started: Introduction

icy maple
rose helm

unless the lib literally says only 1 per thread

idk if SharedArrayBuffer would be appropriate for this use case

subtle granite

what would be a way to wait until one file finishes playing

tame thunder

I want to query whether members with a specific role are in any voice channel how can i do this

subtle granite

get members in the voice channel, check if they have the role

tame thunder

I want to print whether members with that role are on the voice channel or not

so if the member with the role is not in the voice channel, I will report it as a message

rugged sky
mellow kiln

Hi, when I run discord on my local windows 10 PC, it works well. But when I run it on a linux vps, there is no sound. And there is no error messages. I'm just playing some mp3 files.
Following are my dependencies:
···
"@discordjs/opus": "^0.5.3",
"@discordjs/voice": "^0.8.0",
"discord.js": "^13.6.0",
"ffmpeg-static": "^4.2.7",
"libsodium-wrappers": "^0.7.9",
···

midnight osprey
adapterCreator: guild.voiceAdapterCreator,

iam making music bot ..what should i add here ??

final jay

is djs voice abandoned?

midnight osprey
rugged sky
midnight osprey

Ok.. Ty

balmy spruce
const subscription = connection.subscribe(audioPlayer);

// subscription could be undefined if the connection is destroyed!
if (subscription) {
    // Unsubscribe after 5 seconds (stop playing audio on the voice connection)
    setTimeout(() => subscription.unsubscribe(), 5_000);
}```

What should I put in "audioPlayer"? The folder where my audio track is?
balmy spruce
    const { audioPlayer, joinVoiceChannel, createAudioPlayer, createAudioResource, createReadStream } = require('@discordjs/voice');
    let server = client.guilds.cache.get("951556244492132382")

    joinVoiceChannel({
        channelId: "952690515327987712",
        guildId: "951556244492132382",
        adapterCreator: server.voiceAdapterCreator,
    });

    const player = createAudioPlayer();

    const resource = createAudioResource('https://www.youtube.com/watch?v=jcBd5GLP1fg', {
        metadata: {
            title: 'A good song!',
        },
    });

    resource.playStream.on('error', error => {
        console.error('Error:', error.message, 'with track', resource.metadata.title);
    });

    player.play(resource);```

Why isn't it playing nothing
south lark

Does anyone have any tips for scaling DJS voice stuff? I keep running into issues where when the bot has been up for too long, the audio becomes distorted and slow :(

red rover

i have an AudioRecieveStream that i would like to send over a websocket using socket.io. i'm wondering if i could convert it into a format that could be sent over the socket. could i use @discordjs/opus to encode it, then decode it when it gets received by the client socket? if so, can i directly pass the AudioRecieveStream into the OpusEncoder#encode function and send that?

rugged sky
rugged sky
balmy spruce
rugged sky Get a library that gets a readable stream of a song from youtube with only the u...
    const { createAudioPlayer, createAudioResource } = require('@discordjs/voice');

    const player = createAudioPlayer();

    const resource = createAudioResource('img/a.mp3', {
        metadata: {
            title: 'A good song!',
        },
    });

    resource.playStream.on('error', error => {
        console.error('Error:', error.message, 'with track', resource.metadata.title);
    });

    player.play(resource);```

Why isn't it playing now?
rugged sky
balmy spruce
balmy spruce
rugged sky
rugged sky
balmy spruce
rugged sky `connection.subscribe(player)`
    const { createAudioPlayer, createAudioResource, getVoiceConnection, audioPlayer } = require('@discordjs/voice');
    const connection = getVoiceConnection('952690515327987712');
    const player = createAudioPlayer();
    connection.subscribe(player);
    const resource = createAudioResource('a.mp3', {
        metadata: {
            title: 'A good song!',
        },
    });
    resource.playStream.on('error', error => {
        console.error('Error:', error.message, 'with track', resource.metadata.title);
    });
    player.play(resource);```
rugged sky
balmy spruce
rugged sky
balmy spruce
balmy spruce
rugged sky

No

red rover
hardy mountain

How could I have a queue loop functionality that adds a song to the queue after it finishes

is there an event to listen to?

round grail

Hello so am ..
When I run my bot on a vps/locally I face a small problem - After playing a YouTube audio I cant seem to play a stream audio [Radio Stream].

I dont get any error on my console but no audio seems to be played

rugged sky
hardy mountain
rugged sky
hardy mountain

well

how will it know the track that just ended, so i can add it back

@rugged sky ?

rugged sky
hardy mountain

how could i do tha

rugged sky

?

Just add it to your client or whatever as a property

hardy mountain

and how do i do that, i only started discord.js today sorry

rugged sky

I would recommend learning Javascript as a language first before diving into this. It's just basic stuff that'll help you solve issues like this.

hardy mountain

ok, but could u tell me for now how to add the track as a property

ive learnt a decent bit of js

rugged sky

client.track = <your track here>

hardy mountain

so if i edit client.track in a command, it will change globally

rugged sky

It'll just add a property called track to your client object.

hardy mountain

so would i do it so like

rugged sky
hardy mountain

when the client player starts playing, it stores client.track as the current song

rugged sky
hardy mountain

oops

Would smth like this work?

rugged sky
hardy mountain

it never triggered the event

rugged sky

Did the audio start playing and the event didn't trigger or did it never start?

hardy mountain

the audio played fine
just that listener never ran, once it started playing

bruh this slow mode is annoying

rugged sky
hardy mountain

well the listener isnt running?

rugged sky
hardy mountain

oh my bad, i added a console.log after that image

rugged sky
hardy mountain

well am i doing the listener wrong

rugged sky
hardy mountain

can i send full index.js

rugged sky

Sure, but I'm in class right now so I'll take a bit to look at it.

hardy mountain

alr ty

rugged sky
hardy mountain

Yeah, you're not using only discord.js; This is a help server for that package. For the player you're using discord-player so it doesn't work the same. You should find a discord-player help server if you have questions about it, but for this specific one I'm pretty sure the events are called different names in that package so you should figure out what even you should listen to.

hardy mountain

yea my bad,

thanks for the help (darn slowmode)

rugged sky

np

subtle granite

@discordjs/opus stuck at 99%

severe shale

Isnt opus deprecated

subtle granite

its deprecated

use @djs/voice

white pike

Utilizing the @discordjs/voice package and the basic code for playing music, the Discord bot I'm using doesn't seem to play anything. I have tried installing and uninstalling many packages, changing how my code works, etc. Nothing seems to be working.
audioPlayer.js (fileName is a String):
https://sourceb.in/VQkXMkPrvp
package.json:
https://sourceb.in/aFTYUYmvC8
interactionCreate.js (just for /play):
https://sourceb.in/Oz0YxToSFU

rose helm
subtle granite use @djs/voice

@discordjs/opus and voice are only related because opus encodes and decodes opus packets while voice is Discord voice related stuff which uses opus packets. What you should be recommended instead of the djs opus package is opusscript. Everyone should be using opusscript

subtle granite

idk never used djs for voice

round grail

Hello so am ..
When I run my bot on a vps/locally I face a small problem - After playing a YouTube audio I cant seem to play a stream audio [Radio Stream].

I dont get any error on my console but no audio seems to be played

fervent estuary
rose helm

Well, it's the next best option considering there's a memory leak whenever encoding opus packets with @discordjs/opus. This can be observed by setting inlineVolume: true in AudioResources in voice and the pipeline going from ffmpeg pcm to opus

I personally use it for production and have encountered no issues thus far.

atomic pagoda

Hi, I was trying to get my bot to join a channel but its not working at all, as I'm getting a TypeError: o is not a function

I tried removing the adapter control, but neither is working for this.

const { joinVoiceChannel } = require('@discordjs/voice');

    const connection = joinVoiceChannel({
        channelId: "123",
        guildId: "12344",
        adapterCreator: client.guilds.fetch("12344").voiceAdapterCreator,
    });
});```
rugged sky
atomic pagoda

Ah I've used those just so I don't show my real channel/guild IDs

rugged sky
round grail

I can seem to see why ...

rose helm
subtle granite
round grail
round grail
rose helm relevant parts
const player = createAudioPlayer();
            try {
                await joinVoiceChannel({
                  channelId: interaction.member.voice.channelId,
                  guildId: interaction.guildId,
                  adapterCreator: interaction.guild.voiceAdapterCreator,
                }).subscribe(player)
            } catch (error) {
}

const resource = createAudioResource(stationURL);
                    player.play(resource);

player.on(VoiceConnectionStatus.Disconnected, async (oldState, newState) => {
                     try {
                        await Promise.race([
                          entersState(player, VoiceConnectionStatus.Signalling, 5_000),
                          entersState(player, VoiceConnectionStatus.Connecting, 5_000),
                        ]);
                      } catch (error) {
                        
                        }.catch(() => {
                        
                        })
                        return player.destroy();
                      }
                    });
rose helm

Don't use joinVoiceChannel if it already exists.

You're using VoiceConnectionStatus events instead of player status events.

round grail

If its youtube its ```js
let play_youtube = await ytdl(song.url, { highWaterMark: 1 << 25, filter: 'audioonly' });

rose helm

you can getVoiceChannel

round grail
rose helm

ye

round grail

Will that solve the issue?

rose helm

idk. If you also fix the fact you're using the wrong events, then maybe

round grail
rose helm

read the docs for player events

or just change passing the player for the connection instead

oblique lion

        const msg = message.content.split(" ").slice(1).join(" ")
        const channel = message.member.voice.channel;
        if(!channel) return message.channel.send("You need to be in a voice channel to use this command!");

        say.export(msg, null,1, `./temp/${message.id}.mp3`, (err) => {
            if (err) {
              return console.error(err)
            }
           
            console.log("Saved!")
          })
        
        
          const player = createAudioPlayer();
         const connection = joinVoiceChannel({
              channelId: channel.id,
              guildId: message.guild.id,
              adapterCreator: message.guild.voiceAdapterCreator,
          })
  
        connection.subscribe(player);
      
          const resource =createAudioResource(`./temp/${message.id}.mp3`);
             
          
          
  
          player.play(resource);
          
          player.on('error', error => {
              console.error(error);
          });
          
          player.on(AudioPlayerStatus.Idle, () => {
              
              connection.destroy();
          });

the bot isn't playing the audio

the file is created

feral coral

am I able to store player and call it in a different function like pause cause rn I have to make it a global to use it

I want player.pause(); to work like vc[guild].player.pause();

livid furnace

Hey, how come the voicestate has all these null fields after joining a voice channel?

rugged sky
feral coral

More specifically while its attempting

livid furnace

Is the joining async? I'm not sure how to latch onto it and run subsequent code

feral coral
rugged sky
rugged sky
rose helm
dim shadow

can you tell me how can i see the voice connections of the bot? bot.voice.connections.size isn't working anymore, please help its needed

rugged sky
dim shadow

oh

jaunty peak

https://www.codepile.net/pile/VmZvG0mG
Any idea what's that?
happens few seconds after starting a voice activity:

                channelId: vc.id,
                guildId: guild.id,
                adapterCreator: guild.voiceAdapterCreator,
            })

            const stream = ytdl(vid, { filter: 'audioonly' })

            const player = createAudioPlayer()
            const resource = createAudioResource(stream, { inlineVolume: true })
            resource.volume.setVolume(vol / 5);

            player.play(resource)
            connection.subscribe(player)```
runic thistle

is there any method in @discordjs/vocie package that would detect the StreamType for us?

or does the StreamType even required?

i'm working on a package, i just wanna know what kinda types should i get?
right now i'm accepting Readable, IncomingMessage, Buffer, Opus.Encoder, FFmpeg

patent breach

How would I go about doing something like this

So I am creating a public radio bot. And want it so the user can invite the bot and the server administrator can set a channel that will make it so the bot only joins that channel. And another part of the bot will be able to grab the listeners that each server currently have and plug it in to my api

runic thistle
stoic orbit
patent breach How would I go about doing something like this So I am creating a public radio ...

i don't really get your question but:
you could use a database to store data heres how it will go:

KEY: GUILDID
VALUE: CHANNELID

there are some simple key, value npms out there that allow you to use databases

best one (this allows you to use cloud databases): keyv

an built in one (this is called fs allows you to write to files you could make your own json database): fs

semi best (this one is called simple-json-db this is really simple for json databases and requires zero effort): simple-json-db

honestly this one is pretty good still (its called quick.db and it works like simple-json-db but a different file format and some more methods for storing data): quick.db

wooden latch

how do I make bot as a speaker in a StageChannel?

neon ibex

stagechannel.guild.me.voice.setSuppressed(false);

subtle granite

Do you recommend me to use packages or discordjs voice?

subtle granite

is it possible to set the volume?

yep

south lark
subtle granite
rugged sky
rugged sky
subtle granite

ok thanks guys

subtle granite

ohh nvm i accidentally did connection.on

subtle granite
pine mulch

is it possible to stream video in vc?

pine mulch
subtle granite

nope

pseudo forum
subtle granite

ok

round grail

i am unable to install this @discordjs/opus

marble zealot

I can't get newly voice channel of member using message.member.voice.channel, it returned null

does anyone have this?

nvm, I'm lack of intents

subtle granite

install these first, on an administrative cmd

round grail

Will it work

Cause is run and then nothing

candid elm

is it possible to somehow get the sound that's coming from a user in a voice channel?

subtle granite

How to make bot leave VC?

rugged sky
rugged sky
jaunty peak

https://www.codepile.net/pile/VmZvG0mG
Any idea what's that?
happens few seconds after starting a voice activity:

                channelId: vc.id,
                guildId: guild.id,
                adapterCreator: guild.voiceAdapterCreator,
            })

            const stream = ytdl(vid, { filter: 'audioonly' })

            const player = createAudioPlayer()
            const resource = createAudioResource(stream, { inlineVolume: true })
            resource.volume.setVolume(vol / 5);

            player.play(resource)
            connection.subscribe(player)```
rugged sky
jaunty peak

oke ty 🙂

candid elm

hey guys my bot joins my vc but doesn't play the audio, and there are no errors can someone help me? this is my code https://sourceb.in/GwqqYzvahX

rugged sky
subtle granite

Hi, my music bot doesn't work, when I install @discordjs/opus it gives me these errors, now I send them to you

candid elm

i tried ./path/to/file/ and D:/DiscordBots/bot/path/to/file but neither worked

rugged sky
candid elm
rugged sky
south harbor

how can i know which users have permission to join in voice channel
i want there names or id as output

did you got your answer ?

candid elm
rugged sky You need that.

i added them and now the bot joins the channel, it appears that its talking and leaves the channel, but the audio isn't playing

rugged sky
candid elm

it works now

candid elm

is it possible to capture the audio from a vc the bot is in? like when someone talks, start recording and when they stop talking it saves in a mp3 file

or is that against discord tos or something

torpid narwhal
icy maple

The voice package can do voice receive

torpid narwhal
candid elm
torpid narwhal
icy maple
candid elm

how

torpid narwhal
icy maple Yes

hmmm okay ty! ill explore more into that then i rly didnt know that tysm iceCreamCat

candid elm

i saw something called VoiceRetriever

and something called AudioReceiveStream, are those it?

torpid narwhal

yep its all there tysm

icy maple
candid elm

i want to record what a person talks then change the pitch and say it back

torpid narwhal

i think u can add filters to ffmpeg if im not wrong

so with that u can just alter/edit the voice of that person? rly gotta dig into it

feral coral

How do I handle a memory leak?

dusty needleBOT
red rover

how can i wait for an AudioRecieveStream to be closed?

i'm trying to read from a receiver subscription, but the read function is returning null.

i think it might have to do with the write stream not being closed before it tries to read

graceful hedge

Hi 😄 How can i create voice channel with users limit in specific category?

south harbor
nocturne drum

hey so ive been trying the past couple of hours but nothing seems to be working. How can I get my discord bot to join a voice channel when I start the bot?

tried the guide and all

nun works

anyone?

nocturne drum
woeful stone

how do you get users speaking on vc

connection.receiver.speaking.users returns Map(0) {} when speaking or not speaking

am i missing something?

solar scaffold
solar scaffold
woeful stone

i have all of them emabled on code and discord dev portal

solar scaffold
woeful stone

wdym

woeful stone
solar scaffold

it should look something like this so you can get voice states

woeful stone
frank kelp

where you instantiated your client

woeful stone

i didn't get it (sorry for bad english)

severe shale

Yes but what does it have to do with @discordjs/voice library

tepid tulip

idk, as it is pretty much in vocal, i didn't really know where to put it,

also i found how to, so i'll delete

solar scaffold

what the hell does this mean

i dont understand why this couldn't just stay in the main library like it always was 🧍🏼‍♂️

south lark
rugged sky
rugged sky
tiny sigil

I'll be honest i know we're meant to give information about this, but i really don't know what's happening, yesterday it was working, but sometiems in a vc with multiple people it does this( and it randomly started working again, same vc same people)

left pilot

anyone had any issues with audio quality going bad after a few seconds of playing via an audio stream via url? Hosting via AWS. If you did, if you could let me know any solutions u had to this it will help me a lot.

subtle granite
rugged sky
subtle granite
rugged sky Are you trying to call `.playStream()` on your connection?
client.on('messageCreate', message => {
  if(message.content === 'tst') {
  const name = db.get(`j_${message.guild.id}`)
    
 voiceDiscord.joinVoiceChannel({
                channelId: name,
                guildId: message.guild.id,
                adapterCreator: message.guild.voiceAdapterCreator,
            }) 
    const streamOptions = { seek: 0, volume: 1 };
    const { getVoiceConnection } = require('@discordjs/voice');
    const connection = getVoiceConnection(message.guild.id);
const stream = ytdl('https://www.youtube.com/watch?v=_8Ql9I0qJoM', { filter : 'audioonly' });
    const dispatcher = connection.playStream(stream, streamOptions); 
            
  }
})
rugged sky
violet thorn

when i move the bot from one channel to another it shows the same channel id for both the voice states
this issue has been bugging me from a year

and also when i move the bot to another vc and check the cache it shows that the bot is still in the initial channel

rugged sky
violet thorn
rugged sky

Show full code

violet thorn

this is all that's needed for voice state updates

dreamy drum

i have a question

when something playing on player for example i ytdl() a song and my player is stucking for a second then resuming play

i don't know how i explain this

flat river

Can anyone tell me did different lavalink help music bot to give different kind of audio quality ? Or all the lavalink works same.

flat river
dreamy drum
flat river
dreamy drum

to play it with audioplayer

violet thorn
subtle granite

is it possible to record a voice channel?

violet thorn
flat river Link

your dms are closed and you can't post invite links here but the vanity url is "jda"

violet thorn
subtle granite

How?

rugged sky

How do you mean?

subtle granite
violet thorn
solid mesa

how do i check if somebody is speaking? cause i want to record then send to speech to text for voice commands

with the recorder example im getting

prism_media_1.default.opus.OpusHead is not a constructor

spice flint

My join function:VoiceChannel.join().then(connection => { connection.play(getRadioURL(radioID), {volume: 0.5,});}) How can I now in another function get connection from client to change stream/song

fervent estuary

v12 voice is not supported

blissful quiver

Hello there, I'm trying to use v13 Voice to join a voice channel and play an audio file, I've set the GUILD_VOICE_STATES, looked all over google, bot has the Connect and Voice permissions... connection gets stuck in signalling

I'm using node LTS 16.14.2 with these deps

"dependencies": {
"@discordjs/voice": "^0.8.0",
"bufferutil": "^4.0.6",
"discord.js": "^13.6.0",
"ffmpeg-static": "^5.0.0",
"libsodium-wrappers": "^0.7.10",
"opusscript": "^0.0.8",
"tweetnacl": "^1.0.3",
"utf-8-validate": "^5.0.9",
"zlib-sync": "^0.1.7"
}

solid mesa

also the guide page for voice needs to be expanded since there is not really much there

blissful quiver
subtle granite

hey, yesterday i made a radio bot. However this one when he joins the voice he broadcasts music but it stops after 5 sec can someone help me the bot has no error ect

https://pastebin.com/J5ucjuM5

solid mesa

did you use the guide cause in the guide there is a part that stops it after 5 seconds

subtle granite
solid mesa

i dont know how to check if somebody is speaking sorry

normal creek

it's pretty much identical but i changed the connection thing to work for the user's channel

sick gazelle

help me pls im somehow getting this same error whenever bot joins and plays music in my vc ```js
Connected to mongodb
AbortError: The operation was aborted
at abortListener (node:events:838:14)
at EventTarget.<anonymous> (node:events:874:47)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
at EventTarget.dispatchEvent (node:internal/event_target:504:26)
at abortSignal (node:internal/abort_controller:97:10)
at AbortController.abort (node:internal/abort_controller:122:5)
at wt (C:\Users\chibu\OneDrive\Desktop\moosic beta\node_modules@discordjs\voice\dist\index.js:9:316)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}
[antiCrash] :: Multiple Resolves
reject Promise {
[
{
status: 'connecting',
adapter: [Object],
subscription: [O],
networking: [z]
},
{
status: 'ready',
adapter: [Object],
subscription: [O],
networking: [z]
}
]
} AbortError: The operation was aborted
at abortListener (node:events:838:14)
at EventTarget.<anonymous> (node:events:874:47)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
at EventTarget.dispatchEvent (node:internal/event_target:504:26)
at abortSignal (node:internal/abort_controller:97:10)
at AbortController.abort (node:internal/abort_controller:122:5)
at wt (C:\Users\chibu\OneDrive\Desktop\moosic beta\node_modules@discordjs\voice\dist\index.js:9:316)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ABORT_ERR'
}

river mist

i need guidance

i followed the guide for playing yt music

but it only works with this !play URL I want it to search songs and then play so smth like !play <song name> or !search <song name>

severe shale

I dont think its related to discord.js

rugged sky
river mist
rose helm
sick gazelle
rose helm

issue on their end then

violet thorn
violet thorn
subtle granite

Anyone know anything

icy maple
icy maple

Cloudflare

subtle granite

It might be because playing audio in many voice channels?

Because it’s happening a lot

icy maple

The discord api status page seems to state that voice is working fine

devout quarry

My bot joins the channel and spams The audio player has started playing!
but it doesnt acctualy play anything...

const {  createAudioPlayer, createAudioResource, StreamType, joinVoiceChannel, AudioPlayerStatus } = require('@discordjs/voice');
const { createReadStream } = require('node:fs');
var fs = require('fs');


module.exports = {
    name: 'voiceStateUpdate',
    async execute(oldMember, newMember) {


        const player = createAudioPlayer()

        const audioResource = createAudioResource('./src/audio.mp3')        

        joinVoiceChannel({
            channelId: newMember.channel.id,
            guildId: newMember.guild.id,
            adapterCreator: newMember.guild.voiceAdapterCreator
        }).subscribe(player);
        
        player.play(audioResource)

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

    },
}

any quick fix?

wraith carbon

how do i make the bot leave after 30 secs of joining the voice channel

devout quarry
subtle granite

This issue happened but i don’t remember how did i fixed it😅

Idk how’s this helping, but search for it, it’s easy

devout quarry

i did

devout quarry

@subtle granite could u check your code?

gritty minnow
devout quarry

Yea the guide doesnt help

gritty minnow

yeh, ive followed a bunch of different tutorials at this point 😢

subtle granite

I can’t now

devout quarry

ah

devout quarry
gritty minnow

so you might need todo that? I'm learning still so i have no idea

createAudioResource(createReadStream(join(__dirname, 'file.ogg') they've also got anther param here, not sure why

oh and they're using createReadStream()

devout quarry
devout quarry

thanks :)

@subtle granite Now it works, but the audio is stopping randomly and replaying and it also starts after 30sec of being in the voice channel

gritty minnow

what does your code look like now? @devout quarry

devout quarry
gritty minnow what does your code look like now? <@!455384952758992896>
const {  createAudioPlayer, createAudioResource, StreamType, joinVoiceChannel, AudioPlayerStatus } = require('@discordjs/voice');
const { createReadStream } = require('node:fs');
const { join } = require('node:path');
var fs = require('fs');


module.exports = {
    name: 'voiceStateUpdate',
    async execute(oldMember, newMember) {


        const player = createAudioPlayer()

        const audioResource = createAudioResource(createReadStream(join("./src/", 'audio.ogg'), {
            inputType: StreamType.OggOpus,
        }));

        joinVoiceChannel({
            channelId: newMember.channel.id,
            guildId: newMember.guild.id,
            adapterCreator: newMember.guild.voiceAdapterCreator
        }).subscribe(player);
        
        player.play(audioResource)
        

    },
}
gritty minnow

cheers

devout quarry

after some seconds of lagging, it just stops and replays

gritty minnow

made it an .ogg file then eh

devout quarry

audio is something like 3min long but it cuts at 15sec

gritty minnow

i couldnt understand this bit join("./src/" but that's shows me now, thanks

gritty minnow

oh you have a audio.ogg file

so i need to make my mp3 file into that?

devout quarry

join(path, filename)

gritty minnow

what does .join() do exactly?

devout quarry

because .../audio.ogg wont work i think

gritty minnow

yeh makes sense, how did you convert audio file into a .ogg file?

devout quarry

just google convertor

gritty minnow

ah cool

devout quarry

wait that site is Dutch i think, lol

gritty minnow

ah was trying to figure out which language that was haha

devout quarry
gritty minnow

cant get mine to work, get this DiscordAPIError: Invalid Form Body on player.play(audioResource);

which means audioResource is wrong for player.play() somehow? I dunno

vale eagle

record multiple users at once how

icy maple

Has nothing to due w/ voice

gritty minnow
icy maple

That's not an embed

gritty minnow

oh which bit is?

icy maple

I'm talking abt a Discord Message Embed

Has nothing to due w/ voice

burnt gyro

how would i make my bot join vc auto and play the radio stream

gritty minnow
icy maple

But smth is sending an embed

gritty minnow

thanks for the help btw

dusty needleBOT
gritty minnow

oooo okay so im sending that somehow

icy maple

Yea. Voice package doesn't (and can't) do that on ur behalf

gritty minnow

cheers, got rid of that error now! Thank you ❤️ ❤️ ❤️

lofty shuttle

Hi
I'm having trouble creating a @discordjs/voice player
My problem is the code works fine when run locally, or in Docker container on my machine, but won't run in a Digital Ocean app

This is my code ```typescript
import {
AudioPlayerStatus,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
NoSubscriberBehavior,
VoiceConnection,
} from "@discordjs/voice";
import Config from "config";
import path from "path";
import { Global } from "../Global";

export default class VoiceChannelController {
static player = createAudioPlayer({
behaviors: { noSubscriber: NoSubscriberBehavior.Pause },
});

static get resource() {
const p = path.join(__dirname, "..", "sounds", "test-sound.webm");
return createAudioResource(p);
}

static connection: VoiceConnection;

static async init() {
const bb = Global.bot("VOICE_BOT");
const channel = await bb.guild.channels.fetch(Config.channelId("VOICE"));

if (channel === null) {
  throw new Error("Cannot find voice channel.");
}

this.connection = joinVoiceChannel({
  channelId: channel.id,
  guildId: channel.guild.id,
  debug: true,
  adapterCreator: channel.guild.voiceAdapterCreator,
  selfDeaf: false,
});

this.connection.subscribe(this.player);

this.connection.on("debug", (...args) => {
  console.log(...args);
});

this.connection.on("error", (...args) => {
  console.log(...args);
});

this.player.play(this.resource);

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

}
}

As I mentioned it works as expected running on my machine, or in a Docker container on my machine, but fails silently in a Digital Ocean app container. It feels like this will be an utter pain to debug - hoping somebody here has some insight

lofty shuttle
languid quail

Use joinVoiceChannel from this package

message.member.voice.channelId

feral coral

how would I create an event listener that listens to every guilds player without making a listener for each guild or would I just make listener for each guild anyway?

cause rn its activated as a function

icy maple
feral coral
feral coral
subtle granite
const player = createAudioPlayer({
    behaviors: {
        noSubscriber: NoSubscriberBehavior.Pause,
    },
}); ```

This mean if no one in the VC, it will pause, right?

icy maple
subtle granite

And how it can play if there’s no connection 🤨

subtle granite
gritty minnow

Hi again, can't get the audio to play in the voice channel. I'm not getting any errors. Can anyone see any issues with this code?

sick gazelle
frank kelp

show the rest of the error

whats the os on your vps

sick gazelle
frank kelp
sick gazelle
frank kelp

run that on your vps

sick gazelle

oh ok

installed

frank kelp

install opus again

icy maple
icy maple
devout quarry

@subtle granite still have the same problem as yesterday,
My audio laggs a bit then stops after ~15sec and restarts

wraith carbon

i have connection.destroy() how i do make it disconnect after 30 seconds tho?

devout quarry

Thats some basic js

noble wolf

Is there a way to make the bot go into voice chat when the bot is in ready status?

tired leaf

Did I need to make a client for djs voice?

rose helm

There needs to be an active gateway connection, but it can be totally separate from your bot's code

patent forum

Is createAudioResource deprecated? I cannot find it in the documentation

icy maple
rose helm

Trust the .d.ts files the most

night parcel

Hi guys, i'm starting to implement the discord/voice library, before this change i was using join to use .then() to execute code whenever the bot connected, is there a way to do the same?

//OLD CODE
voiceC.join().then(async connection =>{ //connect the bot
            msg.channel.send(this.bh.embed.createSongEmbed(this.bh, msg, song.title, song.member.user.username, song.member.user.avatarURL, song.link,                 song.thumbnail))
            connection.play(link)//(ytdl(song.link,{filter: "audioonly"})
            .on('start', ()=>{
                //Canzone iniziata, metto timeout a null
                if(this.timeout != null) clearTimeout(this.timeout);
                this.timeout = null;
            })
            .on('finish', reason =>{
                console.log("[DEBUG]" + `[${msg.guild.name}]` + " canzone finita: " + song.title + " Reason: " + reason)
                //check if there are more songs to be played
                this.playNext(msg,guildQ.random)
            })
        }).catch(console.error)```
```js
//NEW CODE
const { joinVoiceChannel } = require('@discordjs/voice');
joinVoiceChannel({
    channelId: msg.member.voice.channel.id,
    guildId: msg.guild.id,
    adapterCreator: msg.guild.voiceAdapterCreator
})```
rugged sky
night parcel

That's not code executed at the start of the bot, it's when someone calls it to play something from youtube

But i think i've found a guide on the website

vernal plover

With JoinVoiceChannel, the bot exits the channel after a while... Is it possible to somehow solve this?

jolly zenith
    const { createAudioPlayer, NoSubscriberBehavior, joinVoiceChannel, createAudioResource } = require('@discordjs/voice');
    const player = createAudioPlayer({behaviors: { noSubscriber: NoSubscriberBehavior.Stop, deaf: NoSubscriberBehavior.Deafen }});
    const resource = createAudioResource(`${process.cwd()}/assets/audio.mp3`);
    const connection = joinVoiceChannel({
        channelId: vc.id,
        guildId: client.config.guildId,
        adapterCreator: vc.guild.voiceAdapterCreator,
    });

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

any reason why this is joining the vc but not playing audio? (the mp3 file exists)

tough breach

what was it?
I would guess the path was wrong?

tough breach

oh, lol, I see

ah, I see, you should have waited for the connection to be ready before starting to play the audio resource

or used NoSubscriberBehavior.Pause for it to resume as soon as the connection is available
til

unreal ledge
const connecting = joinVoiceChannel({
                channelId: message.member.voice.channel.id,
                guildId: message.member.guild.id,
                adapterCreator: channel.guild.voiceAdapterCreator,
                selfDeaf: true,
                selfMute: true,
            })
            if (connecting) {
                message.reply(`${client.emotes.success} | Move Me To Another Vc!`)

                client.on("voiceStateUpdate", async (oldmem, newmem) => {
                    if (newmem.member.voice.channel && newmem.member.voice.channel.id !== channel.id) {
                        let newchannel = message.guild.channels.cache.get(newmem.member.voice.channel.id);
                        if (client.user.id === newmem.member.user.id) {
                            channel.members.forEach(e => {
                                e.voice.setChannel(newchannel);
                            })
                            const connection = getVoiceConnection(newchannel.guild.id);
                            connection.destroy();

                        }
                    }
                })
            }

bot joins and moves everyone to second vc the first time
but if i'm executing the command second time it's not connecting to voice channel

west basalt

nothing happens, it just says application did not respond

thorn bough

Hey does someone here know any way to check if the client was kicked out from vc.

slender sparrow

discord didnt send that event as i know, only voiceStateUpdate

pseudo forum
slender sparrow

is that ytdl?

pseudo forum

I get this error after 10~15 minutes

slender sparrow

you use ytdl-core or play-dl?

orchid sun
pseudo forum
slender sparrow

try to use play-dl

pseudo forum
slender sparrow

so many user getting aborted issue when using ytdl-core

pseudo forum

I'll try to change when I go home, thanks

wraith carbon

is it possible to make a bot say things based off what the string is in the command?

lofty shuttle
feral coral

how do I get the timestamp for how far player is through a song?

bold furnace

hi, is djs capable of recording the audio from the channel?

unkempt mirage

hello, this is my code
https://sourceb.in/RLkhbQ3vWZ, im trying to do a music bot but gives this warn, who can help me fix it? idk how
(node:11940) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 addSong listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit (Use `node --trace-warnings ...` to show where the warning was created) (node:11940) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 playSong listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit (node:11940) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 searchNoResult listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit

im trying to make a simple and little music bot, idk how to fix this warn/error

nvm i fixed

subtle granite

whyy

icy maple

You would need to check if the actual .state.status is destroyed

subtle granite
icy maple

I think so, I just use the enums instead of magic strings

subtle granite

i don't like this magic, but idk about enums, so ty

icy maple

d.js v14 will force you to use enums (at least for the main lib)

subtle granite

then i don't think i'll use it soon 🙁

hard trellis

hi, i'm seeing stageInstance = null, but stage is already open when i try to createStageInstance

astral lark

I followed the discordjs voice recorder demo, and have it recording chat perfectly, but weirdly, when someone else speaks, they are not picked up at all, is there any way to subscribe to everyone in the channel speaking?

pure ledge
const { VoiceConnectionStatus, entersState } = require('@discordjs/voice');

is this correct?

subtle granite
pure ledge
languid quail
pure ledge

what is the package for then?

languid quail
subtle granite
pure ledge
languid quail
pure ledge

is like a voice bot with prerecord mp3 files?

torpid narwhal
west basalt

I don’t think I defined it

tough breach
tough breach

because thats how discord sends audio
if you want to record all the users in a channel you would have to subscribe to each user individually and merge them together (probably with ffmpeg or something similiar)

astral lark

Sure, except, discord only listens when you're speaking so if I was to take 4 different people talking and each person spoke at different times, all the tracks would be off, so merging them is almost impossible.

It's like I need to create some kind of empty audio stream and then merge the user streams into that single audio stream, as they speak.

tough breach

correct, ffmpeg can fill it with silence, and then you would have to merge each stream into it,
I managed to do the "have silence if there they arent speaking", not sure how to stream multiple streams into it tho

astral lark

Okay, how do you do the "have silence if no one is speaking"? that may help me a lot, I am sure I can f*** around with ffmpeg to merge multiple streams part, it's the making empty noise part that is kinda confusing.

I see there is a behaviour type of manual, but typescript throws a tantrum when trying to set it, saying you can't set behaviour to that.

tough breach

are you using discord.js or discord.js/voice?

astral lark
tough breach

I dont see any type parameter

its now "end" and that just defines when it should stop listening

astral lark

I have this code tat when the connection reaches ready it runs the below.

Ignore all the logging btw, just testing output.

Then that is the contents of createListeningStream

tough breach

yes there is EndBehaviourType.Manual but it just means that you have to stop the receiver whenever you feel like it

astral lark

Okay interesting, so if I remove the end: {} part, I assume just don't define it, then it would keep creating audio>

tough breach

nono

astral lark

Oh

That is what happens if I set it to manual.

tough breach

probably have to remove duration

astral lark

You're a saviour, so okay, to confirm, this will keep recording even though there is no voice activity? which would create a continuous stream?

tough breach

yes, but pretty sure it wont be filled with silence

astral lark

Okay, so maybe if I was to drop OggStream and use something like ffmpeg, I could accept the voice stream, fill any empty space with silence, and then merge them together (probably after the voice call)?

tough breach

you have the receiver.subscribe method which returns a stream,
at all times the stream will only write data when the users speaks, afaik this will always be like that

with AfterSilence => destroys the stream as soon as the user stops speaking
with manual => the stream runs forever until you stop it

you still have to manually fill it with silence if the person isnt speaking

if its ok to do it after the voice call it would be the easiest way to do it like that yes

astral lark

Yeah I think so, we just want to use it for recording live discussions/meetings in voice chats, we won't need it directly after, and at least then I could call the ffmpeg from a thread rather than the main bot process I think.

So next, but probably silly question, I assume I shouldn't use OggLogicalBitstream but rather pipe the AudioReceiveStream into something better? Or do I still need to use this part:

const oggStream = new opus.OggLogicalBitstream({
    opusHead: new opus.OpusHead({
        channelCount: 2,
        sampleRate: 48000,
    }),
    pageSizeControl: {
        maxPackets: 10,
    },
    crc: false,
});```
tough breach

I'm not sure I didnt do much with the new voice system, before that I just piped the raw pcm into ffmpeg

// spawn is from child_process
const child = spawn('ffmpeg', [
    '-f',
    's16le',
    '-ar',
    '48000',
    '-ac',
    '2',
    '-i',
    'pipe:0',
    // add rest of ffmpeg parameters here
    // preferrably test it with a file as output
]);
const pipe = pipeline(stream, child.stdin, err => {
    if (err) throw err;
});

if you need any more help, I will be back in like 40 minutes and then I can play around with it myself and see if I can get it working

astral lark
tough breach

@astral lark did you get it to work

astral lark
chrome star

I'm trying to get the recorder example working but have run into a ton of issues 😦

I've gotten the bot to start and join voice, but it throws this error on line 19 of createListeningStream.ts when it tries to begin recording:

 const oggStream = new prism_media_1.default.opus.OggLogicalBitstream({
                                                ^

TypeError: Cannot read property 'opus' of undefined

I'm on node v16.8.0. Anyone know how to fix it? I also think it's odd that the actual line in the file is new prism.opus rather than what the error says, which is new prism_media_1.default.opus.

chrome star

Huh... importing the function directly worked but I'm not sure why:

import { OggLogicalBitstream, OpusHead } from 'prism-media/dist/opus';

const oggStream = new OggLogicalBitstream({
    opusHead: new OpusHead({
      ...
astral lark
chrome star

My package.json has "prism-media": "^2.0.0-alpha.0" and I reinstalled it a few times just be sure. I also updated other libraries in there to more recent versions in case any of those were the issue

unkempt mirage

who can help me? when i say ~play the bot joins and leaves, my code is:

im in v13

rugged sky
vale eagle

how do i get a list of all voice channels my bot is in

pure ledge

how to get the parent category of a channel in voice state change event?

severe shale

<VoiceState>.channel.parent

pure ledge
dusty needleBOT

Explaining <Class> and Class#method notation: learn more

pure ledge
slender sparrow

you didnt see the channel properties yet

pure ledge
dusty needleBOT

Documentation suggestion for @pure ledge:
_ VoiceChannel#parent
The category parent of this channel

slender sparrow

read the docs carefully

pure ledge
severe shale
prime oyster
const client = require("../index").client
const { Collection, UserFlags } = require('discord.js')
const voiceCollection = new Collection();
const guildmodel = require('../models/guild.js');
const jointocreatemodel = require('../models/jointocreate.js');

client.on("voiceStateUpdate", async (oldState, newState) => {
    const member = newState.member

    let guilddata = await guildmodel.findOne( { guildId: newState.guild.id} )
    if(guilddata.jointocreate === "") return

    let test = await jointocreatemodel.findOne( { guildId: newState.guild.id, userId: member.id } )


    if(!oldState.channelId && newState.channel.id === guilddata.jointocreate ){
        let jointocreatedata = await jointocreatemodel.findOne( { guildId: newState.guild.id, userId: member.id } )

        if(jointocreatedata) {
            let jointocreatedata = await jointocreatemodel.findOne( { guildId: newState.guild.id, userId: member.id } )
            let channel = await client.channels.cache.get(jointocreatedata.channelid)

            return await member.voice.setChannel(channel)
        }
        
        channel = await newState.guild.channels.create(member.user.username+ "'s Room", {
            type: 'GUILD_VOICE',
            parent: newState.channel.parent,
        });
        member.voice.setChannel(channel);
        voiceCollection.set(member.user.tag, channel.id);

        jointocreatedata = await jointocreatemodel.create( { guildId: newState.guild.id, userId: member.id, channelid: channel.id } )


    }else if(member.voice.channelId === guilddata.jointocreate && test ){
        let targetchannel = await client.channels.cache.get(test.channelid)
        return await member.voice.setChannel(targetchannel)
    }else if(!newState.channel) {
        let jointocreatedata = await jointocreatemodel.findOne( { guildId: newState.guild.id, userId: member.id} )
        if(!jointocreatedata) return
        if(oldState.id != jointocreatedata.channelid) {
            await jointocreatemodel.deleteOne( {guildId: newState.guild.id, userId: member.id } )
            let targetchannel = await client.channels.cache.get(jointocreatedata.channelid)
            await targetchannel.delete ()
        }
    }
    
      
})

This is my JoinToCreate event code. It works but how could i make it so if the owner of a jtc channel switches to another call it deletes the channel that was created by him?

boreal lark

Is there a way to make a bot join the channel and then start playing a music stream?

I want to make a bot that starts playing the music when someone joins the voice channel. I have made it filter on members and check on the size of members in the channel, but now I only need it to play and stop.

It needs to be in the VoiceStateUpdate event.

subtle granite
                dispatcher.on('finish', () => {
                connection.destroy();
            })```

TypeError: connection.play is not a function

full code: https://srcb.in/MqyDjUbNVy
torpid narwhal

ur connection is only to the voice channel

create a player and subscribe it to the connection and then play smth

subtle granite
torpid narwhal
subtle granite
torpid narwhal
subtle granite

ok tysm

torpid narwhal

npp

bright oracle

does anyone know how to check if bot is in a voice channel in discord.js v13

bright oracle

AkiArasaki — Today at 10:55 PM
how can I setVolume before playing music in v13?

rapid rain
bright oracle
async leave(msg) {
    //如果机器人在语音频道
    if (this.connection[msg.guild.id] && this.connection[msg.guild.id].state.status != "Destroyed") {
      //如果机器人播放过歌曲
      /*if (this.queue.hasOwnProperty(msg.guild.id)) {
        //清空列表
        delete this.queue[msg.guild.id];
        //将isPlaying设置为false
        this.isPlaying[msg.guild.id] = false;
      }*/
      //离开频道
      this.connection[msg.guild.id].destroy();
      msg.channel.send({embeds: [
        new MessageEmbed()
        .setColor('#E74C3C')
        .setTitle('ヾ( ̄▽ ̄)Bye~Bye~')
      ]});
      return;
    } else {
      msg.channel.send({embeds: [
        new MessageEmbed()
        .setColor('#E74C3C')
        .setTitle('I\'m not in any channel')
        .setDescription('.help for commands')
      ]});
    }
  }
bright oracle

it does not go into the else section

error looks like this

rapid rain

don't make it leave again after it left

errant iron

hello is this the right way to disconnect a user in djs v13 async function disconnect(userID){
let user = await client.users.fetch(userID)
console.log("Disconnecting " + user)
user.voice.disconnect();
} it doesnt seem to be working

civic yarrow

player.on() not working, can someone help me?
when i try to run this

connection.subscribe(player);
player.play(resource);
player.on(AudioPlayerStatus.Playing, () => {
  interaction.followUp('playing now!');
});

the player.on() function just doesnt work

rugged sky
frozen palm

I was trying to make a radio bot and following the example on @discordjs/voice but always get an error

AbortError: The operation was aborted

can someone explain what happen please?

slender sparrow

did you use ytdl-core?

frozen palm

no

foggy idol
let voiceConnection;
        const audioResource=createAudioResource(stream, {inputType: StreamType.Arbitrary, inlineVolume:true});
        if (!voiceConnection || voiceConnection?.state.status===VoiceConnectionStatus.Disconnected) {
            voiceConnection = joinVoiceChannel({
                channelId: message.member.voice.channelId,
                guildId: message.guildId,
                adapterCreator: message.guild.voiceAdapterCreator,
                selfDeaf: false
            });
            voiceConnection = await entersState(voiceConnection, VoiceConnectionStatus.Connecting, 5_000);
            message.channel.send('Processing text-to-speech');
        }
        message.channel.send('Waiting');
        console.log('AAA');
        const audioPlayer=new AudioPlayer();
        audioPlayer.play(audioResource);
        voiceConnection.subscribe(audioPlayer);

Hi! When i join the voiceChannel with selfDeaf as false i can hear the resource playing, wherease with selfDeaf property not given, i cannot hear the bot play. How can I make the bot play the resource while staying at deafen?

livid furnace

Hey, I keep getting a connResetException after 5-10 mins of playing music through a YT video in my bot, there is no error and it just says connection aborted. Any idea what situations cause this to happen?

torpid narwhal

rq question <AudioResouce>.playbackDuration is returning 0, any idea why? ping me if u can help cookieCat

stark thunder

Error: Cannot play audio as no valid encryption package is installed.
what is the required package ?

when i try to install one of them they don't get installed ! , sodium, libsodium-wrappers, or tweetnacl

subtle granite

Hello
I'm getitng all meta datas and song datas etc.
It all works
but it's not playing any sound in the channel
no matter what i try.

idk why

rugged sky
rugged sky
stark thunder
rugged sky

Great

subtle granite
stark thunder
subtle granite
rugged sky
subtle granite

I got the volume change done, by saving the resource in a map

thanks

true fox

getting this error everytime the bot is disconnected from a vc

open tulip

Hi

i have a command that connect bot to mentioned vc but why when i use it give me this err

subtle granite
torpid narwhal

how can i make <VoiceConnection>.ping.ws not return undefined?

empty ibex

My ytdl Discord bot is still laggy in the voice channel. According to these posts:
https://github.com/fent/node-ytdl-core/issues/405#issuecomment-456410319
https://v12.discordjs.guide/voice/optimisation-and-troubleshooting.html#using-highwatermark

you could set the highWaterMark options like so (one for ytdl and one for discordjs v12):

let dispatcher = queue.connection.playStream(
  ytdl(music.url, {filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1<<25 }),
  {highWaterMark: 1});

I could not find a way to set the highWaterMark on discordjs v13. How can I do this?

half pumice

Hello there, I am making a discord music bot and I get this error. (I am using DisTube) the support server says that this is a djs error

Cannot read property 'set' of undefined
    at C:\Users\dante\Desktop\OutLand-Source\node_modules\discord.js\src\structures\Guild.js:1388:34
    at new G (C:\Users\dante\Desktop\OutLand-Source\node_modules\@discordjs\voice\dist\index.js:8:7254)
    at Oe (C:\Users\dante\Desktop\OutLand-Source\node_modules\@discordjs\voice\dist\index.js:8:12358)
    at gt (C:\Users\dante\Desktop\OutLand-Source\node_modules\@discordjs\voice\dist\index.js:8:12577)
    at DisTubeVoice._DisTubeVoice_join (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\voice\DisTubeVoice.js:246:41)
    at DisTubeVoice.set channel [as channel] (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\voice\DisTubeVoice.js:96:106)
    at new DisTubeVoice (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\voice\DisTubeVoice.js:39:22)
    at DisTubeVoiceManager.create (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\voice\DisTubeVoiceManager.js:36:16)
    at QueueManager.create (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\core\manager\QueueManager.js:37:35)
    at DisTube.play (C:\Users\dante\Desktop\OutLand-Source\node_modules\distube\dist\DisTube.js:197:60)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
Unhandled 'error' event.
See: <link>```
That is the error
Here is my code 
```JS
const { Discord, MessageEmbed } = require("discord.js");
const config = require("../../config/emojiConfig.json");

module.exports.run = async (client, message, args) => {
    return message.channel.send("You actually thought\nFeature comming soon!");

  const { options, member, guild, channel } = message;
  const VoiceChannel = member.voice.channel;

  const Embed = new MessageEmbed().setColor(config.colors.grey);

  if (!VoiceChannel) {
    return message.reply({
      embeds: [
        Embed.setDescription(
          `${config.emojis.denied} You must be in a voice channel to use this command.`
        ).setColor(config.colors.red),
      ],
    });
  }

  if (guild.me.voiceChannelId && VoiceChannel.id !== guild.me.voiceChannelId) {
    return message.reply({
      embeds: [
        Embed.setDescription(
          `${config.emojis.denied} I'm already playing music in <#${guild.me.voice.channelId}>`
        ).setColor(config.colors.red),
      ],
    });
  }

  try {
    client.distube.play(message.member.voice.channel, args.join(" "), {
      textChannel: message.channel,
    });
  } catch (err) {
    return message.channel.send({
      embeds: [
        Embed.setDescription(`${config.emojis.denied} ${err}`).setColor(
          config.colors.red
        ),
      ],
    });
  }
};

module.exports.config = {
  name: "play",
  aliases: ["p"],
  category: "",
  displayName: "",
  description: "",
  usage: "play <query>",
};
fervent estuary
half pumice
upbeat gust
fervent estuary

doesnt make ur issue voice related

fervent estuary
half pumice 13

i dont know about the internal workings of distube but seems like no voice adapter was created

could you log client.voice.adapters for me

half pumice

gimme a sec

vale eagle

Ok

bitter marsh

12.5.3 da best

subtle granite
subtle granite

Thanks in advance

slender sparrow

use play-dl instead of ytdl-core if you dont want aborted issue

subtle granite
slender sparrow

I'm not using ytdl-core

subtle granite

so i'm trying to fix it

slender sparrow

well, you provide the code that had ytdl-core. no clue then

half pumice
fervent estuary

what about client.voice

half pumice
half pumice
fervent estuary

ok

can you do client.voice.get("id of the guild where youre trying to play audio")

and tell me the result

fervent estuary

just a moment ill check something

thats odd

client.voice shouldnt be a collection

half pumice
fervent estuary

thats client.voice

half pumice

huh

half pumice
fervent estuary

yeah thats a problem

half pumice

lemme see if it works now

half pumice
fervent estuary

remvoe that piece of code i told u to add

half pumice
fervent estuary

ic

if thats vital for the operation of ur code and bot ull have to rename it to something else

gritty gorge

Hi! I'm trying to stream music from a radio station using discord.js v13. However, I can't find any code that don't use ytdl or local files. Does anyone have a solution?
PS: I tried to create a ressource with the URL but it's not working (and it doesn't output any error).

const resource = createAudioResource(this.streamURL);
this.audioPlayer.play(resource)
rugged sky
gritty gorge

Okay thanks I'll take a look

wraith carbon

is it possible to make the bot say something from a string

finite grotto

sounds like you want a tts package
which is not what we have here, go search npm

solar scaffold

Why does this keep happing like 3/4ths through the song?

this new voice library sucks ass ngl idk why it wasnt just left the same

icy maple
solar scaffold

why was it never an issue before

icy maple

Recent yt api changes ig?

It's a known issue w/ ytdl-core

You should switch to play-dl instead

solar scaffold

hmm

thanks catsmile

@icy maple is there like better instructions on how to use this anywhere cuz like the documentation doesnt even seem to have any functions for playing music just getting info

oh 🧍🏼‍♂️ im blind

mb

icy maple

They should have an example w/ d.js

solar scaffold

why does it play from the info doe why not just the link PepeHands

solar scaffold

i appear to just be really blind tonight and i suppose its the 3 hours of sleep, thanks for the help

icy maple

Tho, you could do more stuff w/ the info

solar scaffold

tired programmer = useless programmer

icy maple

A wise Evie once said "A tired programmer is a dumbass programmer"

solar scaffold

💀 shes my favorite

solar scaffold

nevermind this library is built by pepegas

icy maple
solar scaffold
zealous coyote

Error: Cannot play audio as no valid encryption package is installed.

  • Install sodium, libsodium-wrappers, or tweetnacl.
  • Use the generateDependencyReport() function for more information.

can some one give me help

icy maple
zealous coyote
icy maple

The first bullet point

vale eagle

My discord bot waits for someone to say something in vc and then replies with a random answer

It is is 1000 servers and starts lagging after like 10 hrs of being online

What's a fix?

My server I run the bot on is a
64gb ram ubuntu server
With 8 cores and 4 TB of storage

subtle granite

try sharding ur bot even with this amount of guilds

loud breach
let stream = await playdl.stream(args[0], { quality: 1 })

let resource = createAudioResource(stream.stream, {
    inputType: stream.type,
    inlineVolume: true
})

let player = createAudioPlayer({
    behaviors: {
        noSubscriber: NoSubscriberBehavior.Pause
    }
})

player?.play(resource)

connection.subscribe(player)

Its laging for some reason and I cant find out why at all. Any advice?

vale eagle
vale eagle
subtle granite

dunno very much about voice, client.voice ig

icy maple

Just iterate over them and call destroy

vale eagle

thim pretty

im pretty sure they removedd this in discord js 13

as i dont see it on the docs anymore @icy maple

icy maple

Top-level functions are not shown by the docs

vale eagle

so
client.getVoiceConnections()?

icy maple

No

It's a top-level function of the voice package

vale eagle

ah ok they should show those

icy maple

Hopefully in a future version of tsdocs + docsgen

vale eagle

ok it works
thx

vale eagle

as my bot is in 1k+ servers and im switching to shards

fallen tapir
dark ridge

How would I detect if my bot is already in a voice channel?

vale eagle
frank kelp
vale eagle

fetchClientValues returns an array, look at the .then() in the guide

vale eagle

but its still doing it

frank kelp

doing what

vale eagle
frank kelp

that code you just sent will not show 900000 servers unless your bot is in 900000 servers

vale eagle

xd

livid furnace

Hey, my bot keeps randomly looping, skipping, and stops playing. Is there a list of things that could be going on or that I should look into? It works in test but breaks in prod

I'm using play-dl for the audio

and streaming stuff I uploaded to youtube

subtle granite

AbortError: The operation was aborted
How do I fix this error?

wary rain

listened music, appeared

const ytdl = require('ytdl-core');
client.on("messageCreate", msg => {
  if (msg.content === "test") {
    const {
      AudioPlayerStatus,
      StreamType,
      createAudioPlayer,
      createAudioResource,
      joinVoiceChannel,
    } = require('@discordjs/voice');
    
    const connection = joinVoiceChannel({
      channelId: "960932830337183764",
      guildId: "876058982609989654",
      adapterCreator: msg.guild.voiceAdapterCreator,
    });
    
    const stream = ytdl('https://youtu.be/EP625xQIGzs', { filter: 'audioonly' });
    const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
    const player = createAudioPlayer();
    
    player.play(resource);
    connection.subscribe(player);
    
    player.on(AudioPlayerStatus.Idle, () => connection.destroy());
  }
})```
pseudo forum
wary rain

how to get a preview

(await play.video_info("https://youtu.be/EP625xQIGzs")).video_details```
subtle granite
wary rain

how to get video preview in play-dl

bright oracle

how do I make my bot leave automatically after playing music, my code looks like this, but it doesn't work

player.on('AutoPaused', () => {
      //如果队列中仍有歌曲
      if (this.queue[guildID].length > 0) {
        this.playMusic(msg, guildID, this.queue[guildID][0]);
      } else {
        this.isPlaying = false;
        msg.channel.send({embeds: [
          new MessageEmbed()
          .setColor('#3498DB')
          .setTitle('End of queue')
          .setDescription('.help for commands')
          .setTimestamp()
        ]});
        this.connection.destroy();
      }
    });
subtle granite
stoic orbit
finite grotto
weak monolith

im trying make my bot automatically become speaker after joining a stage channel but I get this error:
interaction.guild.me.voice.setSupressed is not a function

rose helm
weak monolith

yeah, also spelt suppressed wrong

rose helm

setting suppression wouldn't work anyways since you need to request to speak in a stage channel

weak monolith

Error [VOICE_NOT_STAGE_CHANNEL]: You are only allowed to do this in stage channels. - thats on the set suppressed

rose helm

ah welp. I guess discord.js' interface is ambiguous to someone who doesn't use it

weak monolith

I use to use it a lot back in the days of 1.11 and 1.12 but when 1.13 came out a lot of things puzzled me so i ended up just giving up but need this for a project im working on

got it working in the end, its because the stage channel wasnt started

pseudo forum
fiery pond
TypeError: client.voice.onVoiceStateUpdate is not a function
    at VoiceStateUpdate.handle (/home/container/node_modules/discord.js/src/client/actions/VoiceStateUpdate.js:29:22)
    at Object.module.exports [as VOICE_STATE_UPDATE] (/home/container/node_modules/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js:4:35)
    at WebSocketManager.handlePacket (/home/container/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
    at WebSocketShard.onPacket (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/home/container/node_modules/ws/lib/event-target.js:199:18)
    at WebSocket.emit (node:events:526:28)
    at Receiver.receiverOnMessage (/home/container/node_modules/ws/lib/websocket.js:1137:20)
    at Receiver.emit (node:events:526:28)
    at Receiver.dataMessage (/home/container/node_modules/ws/lib/receiver.js:528:14) uncaughtException
 [Error_Handling] :: Uncaught Exception/Catch```

anyone please help
fervent estuary

that is not a thing

are you trying to get the voiceStateUpdate event?

silk dome

It’s an error within a djs file

silk dome
silk dome

Oh okay

fiery pond

Thanks

subtle granite

this seems to fail when i install it, here's the log file, any idea what's going on?

exotic barn

how can i use custom ffmpeg arguments for audio resources?

fervent estuary

you can

rose helm

pipe the audio through a prism ffmpeg instance

exotic barn
subtle granite

AbortError: The operation was aborted
How do I fix this error?

sturdy sail

i've tried to get the bot an event when the user starts listening, but the event is never called ```ts
const connection = await joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
selfDeaf: false,
selfMute: false,
adapterCreator: channel.guild.voiceAdapterCreator,
})

            const receiver = connection.receiver

            receiver.speaking.on('start', userId => {
              console.log('receiver speaker, start', userId)
            })```
lean sierra

Hello, I'm currently facing an issue where there are certain songs on YouTube that just stop when I try to play it (as if they have 0 duration). It seems to happen whenever the audioresource uses the oggdemuxer. But when it uses the webmdemuxer, there isn't any issue. Does anyone know why?

EDIT: turns out this was a youtube-dl issue. I tried using play-dl now it works fine.

stone halo

How to make skip or stop - Music Bot

stone halo

connection.dispatcher.end() results in TypeError

pine mulch

how to get what user is speaking from
connection.receiver

(cant find any docs)

mortal dawn

Is there a way to receive the AudioPlayer object when using getVoiceConnection?

icy maple
mortal dawn
pine mulch

how to get audio/string (i dont think we can get string without google api) from voice channel receiver?

light basin
                async execute(interaction) {
                    const channel = interaction.member.voice.channel;
                    if(!channel) return interaction.reply("You are not in a voice channel. I can't sing.");

                    const player = voiceDiscord.createAudioPlayer();
                    const resource = voiceDiscord.createAudioResource('./pathtofile.mp3');

                    const connection = voiceDiscord.joinVoiceChannel({
                        channelId: channel.id,
                        guildId: interaction.channel.guild.id,
                        adapterCreator: interaction.channel.guild.voiceAdapterCreator,
                    });
                    player.play(resource)
                    connection.subscribe(player)

                    player.on(voiceDiscord.AudioPlayerStatus.Idle, () => {
                        connection.destroy();
                    })
    }

so i got this code, but the bot joins the vc and then instantly leaves, why?

also, even if i remove the connection.destroy part, the bot doesnt play anything.

languid quail
light basin

lemme try

same thing happens

languid quail
light basin

nothing playing
it changed now, sorry

languid quail
light basin

no
i meant now it joins, doesnt play anything and never leaves

light basin
languid quail
light basin

yeah but if i remove player.on(voiceDiscord.AudioPlayerStatus.Idle, () => { connection.destroy(); })
it still doesnt play anything

light basin

please..

languid quail
waxen wedge

Does the mp3 file exist?

light basin
languid quail
light basin

Same error

Well, problem

languid quail
light basin

One sec

light basin
languid quail show new code

sorry for the wait

                    const channel = interaction.member.voice.channel;
                    if(!channel) return interaction.reply("You are not in a voice channel. I can't sing.");

                    const player = voiceDiscord.createAudioPlayer();
                    const resource = voiceDiscord.createAudioResource('./filename.mp3');

                    const connection = voiceDiscord.joinVoiceChannel({
                        channelId: channel.id,
                        guildId: interaction.channel.guild.id,
                        adapterCreator: interaction.channel.guild.voiceAdapterCreator,
                        selfDeaf: false,
                    });
                    connection.subscribe(player)
                    player.play(resource)

                    player.on(voiceDiscord.AudioPlayerStatus.Idle, () => {
                        connection.destroy();
                    })
    }```
languid quail
light basin

ok

joins, and doesnt do anything

and i played the music file, it does indeed work

light basin

so @languid quail are you still able to help me?

or anyone

languid quail
light basin

yea

languid quail
light basin yea

hmmm, idrk what the problem is
You don't have the bot muted or anything from your side, right?

light basin

oof
also no i dont
its unmuted, undeafened

waxen wedge
languid quail
light basin

well yeah i do tho

waxen wedge
languid quail
light basin

as you can see it's normal so

light basin

I have it enabled tho

so that isn't the problem

light basin

so, how do i solve the problem? or dont i?

languid quail
light basin

off

i added a ready status check

it said it's ready, but no audio was played

languid quail
light basin

it's already there
:/

@languid quail does this help?

waxen wedge
light basin

lemme try another one
what format is the best to test?
maybe mp3 has some issues because ffmpeg

waxen wedge

.ogg or .webm to not rely on ffmpeg I guess

light basin

what if its because of the bitrate?
discord has a max 64k i think

waxen wedge

ffmpeg should resample that on the fly I think

light basin

same thing happens
bruh

light basin

i got it
somehow

languid quail
light basin
languid quail
light basin

basically added this:

let resource = createAudioResource(join(__dirname, 'soldierpoetking.mp3'));
        resource = createAudioResource(createReadStream(join(__dirname, 'soldierpoetking.ogg'), {
            inputType: StreamType.OggOpus,
        }));
        player.play(resource);

it worked idk how

waxen wedge
light basin

probably

jovial patrol

Guys can you help me

light basin

alright another question, how to check if the bot is alr in a vc? like i made it play the song and all, but if someone in another vc does the command WHILE the bot is in a diff vc, it will leave the first one and get into the second one. How to do this checking?

waxen wedge
light basin
waxen wedge
dusty needleBOT

Documentation suggestion for @light basin:
_ VoiceState
Represents the voice state for a Guild Member.

light basin

yeah, ik that, thanks tho 😄

subtle granite

I get this error every time i try to install certain npm packages (enmap and @discordjs/opus), can anyone help? works on my windows pc and i have same npm and node version installed on both

tall fog

regarding this error, it's a node-gyp problem. you can't do anything for now

safe field

i can't seem to get the voice working.
currently, im using this

client.on("ready", async() => {
    const channel = client.channels.cache.get("<insert id here>");
    const connection = joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
    });
});

but it doesnt seem to join the voice channel, or throw any errors.

hollow copper

how would i seek local audio files?
dont see a seek option for audioResource

vale eagle

how would set a listener for just someone talking in any connection i have as


(node:1183014) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 start listeners added to [Q]. Use emitter.setMaxListeners() to increase limit
(node:1183014) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 end listeners added to [Q]. Use emitter.setMaxListeners() to increase limit
(node:1183014) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 start listeners added to [Q]. Use emitter.setMaxListeners() to increase limit
(node:1183014) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 end listeners added to [Q]. Use emitter.setMaxListeners() to increase limit
vale eagle

put the id where it says <insert id here>

subtle granite
vale eagle
waxen wedge
vale eagle

wanna make it leave after scilence but if a person is speaking to the bot longer than the timeout it will leave

and i want it to leave after a certain amount of scilence

subtle granite

You could do everything in the on end listener below instead of creating a new listener everytime someone starts speaking

waxen wedge

You should do that even. Never create more than one listener for any events, only leads to ugly race conditions

You also don’t even check who stopped talking, could be someone else than the one who started speaking. So if Person A starts, B says a short word and A keeps on talking during then person B stopping would end the event for A too…

vale eagle