#archive-voice

30636 messages · Page 20 of 31

subtle granite
    at MessagePayload.resolveData (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\structures\MessagePayload.js:184:36)
    at TextChannel.send (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:167:61)
    at Object.execute (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\events\messageEvent.js:27:23)
    at Client.<anonymous> (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\index.js:42:46)
    at Client.emit (node:events:394:28)
    at MessageCreateAction.handle (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:18)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:345:31)
    at WebSocketShard.onPacket (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
    at WebSocketShard.onMessage (C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
PS C:\Users\WhoAboutYT\Documents\GitHub\vlado-bot> ```
      .setTitle('You may not run this command at the time.')
      .setDescription(`You may run this command in ${ms(a - Date.now(), { long: true })}`)
      .setColor('RANDOM')
      message.channel.send({embeds:embed})``` 
pls help

nvm fixred

carmine timber
vernal jasper

hey guys, id like to add a play music feature to my bot, where do i start?

rugged sky
neon halo

Hi, I've been trying to make a music bot. Right now I'm just trying to make it so that it plays the next song in the queue, it'll play the next song in the queue once but after that it stops playing.
https://sourceb.in/PL8vs2jJpe

rugged sky
vague remnant

So uh, im trying to play from an .ogg file, and the audio just isnt playing. The code is basically this:

const resource = createAudioResource('./data/cache/current-audio.ogg')
player.play(resource);
connection.subscribe(player);

And the music works fine with a direct stream, so i'm not sure why its not working with a file path. The file itself is present and i can play it with other software locally, so that isn't an issue either. The player isnt erroring either, since i have it log errors in console, and nothing shows up.

its not working with any file in general, not a .ogg specific issue im having, tried mp4 and webm too

carmine timber
vague remnant

does it not take relative paths at all?

carmine timber

No it don't take relative paths

vague remnant

nope its not working with the absolute path either, same issue, nothing is playing and no errors either

carmine timber
vague remnant

as i said, everything works fine if i use a direct audio stream, so its not a permission issue

carmine timber
vague remnant

its... literally the same code with the absolute path... how would you verify my absolute path anyway?

vague remnant

existsSync works fine

i use it to check before trying to play the audio, and it passes the check

again if the path was wrong it would error because it wouldnt be able to find the file

its able to create the resource, i log it and it shows the file im trying to play

vague remnant

Ok so the issue seems to be that the audio player cant switch between playing from an Internal.Readable resource to a file resource? Unless im mistaken.

If i try to play from a stream and then play a new resource from a file, it doesnt play, but if i play from a file first its fine

carmine timber

@vague remnant It would be great if you debug your dependencies. Since ffmpeg-static has some issues while playing from a file.

vague remnant

im not using ffmpeg-static

i have ffmpeg installed on the os

supple lava

How to understand that a bot has finished playing a track to start a new one?

vague remnant

have a callback on the AudioPlayerStatus.Idle event for your audio player

rotund wave

hi, I wanted to write a code in the event we know as "voiceStateUpdate" in v12, but this situation has changed in v13. What should I do in v13? (I just started using v13e. I don't know anything)

edgy burrow

What's the problem you're having in v13?

rotund wave

There is no "voiceStateUpdate" in v13. i want to know what i can use instead @edgy burrow

edgy burrow

voiceStateUpdate exists in v13

rotund wave

oh🤧

what can i use instead?

edgy burrow

It exists.
voiceStateUpdate exists

rotund wave

I understand what you want to say. Is there anything else in his mission?

like any other event

edgy burrow

voiceStateUpdate is the only voice event

rotund wave

so I can't do in v13 what I can do in v12?

edgy burrow

Yes you can, you can use voiceStateUpdate

rotund wave

but im using v13

edgy burrow

Yes, it's also a thing in v13
It did not get removed in v13

dusty needleBOT

_ (event) Client#voiceStateUpdate
Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.

edgy burrow

Do you have the GUILD_VOICE_STATES intent?

rotund wave

let me see

oh no. thank u <3

neon halo

If I created a player how would I be able to pause it in a different file

vague remnant

player.pause() pauses the player

player.unpause() unpauses it

neon halo

I defined it in a different file

haughty dagger

Could someone please explain to me the reason for the following error - i.e. what it means/what causes it?

Error: Cannot perform IP discovery - socket closed
    at Socket.<anonymous> (/app/node_modules/@discordjs/voice/dist/networking/VoiceUDPSocket.js:120:52)
    at Object.onceWrapper (node:events:509:28)
    at Socket.emit (node:events:402:35)
    at socketCloseNT (node:dgram:755:8)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)
vague remnant
sour citrus

wtf

sour citrus

help

regal girder

Does anyone know how to trigger a function when an audio player finishes playing an audio resource? I want to run several lines of code as soon as an audio player finishes playing a song.

rose helm

listen for the player idle event

sour citrus

doesn't output "ok", why?

regal girder
sour citrus

pls help 🙂 doesn't showning the "ok man"

:/

opaque crag
neon halo
opaque crag
carmine timber
carmine timber
rugged sky
neon halo
eager crag
Error: Cannot find module 'node:events'
Require stack:
- /home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/client/BaseClient.js
- /home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/index.js
- /home/runner/QuerulousSandybrownExams/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
    at Function.Module._load (internal/modules/cjs/loader.js:667:27)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/client/BaseClient.js:3:22)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/client/BaseClient.js',
    '/home/runner/QuerulousSandybrownExams/node_modules/discord.js/src/index.js',
    '/home/runner/QuerulousSandybrownExams/index.js'
  ]
}
dusty needleBOT
dusty needleBOT
carmine timber
supple lava

Sometimes a strange situation happens:
I turn on the track and I have a check if there is a queue or not. If not, then the specified track is included. If there is a queue, then the track is recorded in the database for the next playback.
Also I have a check for PLAYER IDLE STATE.

The problem is that sometimes after the end of the track I wait about 2-5 minutes and turn on the song again, then he skips it and clears the queue as it becomes empty. Can you help with this, please?

carmine timber
supple lava

I believe this issue is related to connection.subscribe(). Now I will try to solve it...

No, that's not the problem

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

            const audioplayer = voice.createAudioPlayer();

            if (!audioplayer.subscribers[0]) {
                connection.subscribe(audioplayer);
            }

            const resourceFirst = await voice.createAudioResource(`{HERE PATH TO TRACK}`);

            console.log(audioplayer);

            audioplayer.play(resourceFirst);

@carmine timber Here

And SKIP

const connection = voice.getVoiceConnection(message.guild.id);

connection.state.subscription.player.stop(true);
carmine timber
carmine timber
supple lava

How to get a text channel from event?

carmine timber
supple lava
vague remnant

So i'm still having the issue i was having before, essentially, if i play an Internal.Readable resource from a stream, then i play from a file, nothing plays, and the player doesn't error either.
I have all the dependencies installed i think? heres the debug for it:

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

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

Encryption Libraries
- sodium: 3.0.2
- libsodium-wrappers: not found
- tweetnacl: not found

FFmpeg
- version: 4.2.4-1ubuntu0.1
- libopus: yes

Also @discordjs/opus gives me npm warnings when i install it

rose helm

I can't seem to find in the code where the VolumeTransformer pipes data through ffmpeg

subtle granite

Hello everyone sorry to disturb but i just followed a tutorial to create a music bot but the bot won't join the channel ... 🙃

subtle granite

An i have no error

fiery latch

Is it just me or is just simply playing a simple audio file far harder in v13 than v12?

opaque crag

not really I really like the new player thing

obsidian sable

kinda upset that v13 requires a non LTS version of Node

valid marsh

Will be LTS soon

obsidian sable

i wont ever be able to go to anything higher than v14 LTS on my hardware (older homelab) sadly

fiery latch

I'm writing double the code to achieve the same thing, and just making sure I am not going wrong somewhere haha

opaque crag

is there a way I can await an audio resource becoming playable ? like wait 10secs to see if it will become playable otherwise destroy it

fervent estuary

you can setup a timeout urself

ruby current

How can i listen to the 'stateChange' event on a second .js file aside from the main.js file?

instead of having the player.on('stateChange' , ...) code on the main.js have it on the musicplayer.js file where i have the play skip queue and other commands

vague remnant

you can put the player into that file?

if main.js has nothing to do with the music aspect why have the player be there

ruby current

the player is on the second file

but when i use player.on('stateChange' , ...) on this file the event is never detected

vague remnant
ruby current

no

that should be done with the player.addEventListener method?

vague remnant

no you can use player.on()

the main issue is if the player isnt the same instance that is actually playing the music

if they are different players events from one of them wont trigger for the other

ruby current

there's only one player across all files, which is created there in reproductor.js

final jay

will we have a seek option with djs voice in the future?

carmine timber
wet roost

How can I make my bot join vc?

const channel = interaction.member.voice.channel;
   channel.join()```

Not working
wet roost

K

wet roost

How can I make my bot join vc?

const channel = interaction.member.voice.channel;
   channel.join().then(connection => {
    
    console.log("Successfully connected.");
  }).catch(e => {
    
    console.error(e);
  });```

 getting channel.join() is not a function
slender sparrow

not working because you havent try it yet

wet roost
slender sparrow not working because you havent try it yet

See

const { joinVoiceChannel } = require('@discordjs/voice'); const connection = joinVoiceChannel({ 	channelId: channel.id, 	guildId: channel.guild.id, 	adapterCreator: channel.guild.voiceAdapterCreator, });```

Aftee that what to do im confused ;-;
slender sparrow

you didnt define the channel id, guild id, adapter properly

red slate

I'm trying to make a music bot and it isn't reading my messages from discord plus I'm new to js as well. Can anyone please take a look

const { version } = require('os');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });


const ytdl = require("ytdl-core");

const PREFIX = '!';

var servers = {};

client.on('ready', () => {
  console.log(`The bot is online!`);
});

client.on('message', message => {
  console.log("Before switch");

  let args = message.content.substring(PREFIX.length).split(" ");
  switch(args[0]){
    case 'play':

      console.log("play reached");
      function play(connection, message){
        var server = servers[message.guild.id];


        server.dispatcher = connection.playStream(ytdl(server.queue[0], {filter: "audioonly"}));

        server.queue.shift();

        server.dispatcher.on("end", function(){
          if(server.queue[0]){
            play(connection, message);
          } else {
            connection.disconnect();
          }
        });


      }


      if(!args[1]){
        message.channel.send("You need to provide a link!");
        return;
      }

      if(!message.member.voiceChannel){
        message.channel.send("You must be in a voice channel to play this bot!");
        return;
      }

      if(!servers[message.guild.id]) servers[message.guild.id] = {
        queue:[]
      }

      var server = servers[message.guild.id];

      server.queue.push(args[1]);

      if(!message.guild.voiceConnection) message.member.voiceChannel.join().then(function(connection){
        console.log("lol dewd");
        play(connection, message);
      });




    break;

  }
});```

