DiscordJS music bot disconnects immediately after starting to play the song - javascript

I try to play a Youtube URL but when it starts playing it stops after 1 second. mp3 files are working fine, it just doesn't work when I try to play Youtube URLs.
Here is my Code:
case 'play':
{
const Channel = ['903334978199388271'];
for (const channelId of Channel) {
joinChannel(channelId);
}
function joinChannel(channelId) {
Client.channels
.fetch(channelId)
.then((channel) => {
const VoiceConnection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
VoiceConnection.subscribe(player);
player.play(
createAudioResource(
ytdl('https://www.youtube.com/watch?v=sPPsOmQh76A'),
),
);
})
.catch(console.error);
}
}
break;

I had the same problem before, the problem is ytdl-core, so you can use ytdl-core-discord instead. Here is an example:
const { Client, Intents, MessageEmbed } = require('discord.js')
const ytdl = require('ytdl-core-discord')
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
StreamType
} = require('#discordjs/voice')
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_VOICE_STATES /// <= Don't miss this :)
]
});
var prefix = '!'
client.on('ready', async () => {
console.log('Client is Ready...');
});
client.on('messageCreate', async (message) => {
if (message.content.trim().toLocaleLowerCase() === prefix + 'play') {
const channel = client.channels.cache.get('Channel ID Here')
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guildId,
adapterCreator: channel.guild.voiceAdapterCreator
});
const player = createAudioPlayer();
const resource = createAudioResource(await ytdl('https://www.youtube.com/watch?v=sPPsOmQh76A'), { inputType: StreamType.Opus });
player.play(resource);
connection.subscribe(player);
}
});
client.login('Bot Token Here!');

Related

Discord.js audio player doesn't play audio

