#archive-voice

30636 messages · Page 23 of 31

carmine timber

IDK about that, but dash files are basically written in XML language. So more easy to read also.

dusk sedge

So supposing I need to convert it to opus stream, I would need to do more work in order to get the same result, just to proxy live video requests :/

Does anybody tried that before? Proxying youtube live videos from an express.js app rather than ytdl into discord.js directly

carmine timber
dusk sedge

I cannot run ytdl from my Vps because its ip would get banned (from experience, multiple times). Instead, i use a homelab server running a dynamic ip. That's why @carmine timber

carmine timber

That's much efficient way to do it, rather than using express.js to send requests.

dusk sedge

Ok nevermind

i will ask somewhere else

round jackal

Hello!, I created a tts command for voice channel but when the command is used once and the bot is used again it crashes and to use it again the bot has to restart

south lark

In theory, what is the maximum amount of users a bot could listen to all at once in a single voice channel. 👀

On an unrelated note, why does https://github.com/discordjs/voice/releases not have the most up to date version of djs voice? I believe the most up to date version is 0.7.4 yet the most up to date downloadable version is 0.7.5 feelsWoahMan

stuck drum

can somebody explains why the bot is not reproducing the audio ?

        const { joinVoiceChannel, createAudioPlayer, createAudioResource,  generateDependencyReport } = require('@discordjs/voice');
        
        joinVoiceChannel({
            channelId: message.member.voice.channel.id,
            guildId: message.guild.id,
            adapterCreator: message.guild.voiceAdapterCreator
        })

        const player = createAudioPlayer();

        const resource = createAudioResource('./assets/test.mp3')
        player.play(resource);
        console.log(generateDependencyReport());

i already have all the intents

carmine timber
stuck drum
carmine timber
stuck drum

how can i use absolute path?

stuck drum

like that?

const {resolve} = require("path");
const resource = createAudioResource(resolve('./assets/test.mp3'))
stuck drum

nothing happens :/

bot join in call
dont reproduces any sound
0 errors on console

carmine timber
stuck drum

already fixed that

carmine timber
stuck drum already fixed that

Ok so console log this

const fs = require('fs');
filenames = fs.readdirSync('./assets/')

filenames.forEach(file => {
  console.log(file);
})

Do you see test.mp3 there ??

stuck drum

yep, all files in assets folder

        player.on(AudioPlayerStatus.Playing, () => {
            console.log('playing');
        });

I put this in the code and the console registered

but nothing plays

carmine timber
stuck drum

@carmine timber

carmine timber

It says it is playing.

stuck drum

bot not reproducing

carmine timber
stuck drum

where @carmine timber

        const { joinVoiceChannel, createAudioPlayer, createAudioResource, generateDependencyReport, NoSubscriberBehavior, AudioPlayerStatus } = require('@discordjs/voice');
        const {resolve} = require("path");
        const audio = resolve('./assets/test.mp3')
        
        
        joinVoiceChannel({
            channelId: message.member.voice.channel.id,
            guildId: message.guild.id,
            adapterCreator: message.guild.voiceAdapterCreator
        })

        const player = createAudioPlayer()

        const resource = createAudioResource(audio)

        player.play(resource);

        console.log(resource.edges)

        //console.log(generateDependencyReport());

        player.on(AudioPlayerStatus.Playing, () => {
            console.log('playing');
        });
carmine timber
stuck drum where <@!828872488817393717>
        const { joinVoiceChannel, createAudioPlayer, createAudioResource, generateDependencyReport, NoSubscriberBehavior, AudioPlayerStatus } = require('@discordjs/voice');
        const {resolve} = require("path");
        const audio = resolve('./assets/test.mp3')
        
        
        const conn = joinVoiceChannel({
            channelId: message.member.voice.channel.id,
            guildId: message.guild.id,
            adapterCreator: message.guild.voiceAdapterCreator
        })

        const player = createAudioPlayer()
        conn.subscribe(player)

        const resource = createAudioResource(audio)

        player.play(resource);

        console.log(resource.edges)

        //console.log(generateDependencyReport());

        player.on(AudioPlayerStatus.Playing, () => {
            console.log('playing');
        });
stuck drum

that's work, thanks ❤️

carmine timber

👍

vocal lion

Is there any built in functionality for moving the bot between voice channels?

dusty needleBOT

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

carmine timber

<Guild>.me.voice.setChannel()

vocal lion

Thanks man, apparently i suck at searching through the docs

subtle granite

Can someone help me figure out why my music bot sometimes randomly loses connection and leaves/goes to next song in queue?

carmine timber
red totem

hello, can i anyone help with html website add discord server total members count?

dusty needleBOT

Documentation suggestion for @red totem:
_ Client#guilds
All of the guilds the client is currently handling, mapped by their ids - as long as sharding isn't being used, this will be every guild the bot is a member of

carmine timber

<Client>.guilds.cache.size

subtle granite
carmine timber
subtle granite
carmine timber

ok

dusk sedge

can you create an hls audio resource from .m3u8?

solemn current

how to do filters? i do not know much do you do them with ffmpeg static

subtle granite

Now what’s this👀

Is it the same?
Because it happens only at night when i go to sleep, and the rest of the day it works normally

fervent estuary

Cant say anything abt that

Anyhow its not related to djs so you should ask somewhere else

olive osprey

How can I catch this error?

subtle granite
for (let i in qu) {
  let roomid = qu[i].roomID;
  let room = client.channels.cache.get(roomid);
  let connection = joinVoiceChannel({
    channelId: room.id,
    guildId: room.guild.id,
    adapterCreator: room.guild.voiceAdapterCreator,
  });
  const player = createAudioPlayer();
  let rand = audio[Math.floor(Math.random() * audio.length)]
  let resource = rand...

connection.subscribe(player);
player.play(resource);
// ...
}``` I did this to play the same audio in all rooms but it's not working
final dock
client.on('voiceStateUpdate', (oldMember, newMember) => {
    console.log("Someone joined one channel")
    let newUserChannel = newMember.channel.id
    let oldUserChannel = oldMember.channel.id

    if(newUserChannel === "916075568766804008") {
        // Benutzer joint dem Move channel
        console.log("Joined the Move channel!")

    }
});

Does anyone know what is wrong here? The event is not getting triggered (its in index.js)

fervent estuary

Do you have guildVoiceStates intent?

quartz cypress

To follow up on this. The solution to my problem was that I needed to ensure that the stream I was passing to createAudioResource was in object-mode. It also helps if the highwatermark is set to something like 12 which is what was used by default in v12. Hope it helps for anyone.

carmine timber
lament sail

how to make bot join voice channel using id

dusty needleBOT
carmine timber

client.channels.cache

stuck spindle

Is there any way to seek audio ? Bcs the seek option was removed after v13. And ffmpeg's -ss option don't seem to be doing anything.

carmine timber
stuck spindle

some other options is just options that discord.js is and was using

I lyterally copied the seek option from v12

stuck spindle

Well, there is only one option I am not using -accurate_seek

carmine timber

Maybe that could help you.

stuck spindle

I am gonna try that

subtle granite
carmine timber
const player = createAudioPlayer();
let rand = audio[Math.floor(Math.random() * audio.length)]
let resource = rand...
player.play(resource);

for (let i in qu) {
  let roomid = qu[i].roomID;
  let room = client.channels.cache.get(roomid);
  let connection = joinVoiceChannel({
    channelId: room.id,
    guildId: room.guild.id,
    adapterCreator: room.guild.voiceAdapterCreator,
  });

connection.subscribe(player);

// ...
}

@subtle granite

subtle granite

hmmm

but it will play before it connect 🤔
I’ll try it

carmine timber
subtle granite

Yes I’ll try ty

stuck spindle
carmine timber

👍

subtle granite

one question @carmine timber

carmine timber
subtle granite
carmine timber Ask

It will create an audio player for every channel and play the same audio, or it will only create one player?

because i don't want to get banned because of sending requests to yt

carmine timber
subtle granite

Great

Ty!

stuck spindle

Well, I have another problem, when I try to join 2nd bot to a channel and 1st bot is alredy joined somewhere in the guild, it will join the 1st bot instead and remove it from the 1st channel.

icy maple

Are you running the bots in the same project?

stuck spindle

yes

I tryed to remove discord.js modules from require.cache and for each bot use new required module but that didn't work

icy maple

You have to specify the group when joining the channel

stuck spindle

I need to specify a group for each bot ?

icy maple

Else the voice package assumes it’s the same bot

carmine timber
stuck spindle
icy maple

e.g. joinVoiceChannel({ …, group: client.user.id })

carmine timber
stuck spindle
stuck spindle
subtle granite
Error: Initial Player Response Data is undefined.```
carmine timber
subtle granite
carmine timber
subtle granite
subtle granite
client.on('ready',async () => {
//...
const player = createAudioPlayer();
for (let i in qu) {
//...
  let room = client.channels.cache.get(roomid);
  let connection = joinVoiceChannel({
    channelId: room.id,
    guildId: room.guild.id,
    adapterCreator: room.guild.voiceAdapterCreator,
  });
  connection.subscribe(player);
}
///////
player.on(AudioPlayerStatus.Idle , async() => {
  let resource = ...
    player.play(resource);
});
/////////
  let resource = ...
  player.play(resource);
      
});``` I'm doing this to play an audio in all channels with one audio player ...
client.on('messageCreate',async message => {
if (message.content.startsWith('Vc')) {
let qu = JSON.parse(fs.readFileSync('./qu.json'));
let m = message.member.voice.channel;
const player = createAudioPlayer();
/////////
  let connection = joinVoiceChannel({
    channelId: m.id,
    guildId: m.guild.id,
    adapterCreator: m.guild.voiceAdapterCreator,
});
/////
let resource = ...
connection.subscribe(player);
player.play(resource);
    qu[message.guild.id] = {
        roomID: m.id,
        serverID: m.guild.id
    };
////////////
  player.on(AudioPlayerStatus.Idle , async() => {  
    let resource = ...
    player.play(resource);
  });

 }
})```
and if I want to add a room to json, I'll have to create a new audio player to play the audio
Is there any way to add it to json and listin to the audio without creating new audio?
subtle granite

Does someone know how to fix that

                  ^

