Play local music files using djs v13 - javascript

I know a lot of people already asked how to play music from youtube in discord voice channel, but I can't find anything about playing local files on djs version 13.2.0!
I tried using this code:
const { createReadStream } = require('fs');
const { join } = require('path');
const { createAudioResource, StreamType, createAudioPlayer, joinVoiceChannel } = require('#discordjs/voice');
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
message.guild.me.voice.setRequestToSpeak(true);
let resource = createAudioResource(join(../music/audio.mp3, 'audio.mp3'));
const player = createAudioPlayer();
player.play(resource);
When I try to eval() it - my bot joins the channel (stage channel) and says everything worked, but it's not playing anything! How can I make my bot play local music files in stage channel?

There are 2 problems here.
Firstly, the path is completely wrong. It is not a string and even if you try to change it to a string it will be invalid as the first argument ends with audio.mp3, and the second one is audio.mp3. Use this path instead:
let resource = createAudioResource(join('..', 'music', 'audio.mp3'));
Secondly, you are playing audio in the player, but not the voice connection. You must subscribe to the audio player.
This should be the final code:
const player = createAudioPlayer()
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
}).subscribe(player)
message.guild.me.voice.setRequestToSpeak(true);
let resource = createAudioResource(join('..', 'music', 'audio.mp3'));
player.play(resource)

Related

Play Audio when Joining a Voice Channel DiscordJS v13

I've been trying all night to get a simple task working, but yet I am not able to figure out how.
Basically what I achieved is that the Bot joins a Voice Channel when somebody joins, play an Audio file and that's it. What I want to achieve is that it joins when somebody joins, play the Audio file and then leave and as when somebody leaves the voice chat. It's supposed to join the voice chat, play a different audio file and then leave again.
All in all seems easy, but I've been banging my head against it with no results. If possible I would also like to have the code be tidy there aswell.
Here is the code (using discord.js v13):
client.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.channelId === null) {
console.log("Joined")
//playAudio(newState.channelId, './files/bruh.mp3')
const connection = joinVoiceChannel({
channelId: newState.channelId,
guildId: newState.guild.id,
adapterCreator: newState.guild.voiceAdapterCreator,
})
console.log(newState.guild.voiceAdapterCreator)
const player = createAudioPlayer();
connection.subscribe(player)
const resource = createAudioResource('./files/riff.mp3')
player.play(resource)
} else if (newState.channelId === null) {
console.log("Left")
}
});
Edith: With when somebody joins. I mean when somebody joins Voice Chat.
After a Good Nights sleep I was able to figure it out, for anyone corious, here is the code!
var isReady = true
function playAudio(chID, guID, adpID, audioFile) {
isReady = false
const connection = joinVoiceChannel({
channelId: chID,
guildId: guID,
adapterCreator: adpID,
})
const player = createAudioPlayer();
connection.subscribe(player)
const resource = createAudioResource(audioFile)
player.play(resource)
player.on(AudioPlayerStatus.Idle, () => {
connection.destroy()
});
isReady = true
}

discord.js - Audio Bot creation, only plays sound clips that are less than 50KB

Goal
I want to be able to play longer audio files using my discord bot.
Working Code
Using Discord.js and Node.js, I have created a discord bot.
So far my code is able to join a voice call and can only play very short audio files <50KB. Which is great, besides the short file part.
Testing Process: to test different audiofiles, I simply replace the path, during the resource creation, to be the desired audio file.
I have tested 5 short files and it works great! But the three long files >~75KB, that I have, do not work. No errors pop up, it just doesn't play.
const { SlashCommandBuilder } = require('#discordjs/builders');
const { joinVoiceChannel } = require('#discordjs/voice');
const { createAudioPlayer , createAudioResource, StreamType} = require('#discordjs/voice');
const { createReadStream } = require('node:fs');
const { join } = require('node:path');
const { VoiceConnectionStatus, AudioPlayerStatus } = require('#discordjs/voice');
module.exports = {
data: new SlashCommandBuilder()
.setName('jensenrage')
.setDescription('Joins channel and plays jensen\'s rage'),
async execute(interaction){
const { joinVoiceChannel } = require('#discordjs/voice');
const channel = interaction.member.voice.channel
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const resource = createAudioResource(createReadStream(join(__dirname, '../AudioFiles/short.mp3')), {
inlineVolume : true
});
resource.volume.setVolume(0.2);
const player = createAudioPlayer();
connection.subscribe(player);
player.play(resource)
await interaction.reply( "Enjoy!")
}
}
I have looked into why this is, but most of the answers do not explain why the short files play but the long ones do not.
I am assuming that this line is the the issue, but unsure why.
const resource = createAudioResource(createReadStream(join(__dirname, '../AudioFiles/short.mp3')), {
inlineVolume : true
});
These are my dependencies
--------------------------------------------------
Core Dependencies
- #discordjs/voice: 0.8.0
- prism-media: 1.3.2
- prism-media: 1.3.2
Opus Libraries
- #discordjs/opus: 0.5.3
- opusscript: 0.0.8
Encryption Libraries
- sodium: not found
- libsodium-wrappers: 0.7.10
- tweetnacl: not found
FFmpeg
- version: 4.4.1-essentials_build-www.gyan.dev
- libopus: yes