I have been trying to create an audioPlayer with the Discord.js library. I created a /join command that joins my bot to the voice channel and then plays a local audio file.
const { SlashCommandBuilder, ChannelType } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('#discordjs/voice')
const path = require('node:path');
const player = createAudioPlayer();
module.exports = {
data: new SlashCommandBuilder().setName('join').setDescription('Join to a voice channel').addChannelOption((option) =>
option.setName('channel').
setDescription('The channel to join').
setRequired(true).
addChannelTypes(ChannelType.GuildVoice)
),
async execute(interaction) {
const voiceChannel = interaction.options.getChannel('channel');
try {
const voiceConnection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
})
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
player.on('error', error => {
console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`);
});
let resource = createAudioResource('"C:\\Users\\gerso\\Documents\\CS-P\\discord-bot\\audio\\track.mp3"', { inlineVolume: true })
player.play(resource)
const subscription = voiceConnection.subscribe(player)
if(subscription) {
setTimeout(() => subscription.unsubscribe(), 15_000)
}
} catch (error) {
console.error(error)
}
await interaction.reply('player')
},
};
When I use the command on discord the bot joins the voice channel but it doesn't play any audio and the console doesn't show any error.
Note: I have already installed ffmpeg-static in my project.

My discord.js v13 music bot stops playing after about 30 minutes

I recently coded a discord music bot which plays a random mp3 file from a folder 24/7 in a voice channel. After some time it just stops playing and I don't know why. Discord reset my token because it connected itself to Discord over 1000 times within a few seconds. Does anyone know why that happens? Here is my code.
const { Client, Intents, discord } = require('discord.js');
const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES ]});
const { joinVoiceChannel } = require('#discordjs/voice');
const { createAudioPlayer, AudioPlayerStatus, createAudioResource } = require('#discordjs/voice');
const config = require("./config.json")
const fs = require("fs")
client.on("ready", () => {
console.log(`${client.user.tag}`)
const channel = client.channels.cache.get(config.channel)
const player = createAudioPlayer();
player.on(AudioPlayerStatus.Playing, () => {
console.log("Started playing!")
})
player.on("error", error => {
console.log(error)
})
player.addListener("stateChange", (oldOne, newOne) => {
if (newOne.status == "idle") {
startRandomSong()
}
});
startRandomSong()
function startRandomSong(){
let folder = fs.readdirSync("./songs")
let rn = Math.floor(Math.random() * (folder.length - 1 + 1)) + 1;
let counter2 = 0
folder.forEach(song => {
counter2 += 1
if(counter2 === rn){
console.log(song)
const resource = createAudioResource(`./songs/${song}`);
player.play(resource)
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
volume: 1.0
});
const subscription = connection.subscribe(player)
}
})
}
})
client.login(config.token)

Can you stream Audio from a URL in a discord.js resource

How do I play audio from a url with discord.js v13.
I used this code and it didn't work.
const connection = joinVoiceChannel({
channelId: channel_id.id,
guildId: guild_id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const resource = createAudioResource('http://radioplayer.kissfmuk.com/live/')
player.play(resource)
connection.subscribe(player)
I have activated all Intents, the bot shows a green circle but no audio is playing.
Do you have an Idea how it works?
A link of which you are trying to make a resource of, has to return an audio file.
Live audio broadcasts will not work with your current code.
If the url gives you E.g. an .mp3 file, the code should work.
Example Function:
const Discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES] });
const config = require('./config/config.json');
const { joinVoiceChannel, createAudioPlayer, NoSubscriberBehavior, createAudioResource, AudioPlayerStatus, VoiceConnectionStatus, entersState } = require('#discordjs/voice');
const { join } = require('path');
client.once('ready', () => {
console.log(config.onlineMessage);
const channels = client.guilds.cache.find(f => f.name==="<Server Name>").channels;
JoinChannel(channels.cache.find(r => r.name === "<Channel Name>"), './background.mp3', 0.025);
});
client.login(config.token);
function JoinChannel(channel, track, volume) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guildId,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
resource = createAudioResource(join(__dirname, track), { inlineVolume: true });
resource.volume.setVolume(volume);
connection.subscribe(player);
connection.on(VoiceConnectionStatus.Ready, () => {console.log("ready"); player.play(resource);})
connection.on(VoiceConnectionStatus.Disconnected, async (oldState, newState) => {
try {
console.log("Disconnected.")
await Promise.race([
entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
entersState(connection, VoiceConnectionStatus.Connecting, 5_000),
]);
} catch (error) {
connection.destroy();
}
});
player.on('error', error => {
console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`);
player.play(getNextResource());
});
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
player.on('idle', () => {
connection.destroy();
})
}
The answer was pretty simple, I just need to subscribe to the connection before I play the resource!
const connection = joinVoiceChannel({
channelId: channel_id.id,
guildId: guild_id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const resource =
createAudioResource('https://streams.ilovemusic.de/iloveradio8.mp3', {
inlineVolume: true
})
const player = createAudioPlayer();
connection.subscribe(player)
player.play(resource)

discord.js / ytdl-core play command

this is my second question today. I'm using discord.js v13. Earlier I looked into finding out how to make audio play from the bot, and now I am attempting to make a queue work for my discord.js bot. My problem is getting the queue defined from index.js correctly. I will provide the error log along with my code.
error logs: https://i.imgur.com/ScDcJHK.jpg
index.js
const fs = require('fs');
const { Collection, Client, Intents } = require('discord.js');
const Levels = require('discord-xp');
require('dotenv').config();
const client = new Client({
presence: {
status: 'idle',
afk: false,
activities: [{
name: 'The Official Xontavs',
type: 'WATCHING'
}],
},
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MEMBERS]
});
client.queue = new Map();
const mongoose = require('./database/mongoose.js');
Levels.setURL(`mongodb+srv://discordbot:${process.env.PASS}#bot.z8ki0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`);
['aliases', 'commands'].forEach(x => client[x] = new Collection());
['command', 'event'].forEach(x => require(`./handlers/${x}`)(client));
mongoose.init();
client.login(process.env.CLIENT_TOKEN); // SECRET TOKEN
play.js
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const { getVoiceConnection, joinVoiceChannel, AudioPlayerStatus, createAudioResource, getNextResource, createAudioPlayer, NoSubscriberBehavior } = require('#discordjs/voice');
const { createReadStream} = require('fs');
module.exports = {
name: "play",
category: "music",
description: "plays a song",
usage: "<id | mention>",
run: async (client, message, args, queue) => {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You are not in a voice channel.');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT', 'SPEAK')) return message.channel.send('You do not have the correct permissions');
if(!args.length) return message.channel.send('You need to send the second argument');
const server_queue = queue.get(message.guild.id);
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voiceChannel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('Error connecting');
throw err;
}
} else {
server_queue.songs.push(song);
return message.channel.send(`**${song.title}** added to queue.`);
}
//audioPlayer.play(createAudioResource(stream, {seek: 0, volume: 1}))
//audioPlayer.on(AudioPlayerStatus.Idle, () => {
//audioPlayer.stop();
//connection.destroy();
//message.channel.send('Leaving VC');
//});
}
}
const video_player = async (guild, song, queue) => {
const song_queue = queue.get(guild.id);
if(!song) {
connection.destroy();
queue.delete(guild.id);
return;
}
const audioPlayer = createAudioPlayer();
song_queue.connection.subscribe(audioPlayer);
const stream = ytdl(song.url, { filter: 'audioonly' });
audioPlayer.play(createAudioResource(stream, {seek: 0, volume: 1}))
audioPlayer.on(AudioPlayerStatus.Idle, () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
song_queue.text_channel.send(`Now playing **${song.title}**`)
}
messageCreate.js (if needed)
const del = require('../../functions.js');
const Levels = require('discord-xp');
require('dotenv').config();
const prefix = process.env.PREFIX;
const queue = new Map();
module.exports = async (Discord, client, message) => {
if (message.author.bot || !message.guild) return;
const randomXP = Math.floor(Math.random() * 14) + 1; //1-15
const hasLeveledUP = await Levels.appendXp(message.author.id, message.guild.id, randomXP);
if (hasLeveledUP) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send(`${message.member} is now level ${user.level}.`);
}
//const args = message.content.startsWith(prefix) ? message.content.slice(prefix.length).trim().split(/ +/g) : message.content.replace(/[^\s]*/, '').trim().split(/ +/g);
const args = message.content.slice(prefix.length).trim().split(" ");
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd) || client.commands.find(c => c.aliases?.includes(cmd));
if (command) {
command.run(client, message, args, queue);
}
}
Any help is appreciated because I'm really not smart and I'm still trying to learn how all this stuff works, especially with discord.js v13
In
video_player(message.guild, queue_constructor.songs[0]);
You only put two parameters and as you said in the comments, you only had to change it to this to fix your problem
video_player(message.guild, queue_constructor.songs[0], queue, audioPlayer)