It should be playing the songs just by this code but my guess is it's not reading the messages

subtle granite

hello why this can't working fix ${client.voice.connections.size}

@carmine timber

subtle granite

hu now what we do to see status of connection?

carmine timber
subtle granite

oh okay thanks

fading prawn

Do I have to have discordjs/voice installed in order for voiceStateUpdate to work?

slender sparrow

no, you need intent

fading prawn

Ahhhhhhhh

Gotcha. Thanks.POGFurret

cursive nimbus

is there any way to get the connection and destroy it other than creating the variable connection = joinVoiceChannel() ?

cursive nimbus
sonic wraith

Is there a way to trigger an event when audio player finishes playing resource?

fervent estuary

when the audioPlayer state changes from playing to idle

final jay

how can I know if the bot actually disconnected or if it just switched voice channels?

vernal jasper
const connection = joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
});
``` how do i get the channel?
fervent estuary
vernal jasper

i mean when i use this code this code, it sais that channel is undefined

fervent estuary

u will have to define channel as an instance of voiceChannel

either by getting it from cache or from a member that executed a command

vernal jasper
const channel = bot.channels.cache.get('channel-id');
```?
final jay
fervent estuary
vernal jasper

kk

fervent estuary

u will still need an instance of guild tho in order to get the adapter

vernal jasper

wdym

vernal jasper
fervent estuary

which event are you calling the joinVoiceChannel in?

vernal jasper

in the main file

fervent estuary

event

not file

vernal jasper

any xd

in cron

it repeats every minute

fervent estuary

do u wish the bot to join the channel when u send a command or automatically on login?

vernal jasper
fervent estuary

alright

vernal jasper

i want to at least

fervent estuary

in that case you can just get the guild with client.guilds.cache.get(guildID)

fervent estuary

mistyped it as cant. Thats how you can get it. My bad

const connection = joinVoiceChannel({
    channelId: "channel id",
    guildId: "guild id",
    adapterCreator: guild.voiceAdapterCreator,
});
```so you can just do this. Where `guild` is `const guild = client.guilds.cache.get("id")`
vernal jasper
fervent estuary

did you define guild?

vernal jasper

yep

fervent estuary

send me the code around that part now

solemn current

Youtube-dl is not workin when it joins the voice channel it plays the Silence_frame

subtle granite

Help me pls

cursive nimbus

what is this error guys ?

vernal jasper
cursive nimbus
vernal jasper
cursive nimbus

only that one

worryback

vernal jasper
cursive nimbus

its not a error message, its a warning that your using experimental features that may soon be removed i think

vernal jasper
cursive nimbus
vernal jasper

not djs related btw

primal mist

My bot joins the channel but doesnt play anything.
It can parse the link/search and gets the video without any errors but doesnt play

primal mist

It isnt lighting up green its just sitting there

vernal jasper

try with another song

or try with file

rugged sky
primal mist
rugged sky

Can you show your join and play music code?

primal mist
rugged sky

You need to call connection.subscribe(player) to tell you connection to stream whatever the player is playing

primal mist
rugged sky

At any point when both are initialized, doesn't matter.

primal mist
subtle granite

Hello

Is any way we do some eval command bot automatically least all vc there it playing songs

primal mist

I notice sometimes when it buffers or lags it plays it rapidly to get back to where it should be. Is there any solution to this or is this a downside that isnt solvable?

sly bronze

How i can check if my bot is the only user in a voice channel?

my bot plays music, but i will that he leaves when the channel is empty (regardless if he play music or not)

dusty needleBOT
primal mist
sly bronze

ah

sly bronze

can i get a number of the users they in the same voice?

rugged sky
sly bronze
rugged sky
sly bronze

and how i can check if my bot is in this channel?

sly bronze
rugged sky

You can use getVoiceConnection(<guildId>) to get the output of a VoiceConnection object or undefined depending on if your bot is in a channel on that guild.

That's a function from @discordjs/voice

sly bronze

and from this object i need only the channel id. But i cant find it

sorry im dump

i found it haha
BUT THANKS!

pseudo forum

I said read the pin in this channel ._.

subtle granite
viral hollow

My bot won't play audio when there's 6 people in the voice channel at once

He can join, and he'll play about 1 second or so of audio before just stopping, if I go to a VC with it alone it works fine

fiery latch

I feel like this might be a type bug 🤔

        guildId: interaction.guildId,
        channelId: voiceChannel.id,
        adapterCreator: interaction.guild?.voiceAdapterCreator
    });```

If I assert the type as DiscordGatewayAdapterCreator it works and the bot joins the channel with no errors.

Unless I am missing something.

vernal jasper
const { createAudioPlayer, NoSubscriberBehavior, joinVoiceChannel, createAudioResource } = require('@discordjs/voice')
module.exports={
    description:'',
    execute(bot,interaction){
        try{
        const channel = bot.channels.cache.get('895765320034291736');
        const guild = bot.guilds.cache.get(`895765319560331337`)
        const connection = joinVoiceChannel({
            channelId: `895765320034291735`,
            guildId: `895765319560331337`,
            adapterCreator: guild.voiceAdapterCreator,
        });
        const player = createAudioPlayer({
            behaviors: {
            noSubscriber: NoSubscriberBehavior.Pause,
        },  
        });
        connection.on("stateChange",(oldState,newState)=>{
            console.log(oldState,newState)
        })
        const resource = createAudioResource('./data/barka.mp3');
        interaction.reply('t')
        player.play(resource);
    }catch(e){console.log(e)}
    }
}

hey guys, why doesnt the bot join the vc?

channel.join is not a function

fiery latch

if you use Discord v13, that way of joining a voice channel is no longer a thing

You need to use @discordjs/voice package