Error: Cannot destroy VoiceConnection - it has already been destroyed```
vocal lion

Does anyone know how to play a internet radio stream/mp3/icecast?

daring ember

can anyone help me with disconnecting my bot from a voice channel?

rugged sky
daring ember
rugged sky
daring ember
rugged sky

That's where you insert your VoiceConnection object. You can store it as the return value of your joinVoiceChannel() function.

rugged sky
daring ember could I have an example?
const connection = joinVoiceChannel({
    channelId: <Channel>.id,
    guildId: <Channel>.guild.id,
    adapterCreator: <Channel>.guild.voiceAdapterCreator,
})

connection.destroy()

That's joining and leaving.

daring ember

connection.disconnect() also works

also if you don't mind me asking how I can check if the bot is currently in a vc?

rugged sky
daring ember
rugged sky
daring ember

            else if (message.content == (cmd + 'disconnect'))
                {
                const voiceChannel = message.member.voice.channel;

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

                     if (connection.state.status == 'ready')
                     {
                        const connection = joinVoiceChannel(
                            {
                                channelId: message.member.voice.channel.id,
                                guildId: message.guild.id,
                                adapterCreator: message.guild.voiceAdapterCreator
                            });
                         connection.destroy();
                         return message.channel.send("*Left VC*")
                     }
                     else if (!connection.state.status == 'ready')
                     {
                         return message.channel.send("I'm not in a VC")
                     }
                    
                 }```
rugged sky
daring ember
opaque spoke

i used the example "Music Bot" and changed it a bit to play audio files from local folder. However, sometimes the song just stops and it skips to the other one. is there a way to prevent sudden breaks?

shut zenith
summer crow
shut zenith
summer crow
summer crow
shut zenith
summer crow
harsh plover

how to make my bot join a voice channel

summer crow
shut zenith
fossil pine

Does anyone have an example of how to use ffmpeg audio filters?

dark sinew

I am having a hard time trying to figure out how to install discord voice

am i using the right command?

i wrote that command but it still didnt install

dark sinew

someone help

carmine timber
narrow shoal

anyone have a idea how to send the current user voice channel id from backend to frontend

carmine timber
narrow shoal

im making a music dashboard and im stuck at this problem

i can't figure out to send user voice state to frontend

carmine timber
narrow shoal i can't figure out to send user voice state to frontend

Oh I see.

So just get guild class from anywhere and do <Guild>.members.fetch('userID')

You will now get a guild member Class

Then you can simply do <GuildMember>.voice.channel.id

OR
if you have GUILD_VOICE_STATES intent, then you don't require to fetch it.
You can simply do [guild.members.cache.get('ID').voice.channel.id]

narrow shoal

to be honest i don't even know how to make this work

i fell in a bunch of loop hole that i need to solve

finite goblet

??

dark sinew
south glade

my bot joins the vc, its pfp has the green ring, leaves after one second. https://sourceb.in/TZwtSoOMsh
the audio file is 3 minutes long, here it is

please ping me so I can guarantee i can see the response, i have to log off now

viral hollow

For some reason on some songs it will play about a second of it and then stop

I think it might be that it's experiencing some packet loss and instantly giving up but I don't know how to configure that, could anyone help?

random zodiac

Anyone know how to fix ?

carmine timber
random zodiac
subtle granite
hardy veldt

My livestream stop playing after few seconds

const stream = await ytdl(this.songs[0].url, this.songs[0].live ? { isHLS: true, dlChunkSize: 0 } : { filter: 'audioonly', quality: 'highestaudio', dlChunkSize: 0, highWaterMark: 1 << 25 });

fixed with play-dl

main ferry

is there a way to prevent 403 errors

hardy veldt

403 = forbidden

dont play private videos

south glade

I have an issue: my bot joins the vc, its pfp has the green ring, leaves after one second. https://sourceb.in/TZwtSoOMsh
the audio file is 3 minutes long

please help

heres a recording of the error

shut zenith
            const connection = joinVoiceChannel({
                channelId: voiceChannel.id,
                guildId: server.id,
                adapterCreator: server.voiceAdapterCreator
            });
```With this, how do i send a reply only if the bot actually joins the voice channel (meaning it wasn't in it before)?
south glade

no visible error in the console @manic vault

manic vault
south glade

its supposed to

i sent a video of what happened @manic vault

manic vault
south glade

it did not

manic vault

that's why

south glade

wym? how fix

@manic vault

manic vault

r u sure the audio module is '../halloween.mp3'

icy maple

Pretty sure the path is in relation to the working directory, not the file it’s called from

If you want a path relative to the file, use path.join(__dirname, relativePath)

south glade

ohhhh ok i guess it liked ./halloween.mp3 better than ../
thank you

it does sound staticy though, how can i fix that?

south glade

I have 2 issues:

  1. Whenever I use my play command while a song is currently playing, the bot will crash.
  2. It sounds a little staticy
rugged sky
south glade
rugged sky
south glade

@rugged sky my bad, i don't get an error, but it just switches the song. i want it to play the song after the song that is currently playing is done. kind of like a queue

rugged sky
south glade <@!367286978368241664> my bad, i don't get an error, but it just switches the so...

Well the code you currently run is designed to create a new connection and AudioPlayer every time you run the command so that will just discard whatever you had. If you want it to queue just check if the bot is already playing and, if so, create a only a new audio resource for the next song and put it into an array that you can access. Then in your player's .on('idle', () => {}) function just make it play the next song in the queue if there is one.

alpine dagger

hi, is there a way to detect the green circle lighting up for voice chat?

tribal pumice

does anyone know how to solve this problem?
I'm installing sodium package, suddenly this error appears

carmine timber
carmine timber
neon cape
shut zenith
subtle granite

How to make bot join vc user is in?

wide mirage

How can I fix this error?

I have it every times 🤔

So the problem is from this package 😕 . Using lavalink will fix it

haughty maple

Hey guys, I am new to Discord.js Voice and trying to figure out if I can use 2 AudioPlayers at the sametime. Since, I am not sure how to describe what I want to do, here is an illustration of it :

I also am not sure about the logic of using 2 AudioPlayers, there may be an easiyer way to do this.

For example: The Bot plays a song and it has to play a sound effect for X reason (interrupt the song) and then it has to unpause (continue) the song

carmine timber
stiff junco

How do I change the volume of the music playing in a voiceChannel, provided I have the voiceChannelID

woeful dove

how did you do it?

wind arrow

I`m new Into Discord JS and I wanted to ask something:
I want the Bot to join the voice channel, if the message.member is in a channel, but when the member isn't I want him to write a message

tribal pumice

Does the "node-crc" package need to be installed?, I can't install it because of an error

wind arrow
wind arrow

I think he isn't updating the state "message.member.voice.channel"

icy maple

Try logging it

tribal pumice
icy maple

What error are you getting?

wind arrow
tribal pumice

in package.json it says "node-crc" but when I try to install an error occurs

wind arrow
icy maple
dusty needleBOT

To share long code snippets use a service like gist, sourcebin, starbin, or similar instead of posting them as large code blocks.

tribal pumice
icy maple

The npm package says you have to setup the rust environment

tribal pumice

ok i will try

wind arrow
haughty maple
lyric socket

hello

I have made tts bot for about 3 hours.
When I install @discord.js/voice and import them, tsc started returning below errors.

#11 13.34 node_modules/@discordjs/voice/dist/index.d.ts(2,8): error TS1192: Module '"/usr/src/app/node_modules/prism-media/typings/index"' has no 
default export.
#11 13.34 node_modules/@discordjs/voice/dist/index.d.ts(5,8): error TS1259: Module '"/usr/src/app/node_modules/@types/ws/index"' can only be default-imported using the 'esModuleInterop' flag

