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
Related
I'm new to coding in general so expect nooby behaviour.
i try to make discord music bot and it cant join voice chat and when i type node .an error pops up
i dont know where put import, i tried everywhere but i doesnt work, ping and youtube command work only play doesnt
This is the main code:
const { Client, Intents, DiscordAPIError } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const prefix = '!';
const fs = require('fs');
const Discord = require('discord.js');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Musicbot is online!');
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
} else if (command == 'youtube'){
client.commands.get('youtube').execute(message, args);
} else if (command == 'play'){
client.commands.get('play').execute(message, args);
} else if (command == 'leave'){
client.commands.get('leave').execute(message, args);
}
});
client.login('token');
https://stackoverflow.com/questions/ask#
This is the play command code:
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
async execute(message, args){
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('Musisz być na kanale głosowym by użyć tej komendy!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('Nie masz odpowiednich uprawnień');
if (!permissions.has('SPEAK')) return message.channel.send('Nie masz odpowiednich uprawnień');
if (!args.length) return message.channel.send('You need to send the second argument!');
import { joinVoiceChannel } from "#discordjs/voice";
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
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('Nie znaleziono wideo');
}
}
}
Pls help
Try replacing import { joinVoiceChannel } from "#discordjs/voice"; with const { joinVoiceChannel } = require("#discordjs/voice");.
This error occurred because you tried using es modules import inside commonjs. You can however use dynamic imports on commonjs if needed.
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!');
I want to import joinVoiceChannel from discordjs/voice, but it says
SyntaxError: Cannot use import statement outside a module
That's because I'm using .cjs file, if I'm using .js file then nothing will work.
Can anybody help me how to connect DiscordBot to voice channel, I can ping him but can not connect him.
main.js
import DiscordJS, { Intents } from 'discord.js'
import dotenv from 'dotenv'
import { createRequire } from "module";
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
const prefix = '!';
const require = createRequire(import.meta.url);
const fs = require('fs');
client.commands = new DiscordJS.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.cjs'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Mariachi is online!');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
client.commands.get('ping').execute(message, args);
} else if (command === 'play') {
client.commands.get('play').execute(message, args);
} else if (command === 'leave') {
client.commands.get('leave').execute(message, args);
}
});
client.login(process.env.TOKEN);
play.cjs
import { joinVoiceChannel } from "#discordjs/voice";
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 correct permissions');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissions');
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 joinVoiceChannel.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 joinVoiceChannel.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');
}
}
}
package.json
{
"name": "discordbot",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#discordjs/opus": "^0.7.0",
"#discordjs/voice": "github:discordjs/voice",
"discord.js": "^13.3.1",
"dotenv": "^10.0.0",
"ffmpeg-static": "^4.4.0",
"yt-search": "^2.10.2",
"ytdl-core": "^4.9.1"
},
"type": "module"
}
These are the commands I've found on StackOverflow
import { joinVoiceChannel } from "#discordjs/voice";
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
.cjs files are CommonJS. These need require rather than the import keyword
const { joinVoiceChannel } = require("#discordjs/voice")
const ytdl = require('ytdl-core')
const ytSearch = require('yt-search')
And since you have "type": "module" in package.json, the .js files will need the import keyword
const { joinVoiceChannel } = require('#discordjs/voice');
use this above your module.exports and it should start working, but i am having a problem with audio after that, it will join the call but not play any audio
my error code is connection.play(stream, {seek: 0, volume: 1, type: "opus"})
ReferenceError: connection is not defined
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)
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.