voiceChannel.join() isn't a function node v16 discord.js - javascript

I made a bot that plays music. I upgraded to NodeJS v16.6.1 and voiceChannel.join doesn't work anymore.
I already tried using const { voiceChannel } = require('#discord.js/voice'); but it just says module not found.
Code:
const ytdl = require("ytdl-core");
const ytSearch = require("yt-search");
module.exports = {
name: 'play',
description: 'Joins and plays a video from youtube',
async execute(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 neccesary permissions');
if (!permissions.has("SPEAK")) return message.channel.send('You dont have the neccesary permissions');
if (!args.length) return message.channel.send('Define Video');
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(`Now Playing **${video.title}**`)
} else {
message.channel.send('No videos found');
}
}
}```

As the error says, voiceChannel#join is not, in fact, a function. While it did exist on Discord.js v12, which I assume you were using before updating your Node.js version, note that it is nowhere to be found in the Discord.js v13 documentation on VoiceChannel. Instead, you are to migrate to #discordjs/voice, whose joinVoiceChannel function can be used as a replacement.

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.

How to implement a queue array for music bot

I'm an amateur and I have this music bot setup but not sure how to implement a queue feature which would add videos in an array to be played after one song is finished. Do I have to reformat the code so that there is a queue function before everything or is there a simple fix?
Below is my code,
module.exports = {
name: 'play',
description: 'Joins and plays video from youtube',
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if(!voiceChannel) return message.channel.send('Join a channel to play a song');
const permissions = voiceChannel.permissionsFor(message.client.user);
if(!permissions.has('CONNECT')) return message.channel.send('You dont have permission to use this function');
if(!permissions.has('SPEAK')) return message.channel.send('You dont have permission to use this function');
if(!args.length) return message.channel.send('You need to send a second argument');
//Set up play function for link
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('Now Playing Link')
return
}
//Set up play function for youtube search w/ keywords
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(`Now Playing ***${video.title}*** ${video.duration}*** ${video.thumbnail}`)
} else {
message.channel.send('No video results found.');
}
}
}
module.exports = {
name: 'play',
description: 'Joins and plays video from youtube',
queues: {},
voiceConnections: {},
execute() {
if (!this.voiceConnections[guildId]) {
// setup voiceConnections[guildId]
this.voiceConnections[guildId].on('finish', () => {
this.voiceConnections[guildId].play(this.queues[guildId].pop())
}
}
if (track already playing in voice connection) {
this.queues[guildId].push(newTrackDetails);
} else {
// play the track
}
}
}
Some pseudocode. Idea: Each guild has its own queue and voice channel connection. The queue object format looks something like {'guildId1': [...queue tracks details here]}

When I use the -play command,I get an "Uncaught SyntaxError SyntaxError" [duplicate]

This question already has an answer here:
Discord.js v12 code breaks when upgrading to v13
(1 answer)
Closed 11 months ago.
I'm trying to make a discord music bot and when I use the -play command which is the only one I've created so far it gives me this error is console
"(node:20336) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)"
which when I do, I get this
Uncaught SyntaxError SyntaxError: Unexpected identifier
at (program) (<eval>/VM46947595:1:8)
as a result, I am very confused
also here's the code
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const { Message } = require('discord.js');
const queue = new Map();
modulue.exports = {
name: 'play',
aliases:['skip', 'stop', 'pause', 'resume'],
cooldown: 0,
description: 'dat jazz baby',
async execute(Message, args, cmd, client, Discord){
const voice_channel = Message.member.voice.channel;
if (!voice_channel) return message.channel.send('you ain\'t in a voice channel dummy');
const permissions = voice_channel.permissionsFor(Message.client.user);
if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) return message.channel.send('can\'t talk');
const server_queue = queue.get(Message.guild.id);
if (Message.content === prefix + play){
if (!args.length) return message.channel.send('no args. You keep this up and Mark Zukerberg could die of ligma');
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 > 0) ? videoresult.videos[0] : null;
}
const song_info = await video_finder(args.join(' '));
if (video){
song = title; video.title, url; video.url }
else {
return Message.channel.send('damn so no maidens or vidjas');
}
}
if (!server_queue){
const queue_constructor = {
textChannel: message.channel,
voiceChannel: voice_channel,
connection: null,
songs: [],
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push.push(song)
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
play(message.guild, queue_constructor.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
message.channel.send('I fell and I can\'t get up\(try again\)');
throw err; // this will throw the error to the console
}
} else {
server_queue.song.push(song);
return message.channel.send(`${song.title} has been added to the queue`);
}
}
}
}
const video_player = async (guild, song) => {
const server_queue = queue.get(guild.id);
if (!song) {
server_queue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, {filter: 'audioonly'});
song_queue.connection.play(stream, { Seek: 0, volume: 0.5})
.on(finish, () => {
server_queue.songs.shift();
video_player(guild, server_queue.songs[0]);
})
}
I didn't exactly expect it to work, but seeing as I'm pretty new to coding I'm kinda helpless
The error shown in your message is not an error, it's a module DeprecationError. I'm pretty sure that's not causing the problem. The real error is the SyntaxError.
Is your code in Typescript (TS)?
(ytdl-core is a node js dependency, so you have to use require unless you are using TS)

undefined song when I run the play command

I'm trying to build a music discord bot with yt-search but it gives me undefined whenever I play the song and it joins the voice channel without playing the song. I'm trying to use yt-search to find the video I want or only the URL then pass it to ytdl to run it with the URL given from yt-search but I think I'm wrong in some points. I don't know where, could you please fix my code ?
Image to show the problem:
My code:
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const ytdl = require("ytdl-core");
const yts = require("yt-search");
const client = new Discord.Client();
const queue = new Map();
client.once("ready", () => {
console.log("Ready!");
});
client.once("reconnecting", () => {
console.log("Reconnecting!");
});
client.once("disconnect", () => {
console.log("Disconnect!");
});
client.on("message", async message => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const serverQueue = queue.get(message.guild.id);
if (message.content.startsWith(`${prefix}play`)) {
execute(message, serverQueue);
return;
} else if (message.content.startsWith(`${prefix}skip`)) {
skip(message, serverQueue);
return;
} else if (message.content.startsWith(`${prefix}stop`)) {
stop(message, serverQueue);
return;
} else {
message.channel.send("You need to enter a valid command!");
}
});
async function execute(message, serverQueue) {
const args = message.content.split(" ");
const voiceChannel = message.member.voice.channel;
if (!voiceChannel)
return message.channel.send(
"You need to be in a voice channel to play music!"
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"I need the permissions to join and speak in your voice channel!"
);
}
const r = await yts(args[1,2]);
const video = r.videos.slice( 0, 1 );
console.log(video);
const songInfo = await ytdl.getInfo(video.url);
const song = {
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url,
};
if (!serverQueue) {
const queueContruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(message.guild.id, queueContruct);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
play(message.guild, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
}
} else {
serverQueue.songs.push(song);
return message.channel.send(`${song.title} has been added to the queue!`);
}
}
function skip(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"You have to be in a voice channel to stop the music!"
);
if (!serverQueue)
return message.channel.send("There is no song that I could skip!");
serverQueue.connection.dispatcher.end();
}
function stop(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"You have to be in a voice channel to stop the music!"
);
if (!serverQueue)
return message.channel.send("There is no song that I could stop!");
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
}
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
const dispatcher = serverQueue.connection
.play(ytdl(song.url))
.on("finish", () => {
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`Start playing: **${song.title}**`);
}
client.login(token);
There are two errors. I'm not sure what you think args[1,2] is but it's the same as args[2] which is the third item of the args array. By reading your code, I think you want to use a string here, the search term. By removing the first item (the command) from the args array and joining the rest of them, you will receive a string you can use as keywords. Check out the example below:
const message = { content: '!play some music I want'}
const args = message.content.split(' ')
console.log({ args })
// => ["!play", "some", "music", "I", "want"]
console.log({ 'args[1, 2]': args[1, 2] })
// => "music"
console.log({ 'search': args.slice(1).join(' ') })
// => "some music I want"
The other error is that await yts(query) returns an array of results and when you define the video variable you use r.videos.slice(0, 1). The .slice() method returns a new array with the first item of r.videos.
As the video variable is an array, video.url is undefined. You could fix it by using the first item instead as it will have a url property. You should also check if there are any search results.
Check out the updated code below:
async function execute(message, serverQueue) {
const args = message.content.split(' ');
const voiceChannel = message.member.voice.channel;
if (!voiceChannel)
return message.channel.send(
'You need to be in a voice channel to play music!',
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
return message.channel.send(
'I need the permissions to join and speak in your voice channel!',
);
}
const query = args.slice(1).join(' ');
const results = await yts(query);
if (!results.videos.length)
return message.channel.send(`No results for \`${query}\``);
const firstVideo = results.videos[0];
const songInfo = await ytdl.getInfo(firstVideo.url);
const song = {
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url,
};
console.log(song);
if (!serverQueue) {
// ...
// ...

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