(I've aimed to package the bot with Docker. So the errors was displayed when I built docker image)

How can I resolve the errors?

The codes what I had written is here (partial):

import { joinVoiceChannel, getVoiceConnection, createAudioPlayer, VoiceConnection } from "@discordjs/voice";

client.once("ready", async () => {
  const channel = client.guilds.cache.get("")?.channels.cache.get("");
  if (!channel) return;
  joinVoiceChannel({
    channelId: "",
    guildId: "",
    adapterCreator: channel.guild.voiceAdapterCreator
  });

  connection = getVoiceConnection(channel.guildId) ?? null;
});

the dependencies in packages.json are:

"dependencies": {
  "@discordjs/voice": "^0.7.5",
  "@types/ffi-napi": "^4.0.4", /*  not related to this problem  */
  "discord.js": "^13.3.1",
  "ffi-napi": "^4.0.3", /*  not related to this problem  */
  "libsodium-wrappers": "^0.7.9",
  "typescript": "^4.5.2"
}

I installed the packages following discord.js guide.
https://discordjs.guide/voice/#installation

npm install @discordjs/voice libsodium-wrappers

sorry

I solved

I should use require() instead of import

wind arrow

Hey.. if i want to play music on my bot this error occurs

That's my code

wind arrow

I can’t find any fix

I've created an audioPlayer but now i've got a new problem:

rugged sky
woeful dove

Is it just me or this was working earlier but now the bot wont join my voice channel after this is executed?

wind arrow
woeful dove
wind arrow

Do you know how i can use AudioPlayer to play music from an YouTube - URL?

subtle granite

👀?

slim jay

Anyone have any stats on the performance decrease with inlineVolume? I want to change the volume on creation because it always starts too loud for people

carmine timber
woeful dove

Does any knows the name for the listeners for the audioplayer class? like ```
<AudioPlayer>.on('finish', () => {console.log('song finished!')})

icy maple

idle

The only events are the names of the AudioPlayerStatus and stateChange

woeful dove

I see, so if a song starts it would be AudioPlayerStatus.Playing?

icy maple

Yea

woeful dove

thanks!

haughty maple

Hey guys, sorry to bother with such a dumb question but can someone tell me how can I move client from X voice channel to Y voice channel ?

Currently, trying with setChannel function but if I understand it correctly, it is used for users and not for the client

woeful dove

I think, u would just use the joinVoiceChannel(channel) again with a different channel

haughty maple

That is what I was doing but I am trying to make a low-level voice recognition bot and for some reason it doubles the connection when I use joinVoiceChannel()

For example: When I say "hello world", It prints it on console. If I move the client on my own manually, it works fine else if I use joinVoicechannel for second time it will print whatever I say twice

carmine timber
haughty maple

I was thinking the same thing yet struggling with it for a while now.

Apparently it is caused by a function that I found on internet to connect a voice channel. I do not know at all why I did look for a function on internet when there is already a function that is very simple (joinVoiceChannel) provided by Discord...

async function connectToChannel(channel) {

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


    try {
        await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
        return connection;
    } catch (error) {
        connection.destroy();
        console.log(error)
    }
}

But I would be glad if someone explains me why this function caused such a problem

carmine timber
haughty maple

It works fine know. I just replaced the above function with a simple joinVoiceChannel()

tribal pumice
carmine timber
wind arrow

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

What does that mean?

        case "play": {
          client.distube.playVoiceChannel(
            VoiceChannel,
            options.getString("query"),
            { textChannel: channel, member: member }
          );
          return interaction.reply({ content: "🎼 Anfrage eingeganen." });
        }```
That's my getSubcommand
wild mist

Hello, is the @discordjs/voice package are TypeScript ready ?

I just installed it with NPM, along side with @discordjs/opus and sodium.

So, the currently installed version is :
@discordjs/voice v0.7.5, @discordjs/opus v0.5.3 and sodium v3.0.2

I try to check if there , now all of my builds are failing with these error :

Module '"${ProjectPath}/node_modules/prism-media/typings/index"' has no default export.
- From : ${ProjectPath}/node_modules/@discordjs/voice/dist/index.d.ts, Line 2

Module '"${ProjectPath}/node_modules/@types/ws/index"' can only be default-imported using the 'esModuleInterop' flag
- From : ${ProjectPath}/node_modules/@discordjs/voice/dist/index.d.ts, Line 5

I didn't even import anything from the @discordjs/voice package yet, as adding voice support to my bot was still only a plan.

Should I just forcefully silence the above TypeScript errors ?

I'm on TypeScript v4.4.4

carmine timber
wild mist

I quickly switched my environment to use TypeScript v.4.5.2, the issue still appears.

Well I do can apply a hot patch by changing those lines (that throws the compilation errors) to not use default export, or importing with wildcards.
But well, it is not a good way as NPM is configured to check and install for available updates every 24hours

carmine timber

So just create a issue at repository.

wild mist

Hmmm that is a good idea, hope it is a valid issue

wild mist
rotund wave
    at Socket.<anonymous> (/home/runner/Beta/node_modules/@discordjs/voice/dist/networking/VoiceUDPSocket.js:120:52)```what is that
subtle granite

how can i get a list of users playing a discord activity? Eg Poker Night

merry parcel

I get "error: The Operation was aborted" when i disconnect bot manually

is there a way to fix?

solemn condor

Is there a way to pipe the audio input that is received from discordjs/voice back into the bots output? Essentially creating a bot that echos the audio of a user?
I've made a couple of attempts but am not super familiar with handling audio streams

carmine timber
carmine timber
solemn condor

Is joinChannel still a function? or is is joinVoiceChannel now?

solemn condor

So i'm getting the "User user_id started/stopped speaking" in my console, but i dont hear any playback through the bot

here's the basic setup

const voiceConnection = joinVoiceChannel({
          channelId: channel.id,
          guildId: channel.guild.id,
          selfDeaf: false,
          selfMute: false,
          adapterCreator: channel.guild.voiceAdapterCreator,
        });
        console.log(voiceConnection)
        voiceConnection.receiver.speaking.on('start', userId => console.log(`User ${userId} started speaking`));
        voiceConnection.receiver.speaking.on('end', userId => console.log(`User ${userId} stopped speaking`));

        // A Readable object mode stream of Opus packets
        // Will only end when the voice connection is destroyed
        voiceConnection.receiver.subscribe(userId);

        // A Readable object mode stream of Opus packets
        // Will end when the voice connection is destroyed, or the user has not said anything for 100ms
        const opusStream = voiceConnection.receiver.subscribe(userId, {
          end: {
            behavior: EndBehaviorType.AfterSilence,
            duration: 100,
          },
        });

        // -------------------------

        // You can re-use the Opus stream, e.g. to play in another channel as an echo
        const resource = player.play(createAudioResource(opusStream, { inputType: StreamType.Opus }));

I've tried with/without the player.play() at the end

carmine timber

Remove This line

voiceConnection.receiver.subscribe(userId);
sharp temple

how can I request the bot in a call?

carmine timber
sharp temple
carmine timber
merry parcel

I have no entersState function

carmine timber
merry parcel

I’m using the package discord-player

I posted my problem here and they redirected to here

carmine timber
merry parcel
carmine timber
merry parcel

Tell discord-player developer to remove entersState function. Otherwise make your own discord music bot without discord-player.

carmine timber
merry parcel
sharp temple
carmine timber Show me
    at Object.run (C:\Users\55849\Desktop\botds\commands\play.js:17:33)
    at Client.<anonymous> (C:\Users\55849\Desktop\botds\index.js:26:21)
    at Client.emit (node:events:402:35)
    at MessageCreateAction.handle (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\actions\MessageCreate.js:25:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\websocket\WebSocketManager.js:350:31)       
    at WebSocketShard.onPacket (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
    at WebSocketShard.onMessage (C:\Users\55849\Desktop\botds\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
    at WebSocket.onMessage (C:\Users\55849\Desktop\botds\node_modules\ws\lib\event-target.js:199:18)
    at WebSocket.emit (node:events:390:28)
sharp temple
sharp temple

Thank you very much

subtle granite

Hi, I wanted to make sure that when a player joins a voice room it creates a new voice room and moves him into it but I get an error message

client.on("ready", () => {
    const channel = client.channels.cache.get("918037148635136010");
    if (!channel) return console.error("The channel does not exist!");
    channel.join().then(connection => {
        // Yay, it worked!
        console.log("Successfully connected.");
    }).catch(e => {

        // Oh no, it errored! Let's log it to console :)
        console.error(e);
    });
});

error message :

Uncaught TypeError: channel.join is not a function
glossy rampart

I'm probably just overlooking something, but Is it possible to get the JoinConfig properties from a VoiceConnection after it's been created? I absolutely was.

subtle granite
      channelId: interaction.member.voice.channel.id,
      guildId: interaction.guild.id,
      adapterCreator: interaction.guild.voiceAdapterCreator,
    })
    const player = createAudioPlayer()
    const resource = createAudioResource('../../music/FunkyMusic.mp3')
    const subscription = connection.subscribe(player)
    player.play(resource)
    player.on('error', err => {
      console.error(err.message)
    })```

Absolutely nothing happens

Well it does connect

rugged sky
subtle granite

I have all intents enabled so ig yes

rugged sky

I'd suggest you make the path to your resource absolute, I don't think it does relative paths.

subtle granite

Oki ill try that

Ok that worked ty

subtle granite

Are there ways to boost audio quality

left plinth

Hey! So I am having this odd issue with the voice lib, I can obtain packets of audio from a internet stream via axios, and pipe them into a buffer to be read, but at random times, the voice lib will just, stop playing audio. As in, I am still sending packets to the stream buffer to be read, but d.js just, stops handling them. It doesn't emit an event, doesn't close, just hangs there

My current theory is that when I have silence while switching tracks (the stream I pipe in does a crossfade, but some tracks have a little silence) that it stops playback

From what I can tell, there is zero option or configuration for this behaviour, but I'm hoping I'm wrong, because this is annoying

rose helm
left plinth

I am

And as for the silence packets, a little hard to do that- because the audio server is on a different machine, streaming via libshout, to icecast

I suppose I could write a small script to check for a lack of lengthy bytes in the packets and do it that way

rose helm

a shoutcast/icecast server should be sending audio constantly. Once a stream.Readable ends, then it emits the end event which is what causes the AudioResource to be destroyed.

left plinth

See, that's the thing

It is sending it constantly. That's what doesn't make any sense with the lib

I have literally logged the chunks being read, and it'll just suddenly stop sending the audio out to discord

if I completely reset the audio player, ie: new AudioPlayer() and do it again, works fine

rose helm

Are you logging end events and such

left plinth

Yep.

rose helm

I personally have no issues with frisky.fm which is icecast

left plinth

The only difference with the stream I have is it uses an adaptive bitrate, which I think may be breaking the lib

rose helm

CVRchanThinking

that could be possible since it expects a bitrate of 48000. You could pipe through ffmpeg constantly with the args
aresample=48000

At least, I think thats how you resample in ffmpeg

left plinth

The reason I don't do that from the stream side is because some of the tracks are quite old, like 1988 old- and sound horrid upscaled

I'll see what I can do though

rose helm

AwoooConcerned

left plinth

It may be one of those things where I write a custom lib for it, just wanted to try avoiding that to not reinvent the wheel lol

rose helm

Shouldn't really be necessary. ffmpeg probably has some args to preserve as much as possible, but just offer compatibility

left plinth

I'll take a look into it- it has some args I've tried, but it ends up stretching out the audio in funny ways- I'll message a friend of mine who is far more knowledgeable on ffmpeg

rose helm

I would also recommend taking a peek at some other projects to see if they face the same issue as you. I wrote a little something you can look at AmandaDiscord/Volcano on github. Assuming you want to. I'm curious myself because as far as icecast goes, I've only tested frisky.fm

left plinth

For sure, I'll take a look tomorrow, I've gotta get back to studying for a redhat cert exam; It's probably one of those things that is simple, but not immediately thought of fix wise - thanks for the help/pointers!

rose helm

👍

haughty maple

Hey guys, a question for who uses ytdl-core to play music from Youtube. Did you ever encounter this error ? Apparently it is a very common issue and I kind a feel stack. I am open to any workarounds or alternatives or any other solutions

olive ferry

Does anyone know why the audio player isn't firing off any events? There are no errors reported in console but nothing is firing
I attached the code

This segment of code is initialized upon bot startup

solemn condor

I'm working on a bot that can take my audio input and echo it. This is what I have.

          channelId: channel.id,
          guildId: channel.guild.id,
          selfDeaf: false,
          selfMute: false,
          adapterCreator: channel.guild.voiceAdapterCreator,
        });

        voiceConnection.receiver.speaking.on('start', userId => console.log(`User ${userId} started speaking`));
        voiceConnection.receiver.speaking.on('end', userId => console.log(`User ${userId} stopped speaking`));
        voiceConnection.receiver.subscribe(userId)

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

        const resource = createAudioResource(opusStream, { inputType: StreamType.Opus });

It logs User x started speaking and User x stopped speaking but still no audio is coming from the bot. Anyone have an idea why?

haughty maple
olive ferry

I did

carmine timber
carmine timber
subtle granite

Hello I'm playing a local mp3 file with @discordjs/voice but couldn't figure out the way to implement seek feature, can anyone help?

onyx flower

how do i make the bot leave the voice channel it is currently in?

onyx flower

nevermind..

subtle granite
carmine timber
subtle granite
wild mist

Hi guys, do anyone have issues with AudioPlayer constantly firing Idle, Buffering, Playing event ?
It only happens randomly at me, but it hangs the whole bot, as it keeps looping and taking 25% CPU usage (All available for the NodeJS instance).