const connection = joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
});```
vernal jasper
const player = createAudioPlayer();
const resource = createAudioResource('link or path to file');
player.play(resource);

thats how u play music

fiery latch
rugged sky
rugged sky
vernal jasper

look higher

vernal jasper
rugged sky
vernal jasper no error

Can you change it to this:

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

and try again?

vernal jasper
rugged sky
rugged sky
vernal jasper
rugged sky
vernal jasper

no

npm install ffmpeg-static

rugged sky

Read the page I linked, it explains it.

vernal jasper
rugged sky
rugged sky
viral hollow
vernal jasper
rugged sky
rugged sky
viral hollow

My bot doesn't want to play audio when there's too many people in the VC and I can't figure out why. No error or anything, it just doesn't want to play

fervent estuary

There are no events on player.play()

rugged sky

A few things. Change line 62 to player.on('idle', () -> { Also, channel.leave() is not a function.

fervent estuary

Yes as thats not a thing

vernal jasper

nvm

rugged sky

Playing songs with the AudioPlayer and joining voice channels are two separate things. You have to do both.

fervent estuary

Are you using v12 or v13?

I see code for both

rugged sky

In your joinVoiceChannel() the ids should be strings, not ints.

vernal jasper

how to disconnect a bot from a channel

fervent estuary

connection.destroy()

rugged sky

That's usually better, yeah.

vernal jasper
rugged sky

You still have to subscribe the connection to the player: connection.subscribe(player)

Just put it after your .play() it doesn't really matter.

No, you can't call .play() on a connection, and that .on will also make you crash.

fiery latch
  1. create player const player = createAudioPlayer()
  2. create a connection const connection = joinVoiceChannel({...options});
  3. subscribe the player to the connection connection.subscribe(player);

Does that help?

rugged sky

You just sent a screenshot when you had player.play(...)

At any point where both the player and connection exist. It doesn't matter where.

Legit this @subtle granite

fiery latch

apzrn, have you recently upgraded your Discord.js version to v13 under a v12 codebase?

Ahhhh
v13 is a whole different ball game

Everything to do with voice has changed basically

rugged sky

Matte told you the .on part was a problem. Not the .play(). What he said was because you need to call .on(...) on something and the way you did it, it would've been on the output of some other function which doesn't work. That's why I said change it to player.on('idle', () => { connection.destroy() }

fiery latch

It is TS, but it shouldn't be hard to filter that out hopefully it helps you

fervent estuary

For simplicity before you start implementing @discordjs/voice just remove everything that has to do with v12 voice in ur code. Otherwise youll end up with a mess

fiery latch

Yeah Matte, there was so much in my old youtube bot that would need refactoring that I just started a new project entirely 😂

npm i tweetnacl

rugged sky

Not the FFmpeg part, but the debug dependecy part @subtle granite

fiery latch

wym?

Can you send a screenshot?

What was it before? Do you use a transparent profile picture or something? I am not sure but maybe discord has a background colour set in the profile pic for a transparent picture?

I doubt it is anything serious though :)

rugged sky

Does the bot play music or no?

fiery latch

Huh maybe it's a Discord quirk I am not aware of Thinkeng

rugged sky

Do you have the GUILD_VOICE_STATES intent?

Yes

Yeah, that's fine.

fiery latch

yeah you only specify once you init the client

have you hard-coded the resource for the version of the code you are testing?

or should I say not coded in

rugged sky

Yeah, was just about to mention that haha.

fiery latch

well in the code you provided, the createAudioResource method does not have a valid audio bitstream as an argument

rugged sky

Most tutorials are still from v12, since v13 is still only a few months old.

fiery latch

Yeah also like Touche says, v13 is wayyyyyy different

Make sure when you watch video guides, you watch for discord v13. It's vastly different in almost every aspect

rugged sky

You can input that stream object into the createAudioResource(stream), but the rest of the if-statement in this iswrong. I'm actually surprised this hasn't crashed you yet. Just remove all of that and use the stream object.

fiery latch

well, my old youtube bot I made that has quite a few features became wayyy too much hassle to refactor to v13 because v13 is so different. I just started a new project instead, I think that would be the best way to go or at the very least archive big chunks of v12 code and rewrite with v13.

Ayyyy 😂

Don't get rick rolled too easily 👀

One thing I do notice in the code you sent is that you're passing in an instance of Message into your function but my code uses the new CommandInteraction instance (the variable called "interaction")

So you may need to swap out the "interaction" variables for "message". I can't guarantee that will give no errors though!

Ah yes, you're using commonjs. My codebase uses the new ES6 module syntax. It should be safe to swap it to const.

Ok one glaring obvious thing I forgot to mention is that globals is my own creation so it will not exist in your project.
In my code globals contains a variable called "audioPlayer" which is simply the result of createAudioPlayer()
So delete the whole globals import and just create a variable called player which is created with createAudioPlayer()

By the way, the reason I did that is because you do not need to create an audio player for every command. You can do it once and reuse it

If by other one you mean old project then maybe. My project file is written for my environment so you would need to understand what to swap out.
I think at this rate, you should create an empty sandbox project and in one JS file get the bot to join and play audio as a way to grasp how the new adio system works. Then, you should know enough to be able to translate that to your current project. I am running out of suggestions, so I think from now on the best thing to do is the above with a mix of reading documentation.

https://discordjs.guide/voice/voice-connections.html#playing-audio
https://discordjs.github.io/voice/index.html

In that case my above response applies!

maybe this still const resource = createAudioResource('link or path to file')

as mentioned before there is a hard coded invalid value in there

as a test get any mp3 and put the path to the mp3 in there.

granite geyser

How can I test for the bot and a certain user being in a voice channel together with no other users?

I want the user to be able to disconnect the bot if they are the only one in the vc listening to the bot, even if they don't have the right permissions.

In other words, how do I access the channel of a current connection? I can use the .members property on the channel

quick lantern

i just tried

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

and it gives me this error

TypeError: Cannot read property 'set' of undefined
    at D:\tecno\Documents\code\node\Oneki-bot\node_modules\discord.js\src\structures\Guild.js:1342:34
    at new VoiceConnection (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\VoiceConnection.js:76:25)
    at Object.createVoiceConnection (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\VoiceConnection.js:515:29)
    at joinVoiceChannel (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\joinVoiceChannel.js:18:30)
    at D:\tecno\Documents\code\node\Oneki-bot\js\scripts\util.js:80:53
    at new Promise (<anonymous>)
    at Object.joinVoice (D:\tecno\Documents\code\node\Oneki-bot\js\scripts\util.js:64:16)
    at D:\tecno\Documents\code\node\Oneki-bot\js\commands\play.js:26:93
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Ty
peError: Cannot read property 'set' of undefined".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

any solution?

subtle granite
quick lantern
subtle granite
quick lantern

???

keen sail

Current node-opus package is deprecated?

ripe orchid

yes

olive osprey

Hey, I'm attempting a simple script to record, and then play back voice data from a specific user in a voice channel. The following script records opus packets into the "bufferData" array, however it fails to play it back: ```js
const opusStream = receiver.subscribe("472158867183108118", {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
const bufferData = [];

opusStream.on("data", chunk => {
bufferData.push(chunk);
})
opusStream.on("end", async () => {
var player = createAudioPlayer()
var resource = createAudioResource(bufferData, {type: "opus"})
connection.subscribe(player)
player.play(resource)
})```

keen sail

When I installed @discordjs/opus it logged "Found 1 vulnerabilities, 1 severity" what does this mean

carmine timber
hexed tusk

Hi. Question. I'm using @discordjs/voice and I used joinVoiceChannel for joining the channel. What can I do for leaving the channel? It's my first time using it.

carmine timber
vivid crane

Hey why this error occurs and my bot leaves the voice channel or stop playing the song without leaving the voice channel.

And this happens multiple times

carmine timber
vivid crane

It joins the voice channel and start to play the song but at the middle it suddenly stops playing and when i see console i receive this error

vivid crane
vivid crane

Linux

carmine timber
vivid crane
carmine timber
hexed tusk

Is there a way to play a mp4 in a video o screen sharing by the bot?

vivid crane
hexed tusk

Rip

languid magnet

Why this thing happened
Music stopped in stage but bot is still in stage

slender sparrow

you get ratelimit

carmine timber
languid magnet
carmine timber
dapper helm

anyone know what would cause AudioPlayerError: connect ETIMEDOUT ?

full grove

How can I smoothly transition between audio resources like transitions instead of just cutting between them?

misty tendon

is the only way to leave voice channel destroying connection?

fervent estuary

you can also use connection.disconnect

brisk jasper
const connection = joinVoiceChannel({
            channelId: message.member.voice.channel.id,
            guildId: message.guild.id,
            adapterCreator: message.guild.voiceAdapterCreator
        })
if(video){
            const stream = ytdl(video.url, {filter: 'audioonly'});
            connection.play(stream, {seek: 0, volume: 1})
            .on('finish', ()=>{
                voiceChannel.leave();
            });

            await message.reply(`:youGotThis: Puszczam: ***${video.title}***`);
        }
```Why .play() is not a funcion?
fiery latch

Because the play method does not belong to connection. play() exists on the result of createAudioPlayer()
connection.play() was a thing in V12 but v13 changes it.

jovial mesa

Code

const fs = require("fs")

module.exports.run = async (client, message, args) => {

    const channel = message.member.voice.channel;

    if(!channel) return message.channel.send({ content: '>>> You need to be in a voice channel!' })

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

    if(!args.length) return message.channel.send({ content: ">>> Arguments required!" })

    const connection = getVoiceConnection(message.guild.id)

    files_ = [];
    var files = fs.readdirSync("./songs");
    for (var i in files){
        var name = "./songs" + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }

    console.log(files)

    for(var i = 0; i < files.length; i++)
        if(files[i] == args[0])
            var song = files[i]
    
    const subscription = connection.subscribe(song)

    if(subscription)
        setTimeout(() => subscription.unsubscribe(), 5_000)
}

module.exports.help = {
    name: "play"
}```

Error
```    const subscription = player['subscribe'](this);
                                                ^

TypeError: player.subscribe is not a function```

What does this error mean and how do i fix it?
rugged sky
jovial mesa

ok

ill do that then

near quest

Hello!
Can anyone tell me (or redirect me to a doc that explains it to me) how to know the play-time duration of the currently playing track (for a nowplaying command). Cause I found nothing on discord.guide or discordjs.github.io...
Thx a lot 🙂
||Edit:
Found it: player["_state"].playbackDuration
||

blissful zephyr

is there any package to play spotify tracks (not like play-dl) in a voice channel??

fervent estuary

you cant play songs from spotify directly

you can get metadata tho and use that to search the same song on youtube and play that

azure lagoon

Does anyone recommend any packages for making a musicbot? (Not ytdl since it has alot of issues abborting music)

rugged sky
azure lagoon
solid hemlock

I cant start my bot, because discordjs/voice returns this error. and idk what to do

pls help, because i was waiting the hole day

full grove

try running npm install in the commandline that seems to sometimes work

olive osprey

Hey, I'm attempting a simple script to record, and then play back voice data from a specific user in a voice channel. The following script records opus packets into the "bufferData" array, however it fails to play it back: ```js
const opusStream = receiver.subscribe("472158867183108118", {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});
const bufferData = [];

opusStream.on("data", chunk => {
bufferData.push(chunk);
})
opusStream.on("end", async () => {
var player = createAudioPlayer()
var resource = createAudioResource(bufferData, {type: "opus"})
connection.subscribe(player)
player.play(resource)
})```

full grove
sour citrus

my bot doesn't play the audio resource, why?

royal quail

After trying to install @discordjs/opus

Im using node v16 discord.jsv13 btw

subtle granite

when i say $play likeag6 it comes up with you are not connected to a voice channel but i am connected in a vc

olive osprey
subtle granite
olive osprey
const opusStream = receiver.subscribe("472158867183108118", {
    end: {
      behavior: EndBehaviorType.AfterSilence,
      duration: 100,
    },
  });
  var resource = createAudioResource(opusStream, {inputType: "opus"})
  var player = createAudioPlayer()
  connection.subscribe(player)
  player.play(resource, {seek:0, volume: 1})```
I am planning on making a PA system for Mumble using Discord, however Mumble only accepts raw 16 bit PCM chunks

Not really sure how I can extract the pcm buffer from the opusStream type

royal quail

Since my error deals with discordjs/opus, is there a way to play using an alternative?

subtle granite

I did require('ytdl') but it can't find the module

And I installed the package

olive osprey

Doing this works great: js const opusStream = receiver.subscribe("472158867183108118", { end: { behavior: EndBehaviorType.AfterSilence, duration: 100, }, }); var resource = createAudioResource(opusStream, {inputType: "opus"}) var player = createAudioPlayer() connection.subscribe(player) player.play(resource, {seek:0, volume: 1})
However doing this does not work

  const opusStream = receiver.subscribe("472158867183108118", {
    end: {
      behavior: EndBehaviorType.AfterSilence,
      duration: 100,
    },
  });
  var writable = fs.createWriteStream('test.pcm');
  opusStream.pipe(writable)
  opusStream.on("end", async () => {
    var readable = fs.createReadStream('test.pcm');
    var resource = createAudioResource(readable, {inputType: "opus"})
    var player = createAudioPlayer()
    connection.subscribe(player)
    player.play(resource, {seek:0, volume: 1})
  })```
subtle granite

its saying voiceChannel.join is not a function but i defined it as const voiceChannel = message.member.voice.channel;

sour citrus

my bot doesn't connecting in the voice channel ( ready ), why?

sour citrus
dusty needleBOT

_ Guild#me
The client user as a GuildMember of this guild

carmine timber
solid hemlock
carmine timber

👍

full grove
eager lake

use the voiceStateUpdate event and look if the newState has no channel but the oldState has one.
Then check oldState.channel.members

dusty needleBOT

_ (event) Client#voiceStateUpdate
Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.

eager lake

do you have the proper intents enabled?

also oldstate.channel.members.size will never be null

at least 0

please send the code, I can't see shit with that gif xD

please send the whole event

fierce beacon
PS C:\Users\Timsl\Documents\FarCryDiscordBot> npm i @discordjs/opus
npm ERR! code ENOENT
npm ERR! syscall spawn bash
npm ERR! path C:\Users\Timsl\Documents\FarCryDiscordBot\node_modules\@discordjs\opus
npm ERR! errno -4058
npm ERR! enoent spawn bash ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
``` Anyone know how to fix this error? Im just trying to install discord.js/opus
PS C:\Users\Timsl\Documents\FarCryDiscordBot> npm i @discordjs/opus@latest
npm WARN ERESOLVE overriding peer dependency
npm WARN While resolving: prism-media@1.3.2
npm WARN Found: @discordjs/opus@0.6.0
npm WARN node_modules/@discordjs/opus
npm WARN   @discordjs/opus@"0.6.0" from the root project
npm WARN
npm WARN Could not resolve dependency:
npm WARN peerOptional @discordjs/opus@"^0.5.0" from prism-media@1.3.2
npm WARN node_modules/prism-media
npm WARN   prism-media@"^1.3.1" from @discordjs/voice@0.6.0
npm WARN   node_modules/@discordjs/voice
npm WARN
npm WARN Conflicting peer dependency: @discordjs/opus@0.5.3
npm WARN node_modules/@discordjs/opus
npm WARN   peerOptional @discordjs/opus@"^0.5.0" from prism-media@1.3.2
npm WARN   node_modules/prism-media
npm WARN     prism-media@"^1.3.1" from @discordjs/voice@0.6.0
npm WARN     node_modules/@discordjs/voice
npm ERR! code ENOENT
npm ERR! syscall spawn bash
npm ERR! path C:\Users\Timsl\Documents\FarCryDiscordBot\node_modules\@discordjs\opus
npm ERR! errno -4058
npm ERR! enoent spawn bash ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Timsl\AppData\Local\npm-cache\_logs\2021-10-15T11_37_44_895Z-debug.log
PS C:\Users\Timsl\Documents\FarCryDiscordBot>
echo bone

Is it possible, to call someone private?

eager lake
echo bone

Thx

brisk jasper
const stream = ytdl(song.url, {filter: "audioonly"});
        const resource = createAudioResource(stream);
        player.play(resource);
        song_queue.connection.subscribe(player)
        .on('finish', () => {
            song_queue.songs.shift;
            video_player(guild, song_queue.songs[0]);
        });

player.play(resource).on('finish', () => {
^
TypeError: Cannot read properties of undefined (reading 'on')
Where am I supposed to place .on function to make it work?
What's event for player finishing song

hexed tusk

How can I play a mp3 on my pc using @discordjs/voice? Now I'm using a url.

full grove
brisk jasper

Here is example with mp3 file

eager lake
brisk jasper
const { joinVoiceChannel, createAudioPlayer, createAudioResource} = require('@discordjs/voice') //npm i @discordjs/voice
const player = createAudioPlayer();
cold snow

Hello! I want to make my music bot to play audio form youtube (worked on v12). I managed to make the bot join let connection = joinVoiceChannel({channelId: interaction.member.voice.channel.id, guildId: interaction.member.voice.channel.guild.id, adapterCreator: interaction.member.voice.channel.guild.voiceAdapterCreator}); connection.on(VoiceConnectionStatus.Ready, () => { playMusic(interaction.guild, guildObj, connection); });but I do not understand what is wrong with my playMusic function. I get TypeError: connection.subsribe is not a function.
The playMusic is

const resource = createAudioResource(ytdl(guildObj.music.queue[0], {filter: "audioonly", "quality": "highestaudio"}));
player.play(resource);
connection.subsribe(player);```What am I doing wrong?
cold snow

🤦‍♂️ Have been looking for a mistake for 10 minutes already. Thanks a lot

eager lake

sometimes 4 eyes are better than 2 eyes reallyFckingCuteCatThumbsUp

full grove
brisk jasper

Worked ❤️

const stream = ytdl(song.url, {filter: "audioonly", "quality": "highestaudio"});
        const resource = createAudioResource(stream);
        player.play(resource);
        song_queue.connection.subscribe(player);
        player.on('finish', () => {
            console.log('Song finished');
            song_queue.songs.shift;
            video_player(guild, song_queue.songs[0]);
        });

It seems that 'finish' event doesn't happen even tho a song is finished, why?

eager lake

Dont forget to import the type properly

brisk jasper
eager lake
cold snow

Hello again! I play music like that:

{
    let player = createAudioPlayer();
    let resource = createAudioResource(ytdl(guildObj.music.queue[0], {filter: "audioonly", "quality": "highestaudio"}));
    player.play(resource);
    connection.subscribe(player);
    player.on(AudioPlayerStatus.Idle, () => 
    {
        playMusic(guildObj, connection);
    });
}```1) After a few minutes of a song playing I get `AudioPlayerError: aborted` and the playback stops. What is it caused by?
2) How do I get the `player` from `connection`. I have separate functions for `pause`, `stop` and so on which need to access the `player`. I can get `connection` with `getVoiceConnection(<guild>.id)`. But how do I get `player` from that `connection`?
rugged sky
cold snow

ah... that's weird. It worked well on djsv12. But ok, thanks. I will look into something else. What about the second?

full grove

I would recommend keeping track of the player if that is possible within your architecture it is pretty safe to do so

cold snow

Guess I will have to do so. But I wondered whether there is something like message.guild.voice.connection.dispatcher.pause(true); in v13

mental totem

Is there a way to detect an afk user in VC or at least if they're talking / muted?

olive osprey
carmine timber
slow shuttle

How do I check if an AudioPlayer object is playing?

rugged sky
slow shuttle

thanks

hard haven

Why is this an issue

elder sorrel

What the f**k is this error and WHY It appears?

MinigetError: Status code: 403
    at ClientRequest.<anonymous> (/mnt/c/Users/olegl/GitHub Desktop/ZeroBot-Discord/node_modules/miniget/dist/index.js:210:27)
    at Object.onceWrapper (node:events:514:26)
    at ClientRequest.emit (node:events:394:28)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:621:27)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
    at TLSSocket.socketOnData (node:_http_client:487:22)
    at TLSSocket.emit (node:events:394:28)
    at addChunk (node:internal/streams/readable:312:12)
    at readableAddChunk (node:internal/streams/readable:287:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:226:10) {
  statusCode: 403
}

That thing is annoying! I getting it randomly and I can't debug it!

hard haven

i feel you but for me it's to even connect to the voice channel lol

hard haven
rugged sky
slow shuttle
rugged sky
slow shuttle

If I am using multiple files, how do I create an AudioPlayer in the main one, and use it in a command.js

elder sorrel
rugged sky
eager crag

how to get youtube cookie

elder sorrel
rugged sky

I'm not an expert on the subject though @elder sorrel , I'm sure someone else actually knows what they're talking about when it comes to rate limits.

Not to mention that I could be completely wrong about the whole rate limit thing.

elder sorrel

Ok, thank you. Seems like that problem disappeared after restarting the whole server (lol)

cold snow
carmine timber
rugged sky

Ah right, that's where I went wrong. Thanks for correcting me.

sour citrus

how to set music volume

carmine timber
sour citrus

thx

eager crag
Error: Cannot find module 'node:events'
Require stack:
- /home/runner/I-FUCK/node_modules/discord.js/src/client/BaseClient.js
- /home/runner/I-FUCK/node_modules/discord.js/src/index.js
- /home/runner/I-FUCK/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (/home/runner/I-FUCK/node_modules/discord.js/src/client/BaseClient.js:3:22)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14)
    at Module.require (internal/modules/cjs/loader.js:974:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/runner/I-FUCK/node_modules/discord.js/src/client/BaseClient.js',
    '/home/runner/I-FUCK/node_modules/discord.js/src/index.js',
    '/home/runner/I-FUCK/index.js'
  ]
}