Discord js doesn't plays audio anymore

I had a base discordjs code that could play 2 audio files, leave and join voice channels, but I did created a new file with this code followed from a youtube video:
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
descreption: 'Play',
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.send('PALI! Egy voice channelben bent kéne lenne, már nemazé!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('Player')) return message.reply('Kéne rang is nem gondolnád?, hogy a bánat egyeki a lelked!');
if (!args.length) return message.channel.reply('KÖZÖLDNÉDHOGYMIAKUKITAKARSZ?? (Need more argumets)');
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: 100 })
on('finish', () => {
voiceChannel.leave();
});
await message.reply(`Most játszom: ***${video.title}$***`)
}
else {
message.channel.send('Nem találtam videót.')
}
}
}
Then I tried to imploment it into my other js file, but after I did it it gave me errors so I gave it up and deleted all that stuff, but now the original code just doesn't wants to play audio, it doesn't gives me errors or anything, I tried everthing I could but I couldn't solve it. Any solutions?
Here's the code:
const Discord = require('discord.js');
const client = new Discord.Client();
//const ytdl = require('ytdl-core');
//const ytSearch = require('yt-search');
var prefix = ';';
client.login('CENSORED');
client.on('ready', () =>{
console.log('\n ----------WELCOME TO ADY STUDIOS AUTOMATIC------------')
})
client.on('message', async message => {
if (message.content === ';join') {
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
} else {
message.reply('You need to join a voice channel first!');
}
}
if(message.content === ';leave'){
message.guild.me.voice.channel.leave();
}
if (message.content === ';coconut') {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('./coconut.m4a');
}
if (message.content === ';roll'){
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('./rickroll.m4a');
}
});
{ "dependencies": { "#discordjs/opus": "^0.3.2", "discord.js": "^12.3.1", "ffmpeg-static": "^4.2.7", "mysql": "^2.18.1", "opusscript": "0.0.7", "request": "^2.88.2", "ytdl-core": "^4.2.1" } } install disc should be work

Categories

Resources