The error occurs when the current song is ended, I then create a new AudioResource and then assign it to the existing AudioPlayer.
When it works, the bot starts playing the new song.
When it fails, the bot starts going from Idle -> Buffering -> Playing -> Idle -> Buffering -> Playing -> ....... (it's a constant loop)

My audio source is a localfile, I used my own youtube management API as YTDL wasn't reliable, and fetching details from the YouTube Data v3 API is costing quotas, I had make sure the local audio source file are not corrupted, infact, it plays just fine atleast, until at some point the AudioPlayer goes crazy

I noticed the issue as I was subscribed to the debug event.

My queue system listens for Idle and Playing events, so when the AudioPlayer went weird, it can flush all song in the queue in less then a second 😄
Or when the queue is on loop, it'll loop forever !

In the meantime, I had implemented a rate limit, so the bot will not try to load a new song if the olderSong was not completed yet.
Well, it helps a bit, but the audio player still loops there.

For my curiosity, I put a :

ConnectionInfo.AudioManager.player.on('debug', (messagess: string) => {
    globalThis.Debug.Debug.Debug.log('AudioPlayer Debug : ', messagess);
});

and this is what is logged, when the bot is on loop for 1 second :

from {"status":"playing","missedFrames":0,"playbackDuration":100,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}
AudioPlayer Debug :  state change:
from {"status":"buffering","resource":true,"stepTimeout":false}
to {"status":"playing","missedFrames":0,"playbackDuration":0,"resource":true,"stepTimeout":false}
AudioPlayer Debug :  state change:
from {"status":"idle","resource":false,"stepTimeout":false}
to {"status":"buffering","resource":true,"stepTimeout":false}
AudioPlayer Debug :  state change:
from {"status":"playing","missedFrames":0,"playbackDuration":100,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}
AudioPlayer Debug :  state change:
from {"status":"buffering","resource":true,"stepTimeout":false}
to {"status":"playing","missedFrames":0,"playbackDuration":0,"resource":true,"stepTimeout":false}
AudioPlayer Debug :  state change:
from {"status":"idle","resource":false,"stepTimeout":false}
to {"status":"buffering","resource":true,"stepTimeout":false}
AudioPlayer Debug :  state change:
from {"status":"playing","missedFrames":0,"playbackDuration":100,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}
AudioPlayer Debug :  state change:
from {"status":"buffering","resource":true,"stepTimeout":false}
to {"status":"playing","missedFrames":0,"playbackDuration":0,"resource":true,"stepTimeout":false}
AudioPlayer Debug :  state change:
from {"status":"idle","resource":false,"stepTimeout":false}
to {"status":"buffering","resource":true,"stepTimeout":false}
....
Sadly discord do not allow longer messages.

It doesn't have any kind of issues if it wasn't randomly looping when on song switch

carmine timber
wild mist
    // Since there is still another song in the queue, start playing again.
                    
    // Load the music data object for that song
    let SongData : PlaylistItem = ConnectionInfo.Queue[0];

    if (SongData.sourcetype !== "local" && !SongData.localsource) {
        // Song is not from local, and it was not cached yet.
        message.channel.send(`Please refill the TirtaAPI wallet again, the song is not decrypted successfully !!!!!`)
        return;
    }

    // It was a local song, load it !
    const RawSongData : AudioResource = createAudioResource(SongData.localsource);

    // Use the duration of the song and store it in the song data object
    SongData.duration = RawSongData.playbackDuration;
                
    // Update the ConnectionInfo queue with the SongData
    ConnectionInfo.Queue[0] = SongData;

    ConnectionInfo.CurrentState = "PREPARING"

    // Update the ConnectionInfo
    MusicModuleData.ActiveNodes.set(ConnectionInfo.GuildID, ConnectionInfo);
                
    // Play the song
    ConnectionInfo.AudioManager.player.play(RawSongData);

So the ConnectionInfo.AudioManager is a variable that holds PlayerSubscription object, the code :

ConnectionInfo.AudioManager = connection.subscribe(createAudioPlayer({
    behaviors: {
        noSubscriber: NoSubscriberBehavior.Play
    }
}));

In normal behaviour this happens on the AudioPlayer's debug listener :

AudioPlayer Debug :  state change:
from {"status":"idle","resource":false,"stepTimeout":false}
to {"status":"buffering","resource":true,"stepTimeout":false}
AudioPlayer Debug :  state change:
from {"status":"playing","missedFrames":0,"playbackDuration":192640,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}

Which seems to be perfectly normal, since when the song ends, it switches into Idle, and when the new song is loading, it's at buffering, less than 1 second, it was on playing.

However, when the random loop occurs, after it was on playing state, it just quickly go into Idle and the whole state cycle repeats

One thing that I noticed, when the AudioPlayer's is somehow goes into infinite loop when I assign a new AudioResource, this happens on the debug listener:

from {"status":"playing","missedFrames":0,"playbackDuration":100,"resource":true,"stepTimeout":false}
to {"status":"idle","resource":false,"stepTimeout":false}

That's playing the exact same song (Yes, I use the bot to repeat the same song for a lot of hours, and it's kind of annoying when at random times it just goes into infinite loop)

Currently it's playing I put gas gas gas over a police chase which is around 3minutes ish (which seems to be correct: "playbackDuration":192640.
When the looping starts, that playback went weird : "playbackDuration":100, my 3 minute song is now 100ms ? 😄

I was not sure if my current way is the best way to re-assign a AudioResource over to an existing AudioPlayer

I'm open to any suggestions 🙂

In the meanwhile, the bot is correctly looping the queue.

thorny path

hi i need to detect when a bot has finished reproducing: ```js
const player = createAudioPlayer();
const resource = createAudioResource(Readable.from(await tts.get({ text: message.content, lang: row.lang || 'en-us', limit_bypass: true })))

player.play(resource);
connectionVoice.subscribe(player);```

wild mist
strange nexus

How to kick a user from voice channel

wild mist
zenith lichen

I want to have a really big duration parameter here, so that long silences are also filled in the stream. but can't have due to interger overflow, also can't use BigInt here

    end: {
      behavior: EndBehaviorType.AfterSilence,
      duration:10000000000,
    },
  });

is there any workaround that

a little context here: I want to build a bot that can record the VC audio,

i tried using EndBehaviourType.Manual , but then, silences are automatically clipped in stream and i dont want that

subtle granite

How can i make a queue with @discordjs/voice

solemn condor

is there a permission or something that wouldn't allow my bot to play audio in a channel?

subtle granite

how do i make the bot to connect to a channel

solemn condor
turbid hedge

whats a good lavalink client as of now? I feel like erela.js isnt gonna work for me?

primal night
Error TypeError: Cannot read properties of undefined (reading 'adapterCreator')```
whole flare
turbid hedge

What are some benefits of shoukaku?

wide mirage
dusk sedge

how do you play a youtube livestream (using ytdl-core) in discord.js/voice?

using createAudioResource(ytdl(.... )) does not work, audio stops in few seconds

dusk sedge

anybody?

primal night
whole flare Can you send your `joinVoiceChannel` function?
    if (!serverQueue) {
        const queueConstruct = {
            textChannel: message.channel,
            voiceChannel: voiceChannel,
            connection: null,
            songs: [],
            volume: 100,
            playing: true,
            loop: false
        };
        queue.set(message.guild.id, queueConstruct);
        queueConstruct.songs.push(song);

        try {
            var connection = await joinVoiceChannel();
            queueConstruct.connection = connection;
            play(message.guild, queueConstruct.songs[0]);
        } catch (error) {
            console.error(`Error ${error}`);
            queue.delete(message.guild.id);
            
            const errorvoice = new MessageEmbed()
            .setColor("RED")
            .setDescription(`Error **\`${error}\`**`)
            return message.channel.send({ embeds: [errorvoice] });
        }
    } else {
        serverQueue.songs.push(song);
        if (playlist) return;
        else return message.channel.send(`✅ **|** **\`${song.title}\`** Queued`);
    }
    return;
}

function chunk(array, chunkSize) {
    const temp = [];
    for (let i = 0; i < array.length; i += chunkSize) {
        temp.push(array.slice(i, i + chunkSize));
    }
    return temp;
    return;
}