i need help with this error

carmine timber
eager crag
carmine timber
eager crag
dusty needleBOT
cold snow
slow shuttle how exactly?

global.music_subscriptions = new Map();, global.music_subscriptions.set(guildObj.id, subscription);, global.music_subscriptions.get(guildObj.id);.

carmine timber
slow shuttle how exactly?

Leave that method,

Just get connection by getVoiceConnection through discordjs/voice function
and get player by

const player = connection.state.subscription.player
carmine timber
cold snow

Someone has answered me it is not possible.

Have seen your answer now, will try) thanks

carmine timber
slow shuttle
sour citrus
slow shuttle

if (connection.subscription) {return}
why does this line not work?

rugged sky
slow shuttle

Thanks

hexed tusk

Hii. I need help. How can I know if the bot is playing something? Thanks.

hard haven
const resource = createAudioResource(<link_to_audio>, {
  inputType: StreamType.Arbitrary
});
``` that's from the example code given. do i switch `Arbitrary` to `Opus` if im using `@discordjs/opus`? Actually what does `inputType` even mean in this case?
rugged sky
carmine timber
slow shuttle
carmine timber
sour citrus

:1:

dapper helm

yall know what the autopaused status is?

dapper helm
rugged sky

ty 😄 i didnt find that last part about autopaused XD

hard haven
patent forum

How can I get a list of all active voice connections?

ripe nacelle

I used for the adapterCreator in joinVoiceChannel the guild.voiceAdapterCreator now my TS yells at me. What do I need to insert there now?

coral cairn

Hello bretheren. Anyone here familiar with the play-dl package? And how I manage the soundcloud authorization

subtle granite

how do i make my bot join a vc?

I've googled and came up with nothing

rose helm

Is there any update on prism-media's opus encoder memory leak being fixed?

keen flume
rose helm

@vocal valley I do apologize if you dislike pings, but;
#archive-voice message

Afaik, nothing has been said about this ever since the gh issue emerged on the voice repo regarding inlineVolume. I'm curious if this is something that will not be fixed or if there's any ETA or perhaps just even confirmation that this is known about as it is quite detrimental at scale.

sonic bay

is it possible to save a channel permissions in a data base?

cyan pond

Been trying with the https://github.com/discordjs/voice/blob/main/examples/recorder
my code

if (
      interaction.member instanceof GuildMember &&
      interaction.member.voice.channel
    ) {
      const channel = interaction.member.voice.channel;
      let connection = joinVoiceChannel({
        channelId: channel.id,
        guildId: channel.guild.id,
        selfDeaf: false,
        selfMute: true,
        adapterCreator: channel.guild.voiceAdapterCreator,
      });
      try {
        await entersState(connection, VoiceConnectionStatus.Ready, 20e3);
        const receiver = connection.receiver;

        receiver.speaking.on('start', (userId) => {
          console.log('r');
        });
      } catch (error) {
        console.warn(error);
        await interaction.followUp('Failed to join voice channel within 20 seconds, please try again later!');
      }

      await interaction.followUp('Ready!');
    }
``` With this I get an error `AbortError: The operation was aborted
` and timeout. Any ideas?
rose helm

AbortSignals are used in djs when doing anything http related. Either your connection wasn't good enough and took too long to send a request or Discord's servers took too long to respond which sometimes happens considering today was an outage for a good number of large guilds.

cyan pond
peak sapphire

hi! I'm using typescript in my bot. it times out on entersState(subscription.voiceConnection, VoiceConnectionStatus.Ready, 20e3);
here's the code

            if (!subscription) {
                if (interaction.member instanceof GuildMember && interaction.member.voice.channel) {
                    const channel = interaction.member.voice.channel;
                    subscription = new MusicSubscription(
                        joinVoiceChannel({
                            channelId: channel.id,
                            guildId: channel.guild.id,
                            adapterCreator: channel.guild.voiceAdapterCreator as DiscordGatewayAdapterCreator,
                        }),
                    );
                    subscription.voiceConnection.on('error', console.warn);
                    subscriptions.set(interaction.guildId, subscription);
                }
            }
    
            // If there is no subscription, tell the user they need to join a channel.
            if (!subscription) {
                await interaction.followUp('Join a voice channel and then try that again!');
                return;
            }
    
            // Make sure the connection is ready before processing the user's request
            try {
                await entersState(subscription.voiceConnection, VoiceConnectionStatus.Ready, 20e3);
            } catch (error) {
                console.warn(error);
                await interaction.followUp('Failed to join voice channel within 20 seconds, please try again later!');
                return;
            }

adapterCreator has the cast because tsc complained about it being an InternalDiscordGatewayAdapterCreator, I'm not quite sure what I need to do here

peak sapphire

did the trick, thanks man

dapper helm

So over time my bot AudioPlayer gets stuck in the autopaused state is there a way to get it out of that status?

carmine timber
misty sand