Cannot read properties of undefined (reading 'join') Discord.js

im trying to create my discord music bot, but when i run it. It cannot join my voiceChannel, returning this error: channel_info.channelId.join is not a function. Below, my code:
const Discord = require('discord.js');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };
const botToken = 'mytoken';
bot.login(botToken);
bot.on('ready', () => {
console.log('to olain');
});
bot.on('message', msg => {
if (msg.author.bot) {
return;
}
if (msg.content.toLowerCase().startsWith(';p')) {
const channel_info = msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
if (channel_info.channelId == null) {
return console.log('Canal não encontrado!');
}
console.log('Canal encontrado');
channel_info.channelId.join().then(connection => {
const stream = ytdl('https://www.youtube.com/watch?v=BxmMGnvvDCo', { filter: 'audioonly' });
const DJ = connection.playStream(stream, streamOptions);
DJ.on('end', end => {
channel_info.channelId.leave();
});
})
.catch(console.error);
}
});
There are several issues in this code. Even if we fix some of these issues, this code will still not work due to differences between discord.js v12 and v13. Let's get started.
Issue #1
This is not one of the core issues causing your code to not work, but it's something useful to consider. You are doing this to get the voice state of the message author:
msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
When you could easily do the exact same thing in a much shorter, less-likely-to-produce-errors way:
msg.member.voice;
Issue #2
Now this is a core issue causing your code to not work. In fact, it is causing the error in your question. You are trying to do:
channel_info.channelId.join();
That does not make sense. You are trying to join a channel ID? channelId is just a String of numbers like so: "719051328038633544". You can't "join" that String of numbers. You want to join the actual channel that the member is in, like so:
channel_info.channel.join();
Issue #3
Based on how you are using a channelId property instead of channelID, I assume you are on discord.js v13. Voice channels do not have a .join() method on v13; in fact, discord.js v13 has no support for joining or playing audio in voice channels. You must install the discord.js/voice package in order to join a voice channel in discord.js v13. This is critical. Even if you fix the above two issues, you must solve this third issue or your code will not work (unless you downgrade to discord.js v12).

Bot won't join voice channel [duplicate]

I recently installed Discord.js 13.1.0 and my music commands broke because, apparently, channel.join(); is not a function, although I have been using it for months on 12.5.3...
Does anybody know a fix for this?
Some parts of my join command:
const { channel } = message.member.voice;
const voiceChannel = message.member.voice.channel;
await channel.join();
It results in the error.
Discord.js no longer supports voice. You need to use the other package they made (#discordjs/voice). You can import joinVoiceChannel from there.
//discord.js and client declaration
const { joinVoiceChannel } = require('#discordjs/voice');
client.on('messageCreate', message => {
if(message.content === '!join') {
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
}
})

If bot is in the channel, ignore the join command

I'm making a discord bot and I came across a problem, if I type $join into chat, I want the bot to join the voice channel I'm in and play a sound. That is working but when the bot is already in the voice channel and I type $join again, it just plays the sound again and I want it to play the sound only once when it connects to the channel. I tried to solve it with some if, else and return functions but it didn't work, thanks for help.
This is my code working like I described.
message.delete({
timeout: 5000
})
const voiceChannel = message.member.voice.channel
if (voiceChannel) {
const connection = await voiceChannel.join()
const dispatcher = connection.play("./sounds/xxx.mp3")
dispatcher.setVolume(0.5)
} else {
message.reply("you need to be in a voice channel!").then(message => {
message.delete({
timeout: 5000
})
})
}
You need to check whether the channel of your voice connection is the same you're about to join: if so, you don't need to do anything (you're already in the channel), otherwise you join, make the sound etc...
You can do this with VoiceConnection.channel
Here's how I would do it:
const voiceChannel = message.member.voice.channel
if (voiceChannel) {
// Check if any of the ALREADY EXISTING connections are in that channel, if not connect
if (!client.voice.connections.some(conn => conn.channel.id == voiceChannel.id)) {
const connection = await voiceChannel.join()
const dispatcher = connection.play("./sounds/xxx.mp3")
dispatcher.setVolume(0.5)
} // else: you're already in the channel
} else {
let m = await message.reply("You need to be in a voice channel!")
m.delete({ timeout: 5000 })
}

Categories

Resources