function play(guild, song) {
    const serverQueue = queue.get(guild.id);

    if (!song) {
        serverQueue.voiceChannel.leave();
        return queue.delete(guild.id);
    }

    const dispatcher = serverQueue.connection.play(ytdl(song.url))
        .on("finish", () => {
            const shiffed = serverQueue.songs.shift();
            if (serverQueue.loop === true) {
                serverQueue.songs.push(shiffed);
            };
            play(guild, serverQueue.songs[0]);
        })
        .on("error", error => console.error(error));
    dispatcher.setVolume(serverQueue.volume / 100);```
whole flare
primal night ```js if (!serverQueue) { const queueConstruct = { textC...

The joinVoiceChannel requires an options parameter which has a guildId, channelId and an adapterCreator which are required in the options parameter, also it won't return a Promise so the await won't do something. Replace your joinVoiceChannel function with

const guild = client.guilds.cache.get(`Your Guild ID`);
const vc = guilds.channels.cache.get(`Your Voice Channel ID`);

joinVoiceChannel({
   guildId: guild.id,
   channelId: vc.id,
   adapterCreator: guild.voiceAdapterCreator
});
primal night

Ok

open tulip

What should i do ?? how can i check that user connect to any voice or connect to specified voice
(i know the give role system...)

primal night
remote junco

Hey guys so i have a question about the voice basic example, im getting an error at this line "const connection = await connectToChannel(channel);" specifically on channel, even tho channel is constructed above.
The error message is ** "Argument of type 'VoiceChannel | StageChannel' is not assignable to parameter of type 'VoiceChannel'.**

"Argument of type 'VoiceChannel | StageChannel' is not assignable to parameter of type 'VoiceChannel'."

I have tried to assign proper parameters according to docs to the "channel" but couldn't get it work what am i missing?

icy maple

There should be a typedef for that, smth like VoiceBasedChannels

remote junco

Thank you! I will look into that asap

icy maple

If anything, just use the same return type as VoiceState.channel

cold wind

What's the variable to check if a user is already in a voice channel, or to grab the channel ID? I've tried message.author.voice.channel and message.author.voice.channelId but both return an error

minor bison

voice is a property of GuildMembers, not Users

remote junco

message.member?.voice.channel

cold wind

thanks i'll try that

cold wind
minor bison

correct, that's a User

cold wind

i can't find anything in user

ah nevermind, I was being stupid

remote junco

Ugh now i have fixed the errs but i can't play the audio eventhough i have the correct intents set....

Bot joins the channel also checks if anyone in the channel correctly but i can't play the audio..

also the intents

remote junco

This is the error im getting, when i initiate -join command bot joins but doesnt play audio

subtle granite
solemn condor

anyone around to help me with a sttreaming audio issue?

subtle granite

How can i make a queue with @discordjs/voice

wide mirage

Any eta for the memory leak?

knotty eagle

Hello! Anyone can help me? I'm trying to stablish a voice connection based in the discord.js documentation guide, but got the following error:

    at Object.sendPayload (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\structures\Guild.js:1320:26)
    at Ie (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\@discordjs\voice\dist\index.js:8:12615)
    at gt (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\@discordjs\voice\dist\index.js:8:12763)
    at Object.execute (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\commands\musicSystem\play.js:25:22)
    at Object.execute (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\events\interactionCreate.js:29:19)
    at Client.<anonymous> (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\functions\handleEvents.js:8:58)
    at Client.emit (node:events:390:28)
    at InteractionCreateAction.handle (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\client\actions\InteractionCreate.js:70:12)      
    at Object.module.exports [as INTERACTION_CREATE] (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\client\websocket\WebSocketManager.js:350:31)     

Intents:

subtle granite

👀?

wide mirage

How can i fix it?

subtle granite

.then(connection => {
require('http').get(language.radio.flux[radio].flux, (res) => {

     connection.play(res);

How to do that in v13 ?

whole flare
subtle granite

have u an example plz....

wide mirage
left nymph

How is this message.guild.me.voice.channel.leave(); in V13?

icy maple

<Connection>.destroy()

@left nymph

subtle granite
const vc = interaction.member.voice
        const channel = vc.channel

        const connection = joinVoiceChannel({
          channelId: channel.id,
          guildId: channel.guild.id,
          adapterCreator: channel.guild.voiceAdapterCreator,
        });
      
        
      
        const resource = createAudioResource(language.radio.flux[radio].flux, {inlineVolume: true});
        resource.volume.setVolume(100);
        const player = createAudioPlayer();
        connection.subscribe(player);
player.play(resource);```

No error, but the bot didnt play anything...
median phoenix

Hi, I'm sure this is probably an easy problem; but I can't find any sort of solution online--
I just need my bot to connect to a voice channel at the moment, its long term goal is for it to be able to read the volume of all the users in channel-- but I don't need to get into that rn.

const { joinVoiceChannel, AudioPlayer } = require("@discordjs/voice");
const { Client } = require("discord.js");

module.exports = {
    name: 'join',
    description: 'Joins the chat',
    execute(message, args)
    {
        const voiceChannel = message.member.voice.channel;

        if(!voiceChannel) {return message.channel.send("get in a channel ");}
        
     
        joinVoiceChannel(
            {
                channelId: message.member.voice.channel,
                guildId: message.guild.id,
               // adapterCreator: message.guild.voiceAdapterCreator
            });

        joinVoiceChannel(); 

    }
    
}

this is all that I have in my join.js but it's not working-- it gives me a crash log so large that I can't fit it in one discord message

knotty eagle

Hi, can someone give me some insight? I'm getting this error:

    TypeError: Cannot read properties of undefined (reading 'status')
    at Object.sendPayload (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\discord.js\src\structures\Guild.js:1320:26)
    at Ie (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\@discordjs\voice\dist\index.js:8:12615)
    at Object.gt (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\node_modules\@discordjs\voice\dist\index.js:8:12763)
    at Object.execute (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\commands\musicSystem\play.js:39:34)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Object.execute (F:\Programacion\bots\GTV13Bot_NoSlappey2_v2\src\events\interactionCreate.js:29:5)      
haughty maple

I am not sure but I think you should also precise guldId parameter when you call joinVoiceChannel

haughty maple
knotty eagle also tried that same error xd

It is hard to tell without seeing the actual code. Are you 100% sure that it is caused by these lines of your code ? + I haven't done anything with interactions yet but if your interaction is an object, all of the properties are already defined right? So why would you use "await" ?

knotty eagle

I just copy pasted what discord.js documentation said, kinda wnted to see how it works, it was just a desesperate attempt the await thing. It did works once or twice out of ten attempts

haughty maple

Ignoring your question I want to say something : you will get in trouble with ytdl-core. Go with play-dl if you want to play audio from youtube because it has less bugs, problems and much more easier to use

I can't see the problem on your code but I think it is a better idea to use a single source to retrieve information for channelId & guildId & adapterCreator
Example : If a user sends !join message. You can get the user's voice channel by

const voiceChannel = message.member?.voice.channel 

connection = joinVoiceChannel({
                        channelId: voiceChannel.id,
                        guildId: voiceChannel.guild.id,
                        adapterCreator: voiceChannel.guild.voiceAdapterCreator,
                        selfDeaf: false,
                        selfMute: false,
                    });

If this doesn't solve your problem neither, maybe someone else with more experience then me can help you ^^

icy maple

Preferably, you should also use the entersState function to make sure the connection actually becomes ready

Also gotta do permission checks bc Discord doesn’t emit an error if the bot is missing permissions to connect

subtle granite
subtle granite
zenith lichen

any solutions to this silence problem

carmine timber
zenith lichen
carmine timber
cold wind
carmine timber
haughty maple
carmine timber
haughty maple

are you the creator of play-dl 😮

guys he is speaking language of the gods, careful xd

carmine timber

XD

subtle granite

why does <Guild>.me.voice.channelId still points to channel that was deleted?
bot was connected to it before it was deleted

whole flare
subtle granite

anyways i sorted it out

turns out voice.channel is null after channel is deleted to im using this way now lol

whole flare

ah ok

median phoenix

is there a way for me to track if a user in the voice channel a bot is in is speaking?

                var volume = voiceManager.GetLocalVolume(404360475757903882);
                Console.WriteLine("User is at volume level {0}", volume);```
this thing I found on the documentation straight up does not work; as in it crashes cause "discord" isn't a thing
exotic haven

How can I get the currently playing player?

haughty maple
exotic haven

I just need to be able to resume the song but it won't unpause.

Anyway to create one?

rugged sky
pure basalt

hello, my bot joins the channel and instantly leaves, I've checked that the stateChange event is emitted and that the newState is idle

exotic haven
exotic haven

I seem to get this error Property 'subscription' does not exist on type 'VoiceConnectionState'.

exotic haven
rugged sky Yeah

Did I do something wrong? const player = voiceConnection?.state.subscription.player

subtle granite

Hello, could someone help me? I made a music bot perfectly, I checked that everything was fine and I installed all the following modules:

npm i @discordjs/opus
npm i opusscript
npm i ffmpeg-static
npm i ytdl-core
npm install discord.js

and by the way I am in v13

here are the screenshots of my code and the error :

I changed my token

exotic haven

npm i ytdl-core-discord

rugged sky
subtle granite
subtle granite

when I go to voice and I put a music, I do not hear the music and it puts me this error

exotic haven

What's your code?

subtle granite
rugged sky
exotic haven

Is your connection already subscribed to the player? Because it should have that property.

subtle granite

as a result?

exotic haven
subtle granite

youtube

rugged sky
exotic haven

It should be subscribed first, and the property is called subscription not subscribe.

exotic haven

Then I get Block-scoped variable 'player' used before its declaration. on the line voiceConnection?.subscribe(player)

exotic haven

That video

subtle granite

I have to replace it here?

exotic haven

No

subtle granite

or ?

exotic haven

Before that line try doing const video = args[0]

Or js connection.play( await ytdl(args[0], { filters: 'audioonly' }), {type: 'opus'}

rugged sky
exotic haven

All I need is a way to get the currently playing music, then resume the player.

subtle granite

args is not defined

@exotic haven

exotic haven

Define args

async run (message, args, { query })```
subtle granite

It gives me this error code after changing the connection.play and also after defining args

exotic haven

Show me the new code.

subtle granite
exotic haven

And what's the full error?

subtle granite

this

exotic haven

That's everything? Does it not give you a line?

subtle granite

no it only gives me that :/

exotic haven

Okay, remove args from the first aync run

And try putting it in the last one so js async runVideo(message, args, connection, video) { connection.play( await ytdl(args[0], { filters: 'audioonly' }), {type: 'opus'}

subtle granite

I copied what you told me, but I still get the same error

exotic haven

I mean what I told you works for me.

subtle granite

oh but how do I do that?

exotic haven

Try doing async run instead of async runVideo.

subtle granite

like this?

exotic haven

Yes

subtle granite

It always gives me the same mistake

Maybe the error comes from my index.

exotic haven

I have no more ideas sorry

Like I said what works for me doesn’t seem to work for you.

subtle granite

it doesn't matter xD

subtle granite
subtle granite
uncut thunder

Good night! I'm using @discordjs/voice to make my bot play music on a voice channel. Everything seems to be working out, the bot plays the songs correctly. But in some situations, such as when there is more than one person in the voice channel, the robot simply stops playing and goes into AutoPaused state. I'm very frustrated with this, I've read the documentation a few times and I haven't been able to solve the problem. I installed all necessary libraries for this task. Can someone help me?

true timber

Is anyone else getting this error when installing @discordjs/voice

npm WARN tarball tarball data for prism-media@https://codeload.github.com/distubejs/prism-media/tar.gz/main (sha512-lkEYKsA09+XkKqQHHK96cpmzJE3rlIoMHYww0gfS4Vodz/ZS2p/4Bt09xAqRoHpUEihbO+KdaOFGOypBdBaz7Q==) seems to be corrupted. Trying again.```

nvm I removed package-lock and it seems to be installing correctly

uncut thunder
urban canopy
carmine timber
sick zephyr

hi how to make a leave command for a radio bot

valid marsh

<Guild>.me.voice.disconnect()

sick zephyr
valid marsh
sick zephyr

but it's for a another chanel

foggy bramble

Hey, do you guys know what cause the Voice Connection to never reach the "ready" state, without printing an error?

My code WAS working, but now it decided to refuse connection with discord

(or something, i am pretty confused yk)

If the onStateChange function of the voice library isn't broken, the connection is stuck at the SIGNALLING stage

foggy bramble

ok

i'm stupid

odd trellis

can someone help me code a music bot for my school that has 300+ people in it

dm me whenever

foggy bramble

But gl anyway

halcyon verge

Can anyone help me? How can i do .setVoiceChannel(null) if i got the users ${executor.id} ?

odd trellis

ty

carmine timber
subtle granite

Hey

I'm trying to update my music bot code to v13

carmine timber
subtle granite
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
 
module.exports = {
    name: 'play',
    description: 'Joins and plays a video from youtube',
    async run(client, message, args) {
        const voiceChannel = message.member.voice.channel;
 
        if (!voiceChannel) return message.channel.send('You need to be in a channel to execute this command!');
        const permissions = voiceChannel.permissionsFor(message.client.user);
        if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
        if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
        if (!args.length) return message.channel.send('You need to send the second argument!');
 
        const validURL = (str) =>{
            var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
            if(!regex.test(str)){
                return false;
            } else {
                return true;
            }
        }
 
        if(validURL(args[0])){
 
            const  connection = await voiceChannel.join();
            const stream  = ytdl(args[0], {filter: 'audioonly'});
 
            connection.play(stream, {seek: 0, volume: 1})
            .on('finish', () =>{
                voiceChannel.leave();
                message.channel.send('leaving channel');
            });
 
            await message.reply(`:thumbsup: Now Playing ***Your Link!***`)
 
            return
        }
 
        
        const  connection = await voiceChannel.join();
 
        const videoFinder = async (query) => {
            const videoResult = await ytSearch(query);
 
            return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
 
        }
 
        const video = await videoFinder(args.join(' '));
 
        if(video){
            const stream  = ytdl(video.url, {filter: 'audioonly'});
            connection.play(stream, {seek: 0, volume: 1})
            .on('finish', () =>{
                voiceChannel.leave();
            });
 
            await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
        } else {
            message.channel.send('No video results found');
        }
    }
}
 
 ``` im getting this error: ```:\Users\Patron\Documents\GitHub\Hydration-Homie\commands\play.js:42
        const  connection = await voiceChannel.join();
                                               ^

TypeError: voiceChannel.join is not a function```
subtle granite
carmine timber
subtle granite
carmine timber
subtle granite
subtle granite
carmine timber
subtle granite
carmine timber

Yup probably.

subtle granite

yeah same with messageCreate, etc. like im a fan of slashies but most of what they did seems to complicate sh*t

valid marsh
carmine timber
valid marsh

That is my bad, then! Noted kek

late vigil

hello, did anyone know if we can get the audioPlayer from a VoiceConnection ?

rugged sky
late vigil

but i found it, you get it by the <VoiceConnection>.subscibe(audioPlayer) and that will return a PlayerSubscription

shell hemlock

How can I solve this connection error? (It is related to Discord.js / Voice)

N [Error]: aborted
    at connResetException (node:internal/errors:691:14)
    at TLSSocket.socketCloseListener (node:_http_client:407:19)
    at TLSSocket.emit (node:events:406:35)
    at node:net:672:12
    at TCP.done (node:_tls_wrap:580:7)
rugged sky
late vigil
shy hornet

Where can I find the voice Documentation?
The documentation button on the GitHub page no longer seems to direct to the voice Documentation, and there is no voice option on the documentation site/doc settings

dusty needleBOT
shy hornet
shy hornet
royal valley

hey i'm looking at the basic example from the discordjs/voice repo, and it does not look basic
is the adapter stuff boilerplate code? i'm a bit rusty on my nodejs and this looks so intimidating

green vigil

TypeError: Cannot create property 'audioPlayer' on string 'C:/Users/personal/Downloads/yH7Xg9cjyfkF6JCVBHdoGjlDPyJAOxMt.mp3'

nimble escarp

Can anyone please tell me how to check if the user is in the same vc as the bot.

please

serene briar

only just saw this channel, kinda crossposting ig?

            try{
                await user.voice.setChannel(null);
            }catch(err){
                message.channel.send("Failed to disconnect user");
                return;
            }

user is a user object, this throws an error and goes into the catch. user.voice is undefined when I log it out. I am not sure how to achieve disconnecting people from voice channels.
i assume this is the right channel for it, correct me if not

rugged sky
serene briar

yeah I am struggling to get the guild member right now. I want my bot to work anywhere and get messaged anywhere so I want to be able to give the bot !disconnect [user id] in dms and it will disconnect that user no matter which guild they are in. I am still trying to find an elegant way to do that so if you have any ideas throw them at me.

I know I could manually get the guild by ID, or I could run a loop for every guild my bot is in and check each one, but none of these solutions sound all that great

royal valley

hey i'm currently struggling with something: js bot.channels.cache.forEach(channel => { if (channel.type == "GUILD_VOICE" && channel.members.size > 0) { let played = false; const conn = joinVoiceChannel({ channelId: channel.id, guildId: channel.guild.id, adapterCreator: channel.guild.voiceAdapterCreator }); conn.subscribe(player); const resource = createAudioResource("./resources/waterphone.mp3", { inputType: StreamType.Arbitrary }); player.play(resource); played = true; entersState(player, AudioPlayerStatus.Playing, 5e3); player.on('stateChange', (oldState, newState) => { console.log(newState.status); if (newState.status == 'idle' && played) { conn.disconnect(); played = false; } }); //channel.members.forEach(m => console.log(m.id)) } }); how would i do something when the file has finished playing? i'm trying to disconnect it once it has finished playing, but when there's two channels to use, it will join the first one, disconnect immediately and then do the next channel perfectly

haughty maple
royal valley
lapis compass

Anyone able to help me? I'm getting an error after playing couple of seconds of a song

Pictures of Code + Error:

the player.on error prints this:

soft bough

Hi there, im using the discord.js/voice library to just create an audio player; how do I make it so my bot joins the voice channel undeafend?

haughty maple
lapis compass

honestly, i have no clue. some vid told me to put it in apparently it should ge the next song in the queue

but the main problem really is the error aborted thing

idk even why it gives the error "aborted" and the resource is "null" lol, it plays the song for about 30 seconds to 1 minute then it just stops the music and gives the error: aborted with resource null

soft bough

@haughty maple Ty, it seems my bot joins the vc and is playing but for some reason I don't hear the audio

Could I post the code maybe and somebody could identify something? I installed all the dependecies for the discord.js voice

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


         let resource = createAudioResource(("C:\Users\jk076\OneDrive\Desktop\DiscordProject\images\wedem.mp3"), {inlineVolume: true})
         resource.volume.setVolume(1)

         const player = createAudioPlayer();
       
         connection.subscribe(player);
         player.play(resource)
         console.log("done");
rugged sky
soft bough

Yes and I can see the little green highlight so I know it's trying to play something

haughty maple

Yesterday, I had a similar problem. It was caused by the source file (.mp3). It may be same for you

lapis compass

@haughty maple any idea further for me?

soft bough

What file type would be best? @haughty maple

haughty maple

I don't know I think mp3 is okay. My problem was related to fs. I tried to make my bot speak with google text to speech api and I was trying to use my file before I wasn't done with writing

haughty maple
soft bough

I tried with different files didnt work... in terms of the code does everything seem okay?

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

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

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

FFmpeg
- version: 4.4-essentials_build-www.gyan.dev
- libopus: yes
lapis compass
soft bough

This is also thedependency report

haughty maple
haughty maple

But this is only my opinion. This may not even be related. I would check if it actually finds the mp3 file

soft bough

I think I read that only global paths but yes I can try that

How would I go about testing to see if it finds it?

haughty maple
soft bough

@haughty maple I was using backslashes for the path....

haughty maple

Oh :P, shit happens bro.

soft bough

I thought it was backslash for windows though? I know mac is forward slash

lapis compass
soft bough

Hi there, for the setVolume

What are the inputs for that? 0 to 1 scaling?

icy maple

0 is none, .5 is half, 1 is no change, and 2 is double

soft bough

Thank you and i was wondering what the default disconnect timer is for a bot and how would i go about manually disconnecting after a specified time?

lapis compass

Connection is the variable you gave the joinchannel thing

jade parcel

Hello there. Once I have a voice connection, is it possible to receive events for that connection? Specifically am interested in:

  • Someone started speaking
  • Someone stopped speaking
north frigate
jade parcel
sacred lintel
analog notch

How do I error check if joinVoiceChannel worked or not?

I've had instances where the bot will not join but the function works without an error. All the promise based checking of the old voice implementation in v12 seems to be gone...

For example, I have no idea how to check if the bot could not connect to a voice channel for some reason. The only other workaround I can think of is to manually check the permissions of the channel before attempting to connect.

rugged sky
verbal hemlock

works fine

but after sometimes this error shows up...

someone please help

green rampart
const player = createAudioPlayer();

        const resource = createAudioResource('../mp3/track.mp3', {
            inlineVolume: true
        });

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

I'm trying to play some audio, but it's not playing anything (it does show the talking indicator on the bot)
is it something with volume that I'm missing?
I can't seem to set the volume anywhere

fair wasp

Can bots also go live in a stage channel?

jovial atlas

how do i use streamlink

green rampart

I'm getting a very weird bug when running my bot on ubuntu, it can join and play audio in voice channels just fine, just not when it's done with an OPUS stream. Has anybody else run into this issue?

rose helm

all streams are pipelined to opus. I personally encode to ogg opus when using ffmpeg and have no issues

tribal topaz

is it possible to join another channel with same VoiceConnection?

icy maple

No

Well, i guess if the bot gets moved by another member, the connection will temporarily go out

green vigil

So I got my bot working in vc and stuff and audio file, but says it's not playing audio, when there is a green circle around the bot

want my code?

**I fixed it I didn't need the file extension only the start of it

tribal topaz
icy maple

You could use joinVoiceChannel again and subscribe it to the player

green rampart

How do you encode to ogg opus? I'm using @discordjs/opus with ytdl-core-discord

civic notch

How can I deploy a bot efficiently to multiple guilds?

Currently, I have a list of all channeIDs and I iterating through it and create a new connection in every channel...

for(var i = 0; i < list.length; i++) {
    const channel = bot.channels.cache.get(list[i]);
    channel.join().then(connection => {
        player = connection.play(streamURL, {bitrate: 320000});
    });    
}

...but after connecting to 20-30 channels, the music is very lagging

Is there any more efficient way?

rose helm
rose helm
haughty maple

what happens to connection when bot gets disconnected by a user ?

nimble drift

how to get bot deaf itself on join?

subtle granite

can you help me to solve the problem with the acolade please?

north frigate

How do i pause a connection

civic notch
rose helm

your network upload is bottlenecked by streaming to every guild

civic notch
rose helm

Then it's possible that the cpu is struggling to keep up since you're putting this all on a single core

if the track isn't opus, then it needs to pipe through ffmpeg as well which is more cpu strain

civic notch

Ahhh, yeah this is 24/7 mp3 stream

rose helm

Welp. Good luck multithreading. You'd be best off making an audio service independent from your bot similar to LavaLink, but with the assumption that it's all gonna be the same track. You can have a main thread requesting the stream for download and transcoding to opus and then pipe the data to worker threads

civic notch

Alright, Async - Thank you very much for the great support!! eguyHype

rose helm

papiopComfy

civic notch

@rose helm A little question to the subscription thing...

So I try to stop the sub when the channel is empty and when someone joins, I want to start the sub again

So in the event listener if someone joins the channel, I had something like this to get all "existing" voice connections:

bot.voice.connections.forEach(conn => {
}

...but I can't use conn.subscribe for this - Do you have an idea how can I manage this?

rose helm

You can't pause playback on a per connection basis when using 1 player since the audio playback is linked to the player

civic notch

Mhh, it makes sense...

red spire

how to recover the audio stream of a discord conversation ? I can't find anything on the subject in the doc

north frigate

is there a way to temp pause a connection?

!join

quaint meteor

Hi, I want to make an discord music bot I have the following code

const {videos} = await yts(message.content);
if (!videos.length) return message.reply("No songs were found!");
const song = {
    title: videos[0].title,
    stream: ytdl(videos[0].url, {filter: "audioonly"}),
    url: videos[0].url
};
const resource = createAudioResource(song.stream)
player.play(resource);
bot.connection.subscribe(player);

Everything works, but after a short time I get the following error:

N [Error]: 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:687:12
    at TCP.done (node:_tls_wrap:580:7) 

Anyone knows how to fix that?

north frigate

Every time i do ```javascript
player.pause()

it returns ```false```

why is it doing this?

north frigate
hallow lynx
const connect = joinVoiceChannel({
    channelId: voicec.id,
    guildId: voicec.guild.id,
    adapterCreator: message.guild.voiceAdapterCreator,
});
const dispatcher = connect.play('./Warm Summit.mp3');
``` Everything working until I try and play audio...
```js
Uncaught TypeError: connect.play is not a function
``` If you could help me that would be great, thanks!
dusty needleBOT
icy maple

You need to look into how audio players and audio resources work bc that’s not how the voice package works

vale hollow

is there a way for me to check how long an audio resource has been playing for?

E.g. if I played it for 2 seconds, paused it for 5 seconds. Is there a way for me to know it's played for 2 seconds?

I'm trying to implement rewind/fast forward functionality

subtle granite

Is there anything can I do to avoid this issue 4kr_wb3den

limpid lotus

Hey, I want to play an audio like the documentation said it but I get the Error:

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

This is my code:

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

        const player = createAudioPlayer();
        const resource = createAudioResource('home/FART.mp3')
        player.play(resource)

        connection.subscribe(player)
rugged sky
limpid lotus

still not working

rugged sky

Try a different one.

limpid lotus

Is ist possible that the createAudioResource resoucre is a URL so an internet radio?

limpid lotus
quaint meteor

I'm using an mp3 stream

limpid lotus
quaint meteor
limpid lotus
quaint meteor

Check if you have this intent added ```
Intents.FLAGS.GUILD_VOICE_STATES

limpid lotus

I think I have enabeled all intents with one line. Or do i need to activate them in the dev portal?

limpid lotus
quaint meteor
limpid lotus
limpid lotus
dusty needleBOT
quaint meteor

Here you have a list of the Intents

shy citrus

for some reason, player.stop() throws error

here are my dependencies

"dependencies": { "@discordjs/voice": "^0.7.5", "discord-buttons": "^4.0.0", "discord.js": "^13.3.1", "express": "^4.17.2", "ffmpeg": "0.0.4", "ffmpeg-static": "^4.4.0", "@discordjs/opus": "^0.5.0", "libsodium-wrappers": "0.7.9" }, "devDependencies": { "node": "^16.6.1" }

haughty maple
red spire

i found in v12 its possible to receiving audio from user https://v12.discordjs.guide/voice/receiving-audio.html#basic-usage
i try the method but i have the error connectionA.receiver.createStream is not a function
its v13 who broke this ? or have way for repair that ?

  let user = message.author;
  let channel1 = client.channels.cache.get('864633308797337611');
  let channel2 = client.channels.cache.get('571718353652285444');

  const connectionA = joinVoiceChannel({
    channelId: channel1.id,
    guildId: channel1.guild.id,
    adapterCreator: channel1.guild.voiceAdapterCreator,
    selfDeaf: false,
  });

  const connectionB = joinVoiceChannel({
    channelId: channel2.id,
    guildId: channel2.guild.id,
    adapterCreator: channel2.guild.voiceAdapterCreator,
    selfDeaf: false,
  });

  const audio = connectionA.receiver.createStream(message.author.id);
  connectionB.play(audio, { type: 'opus' });
trail belfry

hello how do i make join vc to create a new channel

drowsy shore
// voiceStateUpdate
/* Emitted whenever a user changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
PARAMETER    TYPE             DESCRIPTION
oldMember    GuildMember      The member before the voice state update
newMember    GuildMember      The member after the voice state update    */
client.on("voiceStateUpdate", function(oldMember, newMember){
    console.log(`a user changes voice state`);
});```
trail belfry

ill make like this but its create after i leave

        if (newState.channelId === '922185381095559219') {
            newState.guild.channels.create(`〔🔒〕ʜᴜʙ - ${newState.member.user.discriminator}`, {
                type: 'GUILD_VOICE',
                parent: '904743415978262591',
                permissionOverwrites: [
                    {
                        id: newState.member.id,
                        allow: [Permissions.FLAGS.MANAGE_CHANNELS]
                    }
                ],
                userLimit: 5
            }).then(async (voice) => {
                await newState.setChannel(voice);
            }).catch((err) => {
                console.error(err);
            });
        } if (oldState.channel?.name === `〔🔒〕ʜᴜʙ - ${newState.member.user.discriminator}`) {
            oldState.channel?.delete();
        }

also why its return null ?

muted pebble

Trying to record audio from a user, it connects and doesn't crash but every time I try to record the file size ia always 0 bytes.

    const stream = receiver.subscribe(userId, {
        end: {
            behavior: EndBehaviorType.Manual
        },
    });
    stream.pipe(fs.createWriteStream('test.pcm'))```
upbeat fog

can anyone provide me with the code from which the bot willl join a vc

upbeat fog
brittle veldt

Provide full code?

trail belfry

hello why is this code doesnt work, when i change the mute or defean status its show the error

        if (oldState.channel?.name === `〔🔒〕ʜᴜʙ - ${oldMember.user.discriminator}`) {
            await oldState.channel?.delete();
        }

Errors

DiscordAPIError: Unknown Channel
    at RequestHandler.execute (C:\Users\haziq\Desktop\Projects\JavaScript\one-venture\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (C:\Users\haziq\Desktop\Projects\JavaScript\one-venture\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
    at async VoiceChannel.delete (C:\Users\haziq\Desktop\Projects\JavaScript\one-venture\node_modules\discord.js\src\structures\GuildChannel.js:535:5)
    at async VoiceStateEvent.run (C:\Users\haziq\Desktop\Projects\JavaScript\one-venture\src\events\voice\VoiceStateEvent.js:38:13) 
{
  method: 'delete',
  path: '/channels/922322676041805885',
  code: 10003,
  httpStatus: 404,
  requestData: { json: undefined, files: [] }
}
upbeat fog
brittle veldt

the message constructor is used internally.
follow the guide on how to setup a listener and create commands, etc.

muted pebble

Does anyone have an example of recording multiple users in a VC?

mental quarry

How would one get a discord bot to just simply join a voice channel
I am far too tired to make sense of discordjs.guide/voice right now im sorry

not even to play music
just like to go into a voice channel and be ther

icy maple
dusty needleBOT
mental quarry
icy maple

joinVoiceChannel is an export from the voice package

Also a function that takes an options object, as shown in the guide

mental quarry

ohhhhh i reread it
lemme try smth

    if (message.channel.send === '!join vc') {
        const connection = joinVoiceChannel({
            channelId: 922142097983799396,
            guildId: 770641536626589696,
        });
    };
});```

this would be it then (this make s sense to me)
icy maple

Ids have to be string

Ur also missing the voice adapter

Also, channel.send is a method, not a string

Prob meant message.content

mental quarry

yes
i am tired man sorry

icy maple

Nw

adapterCreator: channel.guild.voiceAdapterCreator

mental quarry

"adapterCreator: channel.guild.voiceAdapterCreator,"
i saw thisi beforehand but i just ignored it
what would i use for it ig?
channel.guild I can do
voiceAdapterCreator however?

icy maple

Yes, you can do guild.voiceAdapterCreator

mental quarry

oh i literally just have to add underneath guildId: whatever it was
adapterCreator: (the channel id).guild.voiceAdapterCreator

icy maple

Channel id is not valid here

It has to be the channel object

mental quarry
acoustic perch

anyone having issues with discordjs/opus package? it seems like the package is broken or something...

sage nexus

What are the differences between shoukaku and erela.js? Is one better to use than the other? Also in terms of which one is more maintained

limpid lotus

Hey, my code doest work can you help me?
I get the green circle and when i try to play audio from an Internet stream and when I enable the intents I get the error:
"TypeError: Cannot read properties of undefined (reading 'Client')"

Heres my code:

const { Discord, Intents } = require('discord.js');
const { joinVoiceChannel, getVoiceConnection, createAudioResource } = require('@discordjs/voice');
const { createAudioPlayer } = require('@discordjs/voice');

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

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on("messageCreate", async message => {

    var channel_id = message.guild.channels.cache.get("922193458767216641");

    var guild_id = message.guild.id

    if (message.content === "test") {

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

        const player = createAudioPlayer();
        const resource = createAudioResource('streams.ilovemusic.de/iloveradio2.mp3')
        player.play(resource)

        connection.subscribe(player)
    }
})

client.login("TOKEN");

Would appreciate if you could help me

boreal crest
limpid lotus
boreal crest

What other thing?

limpid lotus
boreal crest

No idea how that works lol
Wait for someone else

limpid lotus
limpid lotus
boreal crest

It's only been 2 hours, not that bad for something not-so-popular/easy like djs voice;)

limpid lotus
boreal crest

Ok, congrats xD

wind arrow

Why does connection.dispatcher.pause() work but connection.dispatcher.resume() isn't?

subtle granite

Hello, I'm making a discord bot with music features just like rythm. I'm brand new to js but have experience with discord.py. That said, I've ecountered issues apparently due to discord.js v13 update. Here's my code : https://pastebin.com/TDnU1xPa

shy citrus

when i pause the mp3 file, it throws typerror

btw i am using v13

subtle granite
shy citrus
subtle granite Can you please help me ? How did you make ur bot join a vc

you need to include @discordjs/voice and FFPMEG-Static and libsodium wrappers
you can make your dependencies in package.json this:
"dependencies": { "@discordjs/voice": "^0.7.5", "discord-buttons": "^4.0.0", "discord.js": "^13.3.1", "express": "^4.17.2", "ffmpeg": "0.0.4", "ffmpeg-static": "^4.4.0", "@discordjs/opus": "^0.5.0", "libsodium-wrappers": "0.7.9" }
then, you need to insert this->
`player = createAudioPlayer();
let resource = createAudioResource('Eastside.mp3');
connection = joinVoiceChannel({
channelId: msg.member.voice.channel.id,
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator
});
subscription = connection.subscribe(player);

    player.play(resource)`

you need to create a audio player, initialize a resource and subscribe the connection that youve created to the player then have the player play the resource

also you need to add const { joinVoiceChannel, createAudioPlayer, createAudioResource, NoSubscriberBehavior } = require('@discordjs/voice'); at the start

dont forget to add "GUILD_VOICE_STATES" to your intents

subtle granite

thx

dreamy pasture

Hi guys, I am trying to make a discord bot that plays music for my first time and I have been struggling for the past week with it crashing when playing songs from YouTube. I don't know why it crashes and after 2 days of stackoverflow I couldn't figure it out. I pasted my relevant code related to music and also the error bellow. If anyone has any idea I would appreciate it a lot.
code: https://pastebin.com/D4CS8dn5
error: https://pastebin.com/A1bzfFKj

tranquil lance

Hey, I have a question about a music (private) bot, if I add it to my server where I have some people, this bot becomes public even if it is only on my server?

haughty maple
dreamy pasture
haughty maple

Try play-dl. I never had any problems with it.
It is a common problem with ytdl-core and youtube-dl, If I remember correctly.

dreamy pasture

Alright, will try it right now. thanks!

left plinth

Hey! So is there NOT a way to destroy an audio resource

I can find nothing in the docs about it. I switch from a live radio stream to a file stream, and that works fine, but if I try and create another/new audio resource of the same live stream, it just doesn't work- AND the previous audio resource still runs even after a call to stop the player.

There's seriously 0 documentation about this and it's driving me nuts. If I can't kill a resource after making it, and it's a live stream, it just drains memory till it crashes

I suppose I could in theory just not use the built in function and make my own with axios but I'd rather not reinvent the wheel

left plinth

Ended up re-inventing the wheel because if you destroy it, it doesn't kill the edge cases, which you can't actually kill either without destroying the process pid's

icy maple

Could prob just do resource.playStream.destroy()

left plinth

That doesn't actually work either. I tried that first given the docs. It destroys the object, and stream to discord, but not the edge cases such as ffmpeg, and does a bunch of other weird nonsense I don't have time to look into

Half this library doesn't actually work it seems, or is poorly documented in the cases where it does work

candid ridge

Greetings, fellow human people friends, I'm in dire need of assistance

I'm trying to write a podcast bot where people from different servers can have a bot join their channel and relay audio from one source

The source is another person sitting in a voice channel in some private server, with the bot receiving the audio from the voice channel and relaying it to all the other voice channels

This is my approach:

  1. Creating an audio player
  2. Everyone who wants to listen to the podcast (from different servers) types -join, the bot joins the channel and the audio connection is subscribed to the audio player
  3. One person types -stream in a different server, the bot joins the channel and the audio receiver is subscribed to, and the opus stream is passed to the audio player
  4. ...
  5. profit??

Here's my code, as well:

const player = createAudioPlayer({
    behaviors: {
        noSubscriber: NoSubscriberBehavior.Play,
        maxMissedFrames: Math.round(config.maxTransmissionGap / 20),
    },
});

async function connectToChannel(channel) {
    const connection = joinVoiceChannel({
        channelId: channel.id,
        guildId: channel.guild.id,
        adapterCreator: channel.guild.voiceAdapterCreator,
        selfDeaf: false
    });
    try {
        await entersState(connection, VoiceConnectionStatus.Ready, 30_000);
        return connection;
    } catch (error) {
        connection.destroy();
        throw error;
    }
}

const client = new Client({ intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_VOICE_STATES'] });


function createListeningStream(receiver, userId, user) {
    const opusStream = receiver.subscribe(userId, {
        end: {
            behavior: EndBehaviorType.AfterInactivity,
            duration: 1000,
        },
    });
    
    player.play(createAudioResource(opusStream,
        {
            inputType: StreamType.Opus,
        },
    ));
}
client.on('messageCreate', async (message) => {
    if (!message.guild) return;
    if (message.content === '-stream') {
        const channel = message.member?.voice.channel;
        const connection = await connectToChannel(channel);
        if (connection) {
            const userId = message.author.id;

            const receiver = connection.receiver;
            
            receiver.speaking.on('start', (userId) => {
                console.log("You're speaking");
                createListeningStream(receiver, userId, client.users.cache.get(userId));
            });

            await message.reply('Listening!');
        } else {
            await message.reply('Join a voice channel and then try that again!');
        }
    }
    if (message.content === '-join') {
        const channel = message.member?.voice.channel;
        if (channel) {
            try {
                const connection = await connectToChannel(channel);
                connection.subscribe(player);
                await message.reply('Playing now!');
            } catch (error) {
                console.error(error);
            }
        } else {
            await message.reply('Join a voice channel then try again!');
        }
    }
});

Please let me know if I have the right idea or if I'm doing this terribly wrong
And if I'm not already doing something terribly wrong - is this going to scale at all?

upbeat fog

can someone modify this code and make it work?

pls.

subtle granite
icy maple
subtle granite

New error

icy maple

Error is straightforward

subtle granite

I'm not sure how to work those packages

icy maple

Those are all npm packages

I’m assuming you know how to install an npm package

subtle granite
icy maple

First one for best performance

Second one if you have trouble installing the first one and just want to test

subtle granite
icy maple

Just install it

subtle granite

I did same error

icy maple

Did the install succeed?

You didn’t see any red messages after it finished?

subtle granite
icy maple

Yea

subtle granite
icy maple

Run node -p require("@discordjs/voice").generateDependencyReport()

subtle granite

Do I need to require it?

icy maple

No

subtle granite
icy maple

Oops, wrap the thing in quotes

Also, it’s a node command, not npm

subtle granite

ik i tried both put what in quotes

icy maple

Run node -p 'require("@discordjs/voice").generateDependencyReport()'

subtle granite

@icy maple

icy maple

Is this a PS thing?

subtle granite

PS?

icy maple

PowerShell

subtle granite

no vs Terminal

icy maple

No, ur using PS

It says so at the beginning of the line

I’m talking about the quotes disappearing

Mb swap the single and double quotes

subtle granite
icy maple

Yea

"VS Terminal" is just any terminal on ur computer in the app

subtle granite
icy maple

Yea, it says sodium isn’t installed

subtle granite

i did install it

icy maple

Can also check with npm ls sodium

subtle granite
icy maple

What was the error?

subtle granite

@icy maple

icy maple

Run the command shown

Then try to install again

Are you running on ur computer, or on ur host?

subtle granite

computer

icy maple

Got confused bc you said you installed sodium, but showed a webpage, which I assume is ur host

subtle granite

correct

subtle granite
icy maple

What’s the error?

subtle granite
icy maple

Yea

subtle granite
icy maple Yea

it ran that fine when I ran NPm install again the=is was the error

icy maple

You need to install python v3

subtle granite

why python?

can i do that in the terminal?

icy maple

I think you can if you have chocolatey

subtle granite
icy maple

Yea

If there’s an option to add it to path, make sure to enable it

icy maple

Restart the terminal

Click on the trash icon in VSC, then the plus sign to create a new terminal

subtle granite

retrying

subtle granite
icy maple

Run python3 --version

subtle granite

Wait yes It did

all the right boxes are check marked in the install

@icy maple

icy maple

Where did it install to?

subtle granite
icy maple

You can use method 2 to check if it was added to ur path

subtle granite
icy maple

Try python --version

subtle granite
icy maple

Try installing sodium

subtle granite

Should I just try the other ones?

icy maple

Oh, it’s a different error

Install the vs build tools

subtle granite
icy maple

Still need to install the visual studio build tools

subtle granite

I got it to work that you for your help

dreamy geode

why is the problem

TypeError: channel.join is not a function
    at Client.<anonymous> (D:\0SYSTEM\Desktop\Helper\index.js:19:40)
    at Client.emit (node:events:402:35)
    at WebSocketManager.triggerClientReady (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketManager.js:383:17)
    at WebSocketManager.checkShardsReady (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketManager.js:366:10)
    at WebSocketShard.<anonymous> (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketManager.js:188:14)
    at WebSocketShard.emit (node:events:390:28)
    at WebSocketShard.checkReady (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketShard.js:474:12)
    at WebSocketShard.onPacket (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketShard.js:446:16)
    at WebSocketShard.onMessage (D:\0SYSTEM\Desktop\Helper\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
    at WebSocket.onMessage (D:\0SYSTEM\Desktop\Helper\node_modules\ws\lib\event-target.js:199:18)```

help please

@subtle granite

@icy maple

dusty needleBOT
dreamy geode

@spark marsh

fervent estuary

read the guide for v13 voice

v12 voice is not supported anymore

radiant ridge

why do i get the error cannot read property of undefined updateOverwrite

vcChannel.updateOverwrite(message.author.id, {
  CONNECT: true
})
pseudo forum
radiant ridge
radiant ridge
pseudo forum

ah shit

radiant ridge
upbeat fog

channelId:channel.id,
^

ReferenceError: channel is not defined

radiant ridge
radiant ridge
upbeat fog

put a space, but idk for sure

also channel is not defined so either you put message.channel.id or you define channel with let channel = "id of your channel"

upbeat fog

didnt fixed

radiant ridge
upbeat fog
radiant ridge
upbeat fog

wait lemme send you the code

madeby-codelyon

radiant ridge
upbeat fog

ok

@radiant ridge this is the code now no errors

but when i use .play song nothing happenes

radiant ridge
upbeat fog

stilll no errors

you got any kind of music bot code?

wide mirage

Uh

Why is everything null

fervent estuary

Do u have guild voice states intent?

subtle granite
wide mirage

Who coded this fck package??

there are 3+ memory leaks

Better to use lavalink

icy maple

How did you manage to create that many listeners multiple times?

I’ve never had that issue, and I don’t change the max listeners

wide mirage

Here is my code:

I don't see what's wrong

icy maple

Is this ts transpiled code?

I'd prefer to see the ts code

wide mirage
icy maple

You manually wrote all of that by hand?

wide mirage

ah no

icy maple

I want to see the code before it got transpiled into this

subtle granite
subtle granite
  [
    {
      status: 'connecting',
      adapter: [Object],
      subscription: [W],
      networking: [te]
    },
    {
      status: 'ready',
      adapter: [Object],
      subscription: [W],
      networking: [te]
    }
  ]
} AbortError: The operation was aborted
    at abortListener (node:events:838:14)
    at EventTarget.<anonymous> (node:events:874:47)
    at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:562:20)
    at EventTarget.dispatchEvent (node:internal/event_target:504:26)
    at abortSignal (node:internal/abort_controller:97:10)
    at AbortController.abort (node:internal/abort_controller:122:5)
    at wt (C:\Users\vadle\OneDrive\Documentos\DISCORD\TESTING\PASSION-TESTING\node_modules\@discordjs\voice\dist\index.js:9:680)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async DisTubeVoice.join (C:\Users\vadle\OneDrive\Documentos\DISCORD\TESTING\PASSION-TESTING\node_modules\distube\dist\core\voice\DisTubeVoice.js:103:13)
    at async QueueManager.create (C:\Users\vadle\OneDrive\Documentos\DISCORD\TESTING\PASSION-TESTING\node_modules\distube\dist\core\manager\QueueManager.js:25:13) {
  code: 'ABORT_ERR'
}```

hi, help please
what i can do with this?
abstract acorn

How can I reuse an AudioPlayer. What I'm currently doing is to destroy every AudioPlayer and AudioResource and removing them from reference, which maybe is not good?

another one, how can I make the bot disconnect after a given time of inactivity without using this settimeout mess

(please mention me when anyone answers)

another one, how can I fix this memory leak? (this part is from the example code so ...)

icy maple

Only create the disconnected listener once

abstract acorn

oh

icy maple

Error says it’s getting created alot of times

abstract acorn

i see, i put this in the play function, which will just recreating this listener a bunch of times

should've put this at the connection creation zone

icy maple

Yea, that sounds more reasonable

abstract acorn
icy maple

Players are reusable, just keep a reference to it

abstract acorn

so, when the resource ends, just .stop() the player, remove resource reference, then .play() a new resource into the AudioPlayer?

patent hamlet

Help

After v13 i got eror


	const connection = await channel.join().catch((err) => {
	                                 ^
TypeError: channel.join is not a function
green vigil

Is a connection seeing how many places your bot is connected into different server vcs?

Nevermind

granite geyser
subtle granite

nope