how do I connect to a voice channel?

this used to be simple, just <VoiceChannel>.join()

this is urgent, please, I need to make a video about my other bot working but I have no friends to help so im using all my other bots but I cant get them to join the channel to demonstrate (the video is for the bot verification process)

scenic horizon

How to define guild voice region

hard haven

what's the proper way to check if the playback has ended?

vagrant garnet
hard haven
vagrant garnet

if you don't need other states, then use the one i provided

polar mirage

how can i make my bot leave the channel in v13?

hard haven

ok thanks

im pretty sure u just destroy the connection

polar mirage
vagrant garnet

VoiceConnection.destroy()

polar mirage
vagrant garnet

You can store connection when joining the channel

carmine timber
vagrant garnet
dusty needleBOT

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

Documentation suggestion for @mental totem:
_ VoiceState#mute
Whether this member is either self-muted or server-muted

mental totem

So you can't detect an AFK user?

hexed tusk

Is there a way to get the player so I can pause the audio using @discordjs/voice?

dusty zephyr

how to make bot join vc?

hexed tusk
dusty zephyr how to make bot join vc?
const DiscordVoice = require('@discordjs/voice')

DiscordVoice.joinVoiceChannel({
       channelId: message.member.voice.channel,
       guildId: message.guild.id,
       adapterCreator: message.guild.voiceAdapterCreator,
  });```
hexed tusk

Oh you need the library @discordjs/voice

austere kayak

Having a issue. Bot plays first song all good, but when I call a new player.play(RESOURCE) where resource gets made from next song in queue, no sounds comes from the bot. Someone had similar problems? I have tried using player.stop() then in Idle start next song, or just play next song with a skip command (not going into Idle state).

dusty zephyr

and to use voice to record idk wher to start

carmine timber
sonic wraith

Can you somehow check whether user that used a command is in a voice channel on the server said command was used on?

carmine timber
hexed tusk
carmine timber
carmine timber
hexed tusk

Alr one sec

austere kayak
carmine timber
austere kayak

Yes, no problem at all.

carmine timber
hexed tusk
carmine timber Can you console.log(connection.state.subscription) ??
  connection: <ref *1> VoiceConnection {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    debug: null,
    rejoinAttempts: 0,
    receiver: VoiceReceiver {
      voiceConnection: [Circular *1],
      ssrcMap: [SSRCMap],
      speaking: [SpeakingMap],
      subscriptions: Map(0) {},
      connectionData: {},
      onWsPacket: [Function: bound onWsPacket],
      onUdpMessage: [Function: bound onUdpMessage]
    },
    onNetworkingClose: [Function: bound onNetworkingClose],
    onNetworkingStateChange: [Function: bound onNetworkingStateChange],
    onNetworkingError: [Function: bound onNetworkingError],
    onNetworkingDebug: [Function: bound onNetworkingDebug],
    _state: {
      status: 'signalling',
      adapter: [Object],
      subscription: [Circular *2]
    },
    packets: { server: undefined, state: undefined },
    joinConfig: {
      selfDeaf: true,
      selfMute: false,
      group: 'default',
      channelId: '888827503777566814',
      guildId: '888827503777566810',
      adapterCreator: [Function (anonymous)]
    },
    [Symbol(kCapture)]: false
  },
  player: AudioPlayer {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    subscribers: [ [Circular *2] ],
    _state: {
      status: 'buffering',
      resource: [AudioResource],
      onReadableCallback: [Function: onReadableCallback],
      onFailureCallback: [Function: onFailureCallback],
      onStreamError: [Function: onStreamError]
    },
    behaviors: { noSubscriber: 'pause', maxMissedFrames: 5 },
    debug: [Function (anonymous)],
    [Symbol(kCapture)]: false
  }
}```
carmine timber

See player is there, so what's issue now ??

hexed tusk

Basically

hexed tusk
austere kayak

I only create a new AudioPlayer if non exists. If I had multiple, Idle would have been called twice as well when stopping no?

if (!serverQueue.player) {
        console.log("Lager AudioPlayer");
        const player = createAudioPlayer();

        //Connection Ready
        serverQueue.connection.on(VoiceConnectionStatus.Ready, () => {
            console.log(
                "Kobling er satt til 'Ready' - klar for å spille musikk!"
            );
            const subscription = serverQueue.connection.subscribe(
                player
            );

            player.play(resource);
            serverQueue.player = player; 
        });
carmine timber
mental totem
carmine timber
austere kayak
carmine timber
hexed tusk
carmine timber
austere kayak
carmine timber What kind of resource you are playing ??

Using discord-ytdl-core if thats what you thinking about?

    const stream = ytdl(song.url, {
        filter: "audioonly",
        opusEncoded: true,
        encoderArgs: encoderArgstoset,
        bitrate: 320,
        quality: "highestaudio",
        liveBuffer: 40000,
        highWaterMark: 1 << 32,
                inlineVolume: true 
    });
    const resource = createAudioResource(stream);
carmine timber
hexed tusk
carmine timber

Oh okay no issues 👍

hexed tusk
austere kayak
granite geyser

Hi, I have a voice recorder set up to end on silence. When it ends, I process the recording and all that and start listening again. If a certain word is said, I listen for commands. However, there’s a problem.
Imagine this scenario:
A user says the bots wake word, and is then silent.
The bot is listening for commands now.
The users mic activates for a second due to background noise
My bot tries to process that as a command, gets nothing, let’s the user know and the user is confused.
Is there any way to combat this? Set a minimum audio time before listening for the silence timeout?

carmine timber
austere kayak
carmine timber Can you show me player-idle event code ??
player.on(AudioPlayerStatus.Idle, () => {
            if (serverQueue.connection) {
                if (serverQueue.songs.length > 0) {
                    if (serverQueue.loop) {
                        let lastSong = serverQueue.songs.shift();
                        serverQueue.songs.push(lastSong);
                        player.play(getResource(serverQueue.songs[0], serverQueue, serverQueue.filter));
                    } else if (serverQueue.songloop) {
                        player.play(getResource(serverQueue.songs[0], serverQueue, serverQueue.filter));
                    } else {
                        console.log("LOOOOP") //Where i get to when using player.stop().
                        serverQueue.songs.shift();
                        player.play(getResource(serverQueue.songs[0], serverQueue, serverQueue.filter));
                    }
                }
            } else {
                try {
                    serverQueue.connection.destroy();
                } catch (e) {
                    console.log(String(e).grey);
                }
                serverQueue.connection.disconnect();
                client.queue.delete(message.guild.id);
                return serverQueue.textChannel.send(`**Køen er tom!**`); 
            }
        }); 
carmine timber
austere kayak
carmine timber
austere kayak
austere kayak
player.on("error", (error) => {
            console.error(`Error: ${error.message} with resource ${error}`);
            serverQueue.songs.shift();
            if(!serverQueue.songs[0]){
                try {
                    serverQueue.connection.destroy();
                } catch (e) {
                    console.log(String(e).grey);
                }
                return client.queue.delete(message.guild.id); 
            }
            player.play(getResource(serverQueue.songs[0], serverQueue, serverQueue.filter));
        });

Already do 😦

austere kayak
cobalt jolt

what's the problem here?

teal sandal

is there a way to seek the audioPlayer? 🔵

can someone help me myb?

cobalt jolt

idk why it happens but it does

near quest
carmine timber
carmine timber
near quest

@carmine timber

(it's just a private method but it exists)

near quest
dusty zephyr

"slayer_bosses":{"spider":{"claimed_levels":{"level_1":true,"level_2":true,"level_3":true},"boss_kills_tier_0":1,"xp":1130,"boss_kills_tier_1":1,"boss_kills_tier_2":9},"wolf":{"claimed_levels":{"level_1":true,"level_2":true},"boss_kills_tier_0":1,"xp":630,"boss_kills_tier_1":1,"boss_kills_tier_2":1,"boss_kills_tier_3":1},"zombie":{"claimed_levels":{"level_1":true,"level_2":true,"level_3":true,"level_4":true}
what would be the best way to check what level is the last true?

is the only way checking every single level to see if its true?

coral cairn

Quick question: say I want to create a skip song command in a separate file than where I have my current player functionality. Is it possible to access the player from a different file with some kind of function (like getVoiceConnection)?

sour citrus

not playing, help me

sinful plover

TypeError: player.subscribe is not a function

how come this is happening? im tryingto subscribe to a connection

dapper helm
dapper helm
unreal arch
night wren

I have searched but I don't find why I have AbortError: The operation was aborted

Oh I probably find I will try

echo arch

I doubt it, but is it possible to call someone in a dm?

subtle granite

no

celest dawn

is there a way to play multiple streams to an audio player?

celest dawn

switching back to v12, this sucks

echo arch

Ah ok thx djoh

jovial mesa

how do u make it so if a song has finished it does something like remove the song out of the queue / list

rugged sky
jovial mesa

ok thx

carmine timber

You probably using entersState, It has some issues.

mild swan
sudden wharf

anyone knows this error

split cliff
      throw er; // Unhandled 'error' event
      ^

AudioPlayerError: aborted```

Getting this error whenever I try to play music... does anyone know a fix?
sleek cradle

can somebody help me make a music bot with replit or autocode

cobalt jolt

This code doesn't work properly but there's any error messages

(btw, this.song(music).file is a .mp3 file in the same folder)

sudden wharf

Hey can anyone give me lyrics.Js code for v 13….pls

full grove
sonic bay

How do i wait until everyone leaves the voice channel to delete it? Because it only deletes if the last person leaving is the person who created the voice channel

const { Collection } = require("discord.js");
const voiceCollection = new Collection();

module.exports = async (Discord, client, oldState, newState) => {
  const user = await client.users.fetch(newState.id);
  const member = newState.guild.member(user);

  // JOIN
    if (!oldState.channel && newState.channelID === "899361398654640179") {
      const channel = await newState.guild.channels.create(user.tag, {
        type: "voice",
        parent: newState.channel.parent,
      });
      member.voice.setChannel(channel);
      voiceCollection.set(user.id, channel.id);
      await channel.overwritePermissions([
        {
          id: user.id,
          allow: ["MANAGE_CHANNELS", "CONNECT"],
        },
        {
          id: member.guild.id,
          deny: ["CONNECT"],
        },
      ]);
    } else if (!newState.channel) {
      if (oldState.channelID === voiceCollection.get(newState.id)) {
        if (oldState.channel.members.size < 1) {
        return oldState.channel.delete();
       }
     }
    }```
hexed tusk

Hello. So my bot can play youtube audios, but after 40 seconds it stops with an error. The error is:

      throw er; // Unhandled 'error' event
AudioPlayerError: aborted
Emitted 'error' event on AudioPlayer instance at:
    at OggDemuxer.onStreamError ```

What can I do? Thanks.
full grove
hexed tusk
full grove
bold furnace

hi, how can I just destroy the audioplayer that it wont emit any event enymore?

hexed tusk
mild swan

TypeError: stream.once is not a function ??
const stream = process.stdio;

const process = raw(
                this.url,
                {
                    o: '-',
                    q: '',
                    f: 'bestaudio[ext=webm+acodec=opus+asr=48000]/bestaudio',
                    r: '100K',
                },
                { stdio: ['ignore', 'pipe', 'ignore'] },
            );
serene meadow

How to kick people from voice channel?

quick lantern

i just tried

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

and it gives me this error

D:\tecno\Documents\code\node\Oneki-bot\node_modules\discord.js\src\structures\Guild.js:1342
      this.client.voice.adapters.set(this.id, methods);
                                 ^

TypeError: Cannot read property 'set' of undefined
    at D:\tecno\Documents\code\node\Oneki-bot\node_modules\discord.js\src\structures\Guild.js:1342:34
    at new VoiceConnection (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\VoiceConnection.js:76:25)
    at Object.createVoiceConnection (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\VoiceConnection.js:515:29)
    at joinVoiceChannel (D:\tecno\Documents\code\node\Oneki-bot\node_modules\@discordjs\voice\dist\joinVoiceChannel.js:18:30)
    at Join.run (D:\tecno\Documents\code\node\Oneki-bot\js\commands\join.js:20:33)
    at D:\tecno\Documents\code\node\Oneki-bot\js\events\command.js:10:25
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

any solution?
I used @discordjs/voice v0.6.0 & discord.js v13.2.0

mild swan

Error:

Error: Cannot play audio as no valid encryption package is installed.
- Install sodium, libsodium-wrappers, or tweetnacl.
- Use the generateDependencyReport() function for more information.

And if use generateDependencyReport()
Return:

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

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

Encryption Libraries
- sodium: 3.0.2
- libsodium-wrappers: not found
- tweetnacl: not found

FFmpeg
- version: 4.3.1-full_build-www.gyan.dev
- libopus: yes
--------------------------------------------------
austere sphinx

How would a bot set itself as a speaker in a stage channel?

oh nvm

dusty needleBOT

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

quick lantern
carmine timber
quick lantern

Let me...

carmine timber
carmine timber
dusty needleBOT

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

carmine timber

Get size of above for checking no of users in that channel

quick lantern

I tried but it show me same error

carmine timber
quick lantern
ripe orchid

are you overwriting client.voice

quick lantern

No

ripe orchid

show ur code

ripe orchid

the whole file not just that

quick lantern
ripe orchid

can i see ur index

carmine timber
quick lantern

create a new folder and then run these commands :

npm init -y
npm install discord.js
npm install @discordjs/voice

And copy your codes to that folder.

quick lantern
ripe orchid

client.voice = new Collection(); youre overwriting client.voice

carmine timber
quick lantern

I work as a team, i had not noticed that change

Jeje tnx for the help, i had been programming for hours

jovial mesa

I've got a raspberry pi 4 and i am trying to make a bot that has downloaded songs (non copyright ofc). and its not playing music. did i do something wrong?

that is the part that needs to play music but it doesn't work

rugged sky
jovial mesa

i now get this error
Error: Cannot play audio as no valid encryption package is installed.

rugged sky
jovial mesa

thx now the bot is playing music :)

sudden wharf

hey anybody knows this error i was using genius api for my lyrics cmd

rugged sky

This is for discordjs questions. I'd recommend asking in a genius community.

tired basin
bold furnace

hi, how can I just destroy the audioplayer that it wont emit any event enymore?

dapper helm

are voiceconnections suppose to get destroyed after 2 hours?
mine keeps getting destroy on the 2 hour mark

mild swan

Why sometimes audioPlayer.on('error') return Error: aborted
And if i try again with same video no return error ???

subtle granite

how can i use the @discordjs/voice package to disconnect the bot from a channel

night wren

Do you know how to add filter on the music ?

muted pebble

Is there any way to capture audio from a voice channel? I know there was a way in v12 and hopefully something like that was kept in v13.

rugged sky
rugged sky
muted pebble

That's what I thought, but there's nothing in the guide. I don't know where to look in the docs.

subtle granite
subtle granite

Hey im having this problem that doesnt make any sense, can someone help me out ?

note above is my code for playing audio stream

gentle bluff
const connection = joinVoiceChannel({
  channelId: channel.id,
  guildId: message.member.guild.id,
  adapterCreator: message.member.guild.voiceAdapterCreator,
});
                        
const subscription = connection.subscribe(player);

const { createAudioResource, StreamType } = require('@discordjs/voice');
  const resource = createAudioResource(`/sounds/happy/${happySoundsRandom}`);
  player.play(resource);
}

What am I missing here? my bot wont connect to voice channel.

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

Fix??

subtle granite

uhhhh idk how to say this but how can you prevent your bot from playing musisc accross different servers ???

like it plays music for sure but same song in multiple servers in a row ???

how to fix that even

gentle bluff
subtle granite
gentle bluff

possibly

rugged sky
rapid rain

this is actually quite irritating.

i have this simple if-statement set up like so:

if (!interaction.member.voice.channel) {
      return interaction.followUp({ content: 'You need to be in a voice channel.' });
    };

i am in a voice channel and the bot has full permissions so obviously the bot would know, but no matter if i am in a voice channel or not, it still sends this interaction message. i am quite lost.

rugged sky
rapid rain
rugged sky

In your joinVoiceChannel(...) the id properties have to be Strings, not integers.

What you put is fine, just make it Strings instead of ints.

Just put quotation marks around it.

Yeah, if I may give some unsolicited advise: Codecademy offers some great courses including on javascript that can get you acquainted with the language and programming before undertaking more complicated projects.

You don't have to use the connection object. Just creating it is enough to make the bot join. Are you sure you are providing the right ids?

I'd recommend changing it to this and trying again:

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

This does require you to be in the channel you want it to join.

No, a Guild is a discord server.

Also, make sure you have the GUILD_VOICE_STATES intent.

Looks like you still need to subscribe your connection to the player like so: connection.subscribe(player). This just tells your connection to output whatever your player is playing.

Yeah, at any point when both those variables exist.

No, since you create the player variable only after that so it doesn't know what player is yet. Just put it on like line 62 or something.

odd ocean
data.connection.play(stream, {
                            volume: 0.9
                        });
//this is in my code in one location, when ran it plays a stream, but no audio can be heard.
//this is in another location, it plays an audio file. this can be heard with ease.
dpat = connection.play(scat, {
                        volume: 0.9
                    });```
rugged sky

You need to actually input some audio resource into the createAudioResource(...) function. Right now you just have a placeholder String. Your code is a bit messy since it has a bunch of v12 stuff in there as well. I'd recommend you remove the entire if statement that is above the joinVoiceChannel() stuff and just replace it with this one line: const stream = ytdl(args[0], {filter: 'audioonly'});. Then you change the audio resource line to const resource = createAudioResource(stream).

odd ocean

what do you mean? I dont want to play the audio file. i want to play the stream

oh you thought i was helping you. That was an issue I was having.

rugged sky
odd ocean

so its because its deprecated, thats why. im on 13 and in the process of updating some code i wrote years ago

then, mid-update discord went from 12-13

rugged sky
odd ocean
rugged sky

Could you elaborate on what you mean?

rugged sky
odd ocean

im not sure, i could check but at this point im just going to rewrite everything from scratch in v13 and hope its stable for a month at least

rugged sky

You can put a path to an audio file that is on your computer in there or you can provide it with a stream like I did in my example.

rugged sky

Yeah, so just follow what I said here:
I'd recommend you remove the entire if statement that is above the joinVoiceChannel() stuff and just replace it with this one line: const stream = ytdl(args[0], {filter: 'audioonly'});. Then you change the audio resource line to const resource = createAudioResource(stream).

No, remove this part:

if(validURL(args[0])){ 
  const  connection = voiceChannel.join();
  const stream  = ytdl(args[0], {filter: 'audioonly'});
 
  connection.play(stream, {seek: 0, volume: 1})
  .on('finish', () =>{
  channel.leave();
  message.channel.send('leaving channel');
  });
 
  await message.reply(`:thumbsup: Now Playing ***Your Link!***`)

  return
}

And just leave this in it's place:

const stream  = ytdl(args[0], {filter: 'audioonly'})

And then you change this:

const resource = createAudioResource('link or path to file')

to this:

const resource = createAudioResource(stream)

By the way, can you link the tutorial/guide that you used? I've seen this before and people had the same issues as you.

Can you show the full error? And what is args[0] I assumed that's just a url that you input?

Yeah, so the way it's set up now is it can only handle URL's. So you would have to say "!play <your url here>" instead. You can use something like youtube-search I think to search a youtube video based on search terms, but I'd recommend getting this to work with URLs first before moving on.

Yeah, the bot is just deafened by default to save resources, it doesn't need to hear anything to play.

Can you try changing this:

if(video){
            const player = createAudioPlayer();
            const resource = createAudioResource(stream)
                player.on('idle', () => {
            });
 
            await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
        } else {
            message.channel.send('No video results found');
        }

To this:

            const player = createAudioPlayer();
            const resource = createAudioResource(stream)
                player.on('idle', () => {
            });
 
            await message.reply(`:thumbsup: Now Playing ***${video.title}***`)

Oh, I'm dumb, didn't even see this. You never call the .play() method to start playing the resource haha. Just add this: player.play(resource)
directly after the const resource = createAudioResource(stream) line.

Oh did you remove the .subscribe() line at any point? I can't see it in there. I may have forgotten to add it into one of my code blocks. Just put that back in like you did before.

Big! To error handle that I'd probably just take it the simple route and change this:

 const validURL = (str) =>{
        var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
        if(!regex.test(str)){
            return false; 
        } else {
            return true;
        }
    }
 
    const stream  = ytdl(args[0], {filter: 'audioonly'});

To this:

if(!args[0].startsWith("https://www.youtube.com/watch?v=")) {
    return message.reply({content: "Not a valid youtube url", ephemeral: true})
}

const stream  = ytdl(args[0], {filter: 'audioonly'})

if(!stream){
    return message.reply({content: "Couldn't finde youtube video", ephemeral: true})
}

That just checks if the URL is a youtube video before trying to find it, and after searching for it with ytdl it just makes sure it has got it.

Great, glad it works. Imma head off to bed now haha. Good luck with the rest of your dev!

snow nova

does djs/voice let you play any music file? can it play spotify urls?

youtube is not letting you use it will they let you if you keep your bot non-premium?

hard escarp

Is there any way to adjust the volume of the bot (before playing the resource) without using inlineVolume

odd ocean

not that ive found

Is there an event that fires when a stream ends?

carmine timber
odd ocean

thank you

odd ocean

is there a way to query the current state of the player?

(isPlaying or smth)

carmine timber
odd ocean

Thank you again, where are you getting these? I cant find docs

odd ocean

amazing

thank you

iron flume

I think it's voiceChannel.destroy()

At least in v13 it is

carmine timber

There is no property like VoiceChannel.destroy()

ember estuary

humm how fix this erro ? I can't play music ples help me

(node:1480) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1480) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time
slender sparrow

that just a warning, please read clearly

carmine timber
gentle bluff

i already got it fixed... kinda

it wont play any audio tho :/

carmine timber
gentle bluff

yeah

carmine timber
gentle bluff
var happySoundsRandom = happySounds[Math.floor(Math.random()*happySounds.length)];

                    const player = discordVoice.createAudioPlayer();
                    const resource = discordVoice.createAudioResource(`/sounds/happy/${happySoundsRandom}`);
                    
                    const connection = discordVoice.joinVoiceChannel({
                        channelId: message.member.voice.channel.id,
                        guildId: message.guild.id,
                        adapterCreator: message.guild.voiceAdapterCreator
                    });
                        
                    player.play(resource);
                    connection.subscribe(player);
carmine timber
gentle bluff

absolute?

gentle bluff

eyyyy it works, thanks

gentle bluff

Weird question but is it possible to "undeafen" the bot?

other than by possibly creating a recording thing of somesort

carmine timber
gentle bluff
sturdy sail
                    .then(conn => {
                        const dispatcher = conn.play(__dirname + 'beep.mp3');
                        dispatcher.on('finish', () => { console.log(`Joined ${channel.name}!\n\nREADY TO RECORD\n`); });
                        
                        const receiver = conn.receiver;
                        conn.on('speaking', (user, speaking) => {
                            if (speaking) {
                                const pathToFile =`${Date.now()}.pcm`;
                                const pathToFile2 =`${Date.now()}.mp3`;
                                console.log(`${user.username} started speaking`);
                                const audioStream = receiver.createStream(user, { mode: 'pcm' });
                                audioStream.pipe(createNewChunk(pathToFile));
                                audioStream.on('end', () => { 
                                    
                                const cmd = 'ffmpeg -i ' + pathToFile + ' ' + pathToFile2;
                                exec(cmd, (error, stdout, stderr) => {
                                    if (error) {
                                        console.log(`error: ${error.message}`);
                                        return;
                                    }
                                    if (stderr) {
                                        console.log(`stderr: ${stderr}`);
                                        return;
                                    }
                                    console.log(`stdout: ${stdout}`);
                                });
            
                                    console.log(`${channel.username} stopped speaking`); });
                            }
                        });
                    })``` i'm trying to record audio and then change the file to mp3, but im getting always correupt input packet in ffmpeg also the .pcm file isnt playing anything
tulip oracle

is there a way to stream something via my bot?

sturdy sail

also if i try to use the example code i get this error ```const opusStream = receiver.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
});

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

const filename = `./recordings/${Date.now()}.ogg`;

const out = createWriteStream(filename);

console.log(`👂 Started recording ${filename}`);

pipeline(opusStream, oggStream, out, (err) => {
    if (err) {
        console.warn(`❌ Error recording file ${filename} - ${err.message}`);
    } else {
        console.log(`✅ Recorded ${filename}`);
    }
});```

Unhandled promise rejection: Error: Cannot find module 'node-crc'

dusty needleBOT

If you aren't getting any errors, try to place console.log checkpoints throughout your code to find out where execution stops.
• Once you do, log relevant values and if-conditions
• More sophisticated debugging methods are breakpoints and runtime inspections: learn more

sturdy sail

after installing node-crc i get this error

leaden totem

Hello! When i write this:

let conn = await voice.joinVoiceChannel({
            channelId: voiceChannel.id,
            guildId: message.guild.id,
            adapterCreator: message.guild.voiceAdapterCreator,
            selfDeaf: false,
            selfMute: false
        })
await conn.play(....)

the bot join the voice channel, with no errors, but the it gives at conn.play() "play is not a function"

solemn current
silver galleon

I'm having issues setting the volume of a resource.
I have inlineVolume set to true

DiscordjsVoice.createAudioResource(url, {
                inputType: DiscordjsVoice.StreamType.Arbitrary,
                inlineVolume: true,
                metadata: { url }
            });

Then in a different file - I access the resource by reading the resource property of the state of the audioplayer

console.log(volume, player.state.resource.volume);
        player.state.resource.volume = volume;
        console.log(volume, player.state.resource.volume);

volume = target volume

before, it logs 10 100 then 10 10 but I hear no difference.
Accessing the volume again shows it's set to 10, but no difference in the audio level can be heard.

odd ocean

So i have the audio player etc working perfectly

but id like to access player from another file basically, i get an error if i map it to a global variable. Can you give me some advice?

subtle granite
                       ^

TypeError: leaveVoiceChannel is not a function```
 is it something different than leave? my join one works
odd ocean

connection.destroy()

subtle granite
odd ocean

Then how are you in a voice channel?

subtle granite
odd ocean

idk what it is youre doing

you need to join the voice channel (or else, you wont be in the voice channel) then destroy that connection.

fervent estuary

Youre passing an invalid url to ytdl()

You should check for it before calling that

leaden totem

Hello! How can i leave a voice channel? I'm searching a lot but i cannot find anything. I tried with connection.destroy() but it doesn't work (for because i've commands in different files). How can i do? The bot after finishing playing sound does not leave alone the channel

fervent estuary

Exactly

tawdry halo

anyone know whats going on here? Every once in awhile it aborts.

                try {
                    await entersState(subscription.voiceConnection, VoiceConnectionStatus.Ready, 20e3);
                }
                catch (error) {
                    console.warn(error);
                    await interaction.followUp('Failed to join voice channel within 20 seconds, please try again later!');
                    return;
                }

AbortError: The operation was aborted
code: 'ABORT_ERR'

carmine timber
lofty warren

everything in voice changed in 13.0, is there any guide about how to use that?

fiery pond

why discord/voice cant play full song it play only 15-30 secons song

icy maple
fiery pond

it playing but not full

icy maple

Then it’s most likely an issue with ur code or internet

tawdry halo
fiery pond
icy maple

Or ur only getting 15s of a song

fiery pond
carmine timber
carmine timber
tawdry halo

oooh, that's unfortunate. so just something with have to deal with?

fiery pond
icy maple

That would make sense

carmine timber

Yep but it is difficult to catch that signal

icy maple

I can’t reliably get that error without letting my laptop go to sleep

fiery pond
icy maple
carmine timber

Spotify links are hard to play due to their DRM layer.

fiery pond

does discord/voice support links ?

tawdry halo

discord/voice itself wont

fiery pond
icy maple

That’s what she said

tawdry halo

you have to use a module

fiery pond
carmine timber
fiery pond
tawdry halo

just use some sort of youtube module. forget about trying to stream from spotify

fiery pond

i know how to make bot like hydra but i need only thing which play spotify tracks

slender sparrow

no one can stream from spotify, they just resolve to other source

sturdy sail

when i try to use the example code i get this error (the bot runs on Windows WSL - Ubuntu)

const opusStream = receiver.subscribe(userId, {
        end: {
            behavior: EndBehaviorType.AfterSilence,
            duration: 100,
        },
    });

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

    const filename = `./recordings/${Date.now()}.ogg`;

    const out = createWriteStream(filename);

    console.log(`👂 Started recording ${filename}`);

    pipeline(opusStream, oggStream, out, (err) => {
        if (err) {
            console.warn(`❌ Error recording file ${filename} - ${err.message}`);
        } else {
            console.log(`✅ Recorded ${filename}`);
        }
    });```
sturdy sail

also if i try this ```ts
const connection = await channel.join()
const receiver = connection.receiver
const userStream = receiver.createStream(author, {mode:'pcm', end: 'silence'})
const writeStream = fs.createWriteStream('recording.pcm', {})

                    const buffer = []
                    userStream.on('data', (chunk) => {
                        buffer.push(chunk)
                        console.log(chunk)
                        userStream.pipe(writeStream)
                    });
                    writeStream.on('pipe', console.log)
                    userStream.on('finish', () => {
                        channel.leave()
                        const cmd = 'ffmpeg -i recording.pcm recording.wav';
                        exec(cmd, (error, stdout, stderr) => {
                            if (error) {
                                console.log(`error: ${error.message}`);
                                return;
                            }
                            if (stderr) {
                                console.log(`stderr: ${stderr}`);
                                return;
                            }
                            console.log(`stdout: ${stdout}`);
                        });
                    });```

the output .pcm file cant be played and after using ffmpeg the wav file is 10x size and it only has white noise

summer crow
sturdy sail

oh i see, thank you

jovial mesa

whoops wrong guild

bright cove

Im in a voice channel and if i try interaction.member.voice.channelId it returns null, but if i restart the bot it returns the voice channel id, and if i leave it still returning the voice channel id, why???!!

nvm, missing intents

silver galleon

Setting player.state.resource.volume doesn't seem to change the volume.
I have inlineVolume set to true in createAudioResource

DiscordjsVoice.createAudioResource(url, {
                inputType: DiscordjsVoice.StreamType.Arbitrary,
                inlineVolume: true,
                metadata: { url }
            });

// ... (in another file) ...
player.state.resource.volume = volume;

I've set the volume to 100 and 10 and hear no differences.

full grove
silver galleon
full grove
silver galleon

idk how i managed to miss that

surreal depot

err stream destroyed isnt a valid case, anyone help?

cyan pond

I wanted to record 2-5 users in a voice chat, this lead me into two questions:

  • One: Should I create a pipe when they start talking and destory it when they stop? Or should I start and keep the pipes active all the time?
  • Two: What should I try to do to pass the data into an audio file? I can get the audio from reciver.subscribe or reciver.speaking.on('data' () => {}) so what would be best?
dense vault

Hey so I'm using discord.js/voice and I created an audio resource to play a file and then I set an interval to print debugging information and the bot is able to join a channel, and the audio resource's status is playing but there's no green circle and it's not actually playing any audio. I tried multiple different audio formats. I have ffmpeg installed globally. Is there any way to get more information for debugging purposes? Any tips?

Ah, I needed to add Intents.FLAGS.GUILD_VOICE_STATES

Fixed!

quick lantern

Error: Cannot play a resource that has already ended.
How can I replay an audio that has been played?

icy maple
crude parcel

Are there any viable sources for popular music other than ytdl/youtube? Anyone had luck elsewhere?

icy maple

I heard of play-dl, never actually used it tho

quick lantern
crude parcel

Ty:)

crude parcel

Would using createAudioResource#inlineVolume pretty much nullify the improvement in performance gained by specificying input type? (createAudioResource#inputType: StreamType.WebmOpus) - since the resource ends up piping through FFmpeg anyway?

crude parcel

Cheers :)

meager panther

Hey Guys
pause and resume commands aren't working for me is there anyway to fix it?

icy maple
meager panther
icy maple

Then it’s prob not running

meager panther

pause is working but resume doesn't work until i use pause again

icy maple

Prob got some spaghetti code then

meager panther
icy maple

Bruh, that issue is for v12

meager panther

i am using v12

icy maple

The fix was stated in that issue tho

I doubt the native v12 voice is gonna get updated tho

meager panther

If i update to v13 then i need to make some changes

Is v13 good ?

icy maple

It’s depends on what you define as "good"

Most ppl who hate it are those who either don’t like to update code (even tho that’s what software development is), or prefer to stick to using bad practices bc it’s easier

meager panther

What is the new version of discord.js now?

icy maple

Latest rn is 13.2.0

meager panther

Ok i will update my code then

leaden totem

Hello! Is there a way to handle the audioplayer finish event? For example when it ends the song/audio in order to run the next audio (for example stored in a map)?

icy maple

The player will emit idle

leaden totem

but it emits idle also if the audio is stopped manually. Or Also if it's created and nothing is runned on it. It emits idle the same

icy maple

The last one is false

It does not emit when created

It only emits it becomes idle (from a different state)

leaden totem

in the previous version (when there is not the voice package) ther is the .play(audio).on('finish',....). I'm searching something like that.

icy maple

Well, ur not gonna find anything

leaden totem

ok. so i need to work with the idle event tho?

icy maple

Yes

leaden totem

So if i detach a connection, it should not emit idle anymore right?

icy maple

That’s not the case

The idle listener will still be attached to the player regardless of the connection

No, that’s that a different event

unsubscribe is a different event. But connections don’t affect player events

leaden totem

ok....but so how can i recognize if the audio is finished or stopped? I've to register also my commands?
(my intent is to make an audio map as queue, if i send a stop command, it stops playing, if i skip/or audio finish, it continues with the audios queue).

icy maple

Wouldn’t that be the same thing?

If it finishes, it shifts the queue and continues. If you stop it. It does the same thing

If you want it kill it, clear the queue before stopping. If you don’t want to clear the queue, pause it

leaden totem

oh you right, it changes only that in 1 case it run the next audio, in the other it only shifts

leaden totem

Is there an other way to check the emit event? I've to check it into an asynchronous function and when it emits the idle i've to recursive call that function. But it works only 1 times. If it emits more then 1 time it doesn't work

fading sonnet

Is anybody familiar with speech recognition stuff? I m trying to add feature to my bot which can join vcs and talk to people. Like siri and google assistant. Right now, I have figured out ai chat using swagger ui and it can speak out the output(response) in a vc but you have to type in a channel for a response. (I m using tts for that. The message is sent to a private channel and the tts will read the response)

In short, what I m trying say is: Is anybody familiar with speech recognition? Like, converting speech to text or something like that!

subtle granite

Anyone got the route from posting self deafening a bot?

quasi wraith

Are there any current problems with playing sound in a voice channel? My bot joins the voice channel, lights green, but has no sound. Yesterday everything worked fine.

I have created a simple test bot and it is the same. He joins the voice channel, lights green, but has no sound.

const { Client, Intents } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
const { token, channelId, guildId } = require('./config.json');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_VOICE_STATES] });

client.once('ready', () => {
    console.log('Ready!');
});

client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    const { commandName } = interaction;

    if (commandName === 'ping') {

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

        const audioPlayer = createAudioPlayer();

        const resource = createAudioResource('sound.mp3');
        audioPlayer.play(resource);

        connection.subscribe(audioPlayer);

        await interaction.reply('Pong!');

    }
});

client.login(token);
jovial mesa

ofc import is aswell

quasi wraith

Unfortunately this has not solved the problem. The connection variable is still the VoiceConnection and it also shows in Discord that the bot is talking, but you can't hear anything.

honest shuttle

In your case that would be something like createAudioResource(fs.createReadStream('sound.mp3'))

After ofc importing fs (no download required, it is integrated into node)

quasi wraith

Does not work either. Same result. It shows in Discord that the bot is talking, but you can't hear anything.
My current test code:

const { Client, Intents } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, getVoiceConnection } = require('@discordjs/voice');
const { token, channelId, guildId } = require('./config.json');
const fs = require('fs')

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_VOICE_STATES] });

client.once('ready', () => {
    console.log('Ready!');
});

client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    const { commandName } = interaction;

    if (commandName === 'ping') {

        joinVoiceChannel({
            channelId: channelId,
            guildId: guildId,
            adapterCreator: interaction.member.guild.voiceAdapterCreator,
        });

        const connection = getVoiceConnection(guildId);

        const audioPlayer = createAudioPlayer();

        const resource = createAudioResource(fs.createReadStream('sound.mp3'));
        audioPlayer.play(resource);

        connection.subscribe(audioPlayer);

        await interaction.reply('Pong!');

    }
});

client.login(token);
quasi wraith

Sorry guys. Everything works again. The standard input output devices did not work anymore. I just had to change the settings from default to some other device. There was nothing wrong with the code from the very beginning. Only the discord settings were the problem.

fiery hearth

Hey! Is there a way to make a bot join a stage voice channel in discord.js? I’ve looked through the docs and havent found anything yet 😅

fading sonnet

I don't think it supports stage channels right now, maybe later they may provide an update or something. Even I have been trying for the same

ripe orchid

you would join it the same way you would a regular voice channel

summer crow
crimson crane

hey, so i'm trying to make my bot join a vc and play a locally saved mp3 file, and i've looked through the docs n stuff, and turned for this to be my script:

                    vc.join().then(async (connection) => {
                        console.log("connection"); console.log(connection)
                        const { VoiceConnectionStatus, createAudioResource, createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice');

                        const player = await createAudioPlayer({
                            behaviors: {
                                noSubscriber: NoSubscriberBehavior.Pause,
                            },
                        })
                        console.log("player created")

                        const resource = await createAudioResource('./musicfiles/Bastille_Pompeii.mp3', {
                            metadata: {
                                title: 'A good song!',
                            },
                        })
                        console.log("recourse created")

                        player.play(resource)
                        connection.subscribe(player)
                        console.log(VoiceConnectionStatus)
                        player.on('error', error => {
                            // console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`)
                            // player.play(getNextResource())
                        })
                    })

But it complains that connection.subscribe isn't a function, is this an error on my side? and if so, how should i do it otherwise?

crimson crane
carmine timber
crimson crane

v13

i'll assume that the connection param is just invalid from that method then

carmine timber
crimson crane
carmine timber
crimson crane

yeah i'll assume that it just joins and gives wrong arg

crimson crane

vsc complaining about an error inside the discordjs/voice module

when i did the following:

                    const connection = joinVoiceChannel({
                        channelId: vc.id,
                        guildId: vc.guild.id,
                        adapterCreator: vc.guild.voiceAdapterCreator,
                    })
carmine timber
crimson crane

"TypeError: adapterCreator is not a function"

carmine timber
crimson crane

ok

                const { voice } = msg.member

                if (voice.channelID) {
                    const vc = voice.channel
                    // console.log(channel)

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


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


icy maple
crimson crane

ok

icy maple

Sidenote, its <VoiceState>.channelId (small d)

crimson crane

Voicestate?

icy maple

Yes

carmine timber
crimson crane
icy maple

Make sure ur running npm ls discord.js in ur project directory

crimson crane

yeah the complete bot works, just not the vc part

icy maple

Do npm ls discord.js in the project directory

carmine timber
icy maple

Why init?

icy maple

That's the User directory

crimson crane

oh wait the project directory

icy maple

macci@ /Users/macci

You shouldn't have anything installed there in the first place

crimson crane
icy maple

/Js/CBot

crimson crane

ok yeah apparently i've v13 globally but v12 in this directory

icy maple

Use npm i discord.js@latest to install v13

You should always have ur terminal running in the project directory ur working in

crimson crane

Err, it says i'm missing intents "TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client."

    const { Client, Intents, Permissions } = require('discord.js')



    const client = new Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"], partials: ["CHANNEL"] })
icy maple

Show the full error

crimson crane
/Users/macci/Documents/Programming/JS/CBbot/node_modules/discord.js/src/client/Client.js:544
      throw new TypeError('CLIENT_MISSING_INTENTS');
      ^

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
    at Client._validateOptions (/Users/macci/Documents/Programming/JS/CBbot/node_modules/discord.js/src/client/Client.js:544:13)
    at new Client (/Users/macci/Documents/Programming/JS/CBbot/node_modules/discord.js/src/client/Client.js:73:10)
    at Object.<anonymous> (/Users/macci/Documents/Programming/JS/CBbot/server.js:6:16)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47 {
  [Symbol(code)]: 'CLIENT_MISSING_INTENTS'
}
icy maple

Also add the GUILD_VOICE_STATES intent

crimson crane
icy maple

Is that the line 6 of server.js?

crimson crane

no line 6 is commented out..

icy maple

Make sure the sever.js file is saved

crimson crane
crimson crane
icy maple

I don't think that part changes if it's unsaved?

crimson crane

if its unsaved it shows a white dot

carmine timber
crimson crane

oh

forgot to change that after swap to v13

damn it works, thanks a lot!

fiery hearth
fiery hearth Hey! Is there a way to make a bot join a stage voice channel in discord.js? I’ve...

for anyone wondering, i figured it out:

const {
    NoSubscriberBehavior,
    StreamType,
    createAudioPlayer,
    createAudioResource,
    entersState,
    AudioPlayerStatus,
    VoiceConnectionStatus,
    joinVoiceChannel,
} = require('@discordjs/voice');

let channel = await client.channels.cache.get('900857610717237258');
const connection = joinVoiceChannel({
    channelId: channel.id,
    guildId: channel.guild.id,
    adapterCreator: channel.guild.voiceAdapterCreator,
});
try {
    connection.subscribe(player);

    return connection;
} catch (error) {
    connection.destroy();
    throw error;
}
viral plank

hey i'm tring to make music bot i didn't send any Errors but i don't play anything

this is my code

if (command == "노래") {
        await interaction.reply("잠시 기다려주세요...");
        if (!interaction.member.voice.channel) {
          return interaction.editReply('먼저 음성 채널에 참여해주세요!');
        }
        var video = await youtube.searchVideo(option.getString('곡명'));
        interaction.editReply('```' + video.videos[0].title + '을 재생하겠습니다```');
        const connection = joinVoiceChannel({
          channelId: interaction.member.voice.channel.id,
          guildId: interaction.guild.id,
          adapterCreator: interaction.guild.voiceAdapterCreator,
        });
        const stream = ytdl('http://youtu.be/'+video.videos[0].id, { filter: 'audioonly' });
        const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary, inlineVolume: true });
        resource.volume.setVolume(1);
        const player = createAudioPlayer();

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

        player.on(AudioPlayerStatus.Idle, () => connection.destroy());
      }
rugged sky