I'm doing a Discord bot, and having trouble connecting bot to voice channel, any suggestions? - javascript

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

Related

SyntaxError: Cannot use import statement outside a module discord.js

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.

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

How to make loop command in discord.js?

I'm trying to make a discord.js bot that plays music and runs the looping command.
I'm now stuck trying to use it as it's not working.
My code:
Server.js
const http = require('http');
const express = require('express');
const app = express();
app.get("/", (request, response) => {
response.sendStatus(200);
});
app.listen(process.env.PORT);
setInterval(() => {
http.get(`http://rgrap.glitch.me/`);
}, 280000);
// ßá ÇáÈßÌÇÊ Çáí ããßä ÊÍÊÌåÇ Ýí Çí ÈæÊ
const { Client, RichEmbed } = require("discord.js");
var { Util } = require('discord.js');
const {TOKEN, YT_API_KEY, prefix, devs} = require('./config')
const client = new Client({ disableEveryone: true})
const ytdl = require("ytdl-core");
const canvas = require("canvas");
const Canvas = require("canvas");
const convert = require("hh-mm-ss")
const fetchVideoInfo = require("youtube-info");
const botversion = require('./package.json').version;
const simpleytapi = require('simple-youtube-api')
const moment = require("moment");
const fs = require('fs');
const util = require("util")
const gif = require("gif-search");
const opus = require("node-opus");
const ms = require("ms");
const jimp = require("jimp");
const { get } = require('snekfetch');
const guild = require('guild');
const dateFormat = require('dateformat');//npm i dateformat
const YouTube = require('simple-youtube-api');
const youtube = new YouTube('AIzaSyAdORXg7UZUo7sePv97JyoDqtQVi3Ll0b8');
const hastebins = require('hastebin-gen');
const getYoutubeID = require('get-youtube-id');
const yt_api_key = "AIzaSyDeoIH0u1e72AtfpwSKKOSy3IPp2UHzqi4";
const pretty = require("pretty-ms");
client.login(TOKEN);
const queue = new Map();
var table = require('table').table
const Discord = require('discord.js');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
//ßæÏ ááÊÌÑÈÉ
/////////////////////////
////////////////////////
client.on('message', async msg =>{
if (msg.author.bot) return undefined;
if (!msg.content.startsWith(prefix)) return undefined;
let args = msg.content.split(' ');
let command = msg.content.toLowerCase().split(" ")[0];
command = command.slice(prefix.length)
if(command === `ping`) {
let embed = new Discord.RichEmbed()
.setColor(3447003)
.setTitle("Pong!!")
.setDescription(`${client.ping} ms,`)
.setFooter(`Requested by | ${msg.author.tag}`);
msg.delete().catch(O_o=>{})
msg.channel.send(embed);
}
});
/////////////////////////
////////////////////////
//////////////////////
client.on('message', async msg =>{
if (msg.author.bot) return undefined;
if (!msg.content.startsWith(prefix)) return undefined;
let args = msg.content.split(' ');
let command = msg.content.toLowerCase().split(" ")[0];
command = command.slice(prefix.length)
if(command === `avatar`){
if(msg.channel.type === 'dm') return msg.channel.send("Nope Nope!! u can't use avatar command in DMs (:")
let mentions = msg.mentions.members.first()
if(!mentions) {
let sicon = msg.author.avatarURL
let embed = new Discord.RichEmbed()
.setImage(msg.author.avatarURL)
.setColor("#5074b3")
msg.channel.send({embed})
} else {
let sicon = mentions.user.avatarURL
let embed = new Discord.RichEmbed()
.setColor("#5074b3")
.setImage(sicon)
msg.channel.send({embed})
}
};
});
/////////////////////////
////////////////////////
//////////////////////
/////////////////////////
////////////////////////
//////////////////////
/////////////////////////
////////////////////////
//////////////////////
/////////////////////////
////////////////////////
//////////////////////
client.on('message', async msg => {
if (msg.author.bot) return undefined;
if (!msg.content.startsWith(prefix)) return undefined;
const args = msg.content.split(' ');
const searchString = args.slice(1).join(' ');
const url = args[1] ? args[1].replace(/<(.+)>/g, '$1') : '';
const serverQueue = queue.get(msg.guild.id);
let command = msg.content.toLowerCase().split(" ")[0];
command = command.slice(prefix.length)
if (command === `play`) {
const voiceChannel = msg.member.voiceChannel;
if (!voiceChannel) return msg.channel.send("انت لم تدخل روم صوتي");
const permissions = voiceChannel.permissionsFor(msg.client.user);
if (!permissions.has('CONNECT')) {
return msg.channel.send("ليست لدي صلاحيات للدخول الى الروم");
}
if (!permissions.has('SPEAK')) {
return msg.channel.send("انا لا يمكنني التكلم ÙÙŠ هاذه الروم");
}
if (!permissions.has('EMBED_LINKS')) {
return msg.channel.sendMessage("انا لا املك صلاحيات ارسال روابط")
}
if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
const playlist = await youtube.getPlaylist(url);
const videos = await playlist.getVideos();
for (const video of Object.values(videos)) {
const video2 = await youtube.getVideoByID(video.id);
await handleVideo(video2, msg, voiceChannel, true);
}
return msg.channel.send(`**${playlist.title}**, Just added to the queue!`);
} else {
try {
var video = await youtube.getVideo(url);
} catch (error) {
try {
var videos = await youtube.searchVideos(searchString, 5);
let index = 0;
const embed1 = new Discord.RichEmbed()
.setTitle(":mag_right: YouTube Search Results :")
.setDescription(`
${videos.map(video2 => `${++index}. **${video2.title}**`).join('\n')}`)
.setColor("#f7abab")
msg.channel.sendEmbed(embed1).then(message =>{message.delete(20000)})
/////////////////
try {
var response = await msg.channel.awaitMessages(msg2 => msg2.content > 0 && msg2.content < 11, {
maxMatches: 1,
time: 15000,
errors: ['time']
});
} catch (err) {
console.error(err);
return msg.channel.send('لم يتم اختيار الاغنية');
}
const videoIndex = parseInt(response.first().content);
var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
} catch (err) {
console.error(err);
return msg.channel.send("I didn't find any results!");
}
}
return handleVideo(video, msg, voiceChannel);
}
} else if (command === `skip`) {
if (!msg.member.voiceChannel) return msg.channel.send("يجب ان تكون ÙÙŠ روم صوتي");
if (!serverQueue) return msg.channel.send("ليست هناك اغاني ليتم التخطي");
serverQueue.connection.dispatcher.end('تم تخطي الاغنية');
return undefined;
} else if (command === `stop`) {
if (!msg.member.voiceChannel) return msg.channel.send("يجب ان تكون ÙÙŠ روم صوتي");
if (!serverQueue) return msg.channel.send("There is no Queue to stop!!");
serverQueue.songs = [];
serverQueue.connection.dispatcher.end('تم ايقا٠الاغنية لقد خرجت من الروم الصوتي');
return undefined;
} else if (command === `vol`) {
if (!msg.member.voiceChannel) return msg.channel.send("يجب ان تكون ÙÙŠ روم صوتي");
if (!serverQueue) return msg.channel.send('يعمل الامر Ùقط عند تشغيل مقطع صوتي');
if (!args[1]) return msg.channel.send(`لقد تم تغير درجة الصوت الى**${serverQueue.volume}**`);
serverQueue.volume = args[1];
serverQueue.connection.dispatcher.setVolumeLogarithmic(args[1] / 50);
return msg.channel.send(`درجة الصوت الان**${args[1]}**`);
} else if (command === `np`) {
if (!serverQueue) return msg.channel.send('There is no Queue!');
const embedNP = new Discord.RichEmbed()
.setDescription(`Now playing **${serverQueue.songs[0].title}**`)
return msg.channel.sendEmbed(embedNP);
} else if (command === `queue`) {
if (!serverQueue) return msg.channel.send('There is no Queue!!');
let index = 0;
// // //
const embedqu = new Discord.RichEmbed()
.setTitle("The Queue Songs :")
.setDescription(`
${serverQueue.songs.map(song => `${++index}. **${song.title}**`).join('\n')}
**Now playing :** **${serverQueue.songs[0].title}**`)
.setColor("#f7abab")
return msg.channel.sendEmbed(embedqu);
} else if (command === `pause`) {
if (serverQueue && serverQueue.playing) {
serverQueue.playing = false;
serverQueue.connection.dispatcher.pause();
return msg.channel.send('تم الايقاÙ');
}
return msg.channel.send('ÙÙŠ انتظار تشغيل المقطع');
} else if (command === "resume") {
if (serverQueue && !serverQueue.playing) {
serverQueue.playing = true;
serverQueue.connection.dispatcher.resume();
return msg.channel.send('تم التشغيل');
}
return msg.channel.send('Queue is empty!');
}
return undefined;
});
async function handleVideo(video, msg, voiceChannel, playlist = false) {
const serverQueue = queue.get(msg.guild.id);
console.log(video);
const song = {
id: video.id,
title: Util.escapeMarkdown(video.title),
url: `https://www.youtube.com/watch?v=${video.id}`
};
if (!serverQueue) {
const queueConstruct = {
textChannel: msg.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(msg.guild.id, queueConstruct);
queueConstruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueConstruct.connection = connection;
play(msg.guild, queueConstruct.songs[0]);
} catch (error) {
console.error(`I could not join the voice channel: ${error}!`);
queue.delete(msg.guild.id);
return msg.channel.send(`Can't join this channel: ${error}!`);
}
} else {
serverQueue.songs.push(song);
console.log(serverQueue.songs);
if (playlist) return undefined;
else return msg.channel.send(`**${song.title}**, تمت اضاÙØ© المقطع الى قائمة الانتظار `);
}
return undefined;
}
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
console.log(serverQueue.songs);
const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
.on('end', reason => {
if (reason === 'Stream is not generating quickly enough.') console.log('Song ended.');
else console.log(reason);
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on('error', error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`**${song.title}**, is now playing!`);
}
client.on('message', message => {
if (message.content === 'help') {
let helpEmbed = new Discord.RichEmbed()
.setTitle('**أوامر الميوزك...**')
.setDescription('**برÙكس البوت (!)**')
.addField('play', 'لتشغيل اغنية')
.addField('join', 'دخول رومك الصوتي')
.addField('disconnect', 'الخروج من رومك الصوتي')
.addField('skip', 'تخطي الأغنية')
.addField('pause', 'ايقا٠الاغنية مؤقتا')
.addField('resume', 'تكملة الاغنية')
.addField('queue', 'اظهار قائمة التشغيل')
.addField('np', 'اظهار الاغنية اللي انت مشغلها حاليا')
.setFooter('(general_commands) لاظهار الاوامر العامة')
message.channel.send(helpEmbed);
}
});
client.on('message', message => {
if (message.content === 'general_commands') {
let helpEmbed = new Discord.RichEmbed()
.setTitle('**أوامر عامة...**')
.addField('avatar', "اÙاتار الشخص المطلوب")
.addField('gif', 'البحث عن جي٠انت تطلبه')
.addField('ping', 'معرÙØ© ping البوت')
.setFooter('المزيد قريبا ان شاء الله!')
message.channel.send(helpEmbed);
}
});
client.on('ready', () => {
console.log(`----------------`);
console.log(`Desert Bot- Script By : EX Clan`);
console.log(`----------------`);
console.log(`ON ${client.guilds.size} Servers ' Script By : EX Clan ' `);
console.log(`----------------`);
console.log(`Logged in as ${client.user.tag}!`);
client.user.setGame(`1play | Last Music`,"http://twitch.tv/Death Shop")
client.user.setStatus("dnd")
});
Package.json
{
"name": "simple-music",
"version": "1.0.0",
"description": "Simple shitty music",
"main": "server.js",
"repository": {
"type": "git",
"url": "git+https://github.com/Abady321x123/simple-music.git"
},
"author": "Abady",
"license": "MIT",
"bugs": {
"url": "https://github.com/Abady321x123/simple-music/issues"
},
"homepage": "https://github.com/Abady321x123/simple-music#readme",
"dependencies": {
"anti-spam": "^0.2.7",
"array-sort": "^1.0.0",
"ascii-data-table": "^2.1.1",
"common-tags": "^1.8.0",
"math-expression-evaluator": "^1.2.17",
"canvas": "^2.4.1",
"fs-nextra": "^0.4.4",
"canvas-prebuilt": "^1.6.11",
"cleverbot.io": "^1.0.4",
"get": "1.4.0",
"hero": "^0.0.1",
"steam-search": "^1.0.0",
"hypixel-api": "1.1.0",
"name": "^0.0.2",
"3amyah": "^1.0.0",
"google-translate-api": "^2.3.0",
"dateformat": "^3.0.3",
"discord-anti-spam": "^2.0.0",
"discord.js": "11.4.2",
"express": "^4.16.4",
"ffmpeg": "^0.0.4",
"better-sqlite-pool": "^0.2.2",
"guild": "^1.2.2",
"delay": "^4.1.0",
"enmap": "^4.8.1",
"ffmpeg-binaries": "^4.0.0",
"figlet": "^1.2.1",
"file-system": "^2.2.2",
"forever": "^0.15.3",
"fortnite": "^4.3.2",
"node-emoji": "^1.10.0",
"fortnite-api": "^3.2.0",
"get-youtube-id": "^1.0.1",
"gif-search": "^2.0.1",
"giphy-api": "^2.0.1",
"goo.gl": "^0.1.4",
"google-it": "^1.1.3",
"hastebin-gen": "^1.3.1",
"hh-mm-ss": "^1.2.0",
"jimp": "^0.6.0",
"message": "0.0.1",
"moment": "^2.24.0",
"ms": "^2.1.1",
"new": "0.1.1",
"node-opus": "^0.3.1",
"npm": "^6.5.0",
"opusscript": "0.0.6",
"path": "0.12.7",
"pretty-ms": "^4.0.0",
"queue": "^6.0.1",
"quick.db": "^6.3.2",
"replace": "^1.1.0",
"short-number": "^1.0.6",
"simple-youtube-api": "^5.1.1",
"sqlite": "^3.0.3",
"sqlite3": "^4.0.6",
"stackos": "1.1.0",
"superagent": "4.1.0",
"table": "^5.2.2",
"until": "^0.1.1",
"ustat": "0.0.2",
"winston": "^3.2.1",
"youtube-info": "^1.3.2",
"ytdl-core": "^0.29.0"
},
"scripts": {
"start": "node server.js"
}
}
Config.js
module.exports = {
TOKEN: 'Already In',
YT_API_KEY: 'api ',
prefix: '!',
devs: ['Already In']
}
So first : Don't use an event more the once !
This makes the bot extremely slow and hard to comunicate with ,use a command handler wich is better in most of the cases or just make an if else statement like this :
if(message.content === '!help'){
// code
}
else
if(message.content === '!play'){
// code
}
// etc
Second : So many packages.
Try to get rid of some packages !!§! You have too many and this makes the code really hard to read and honestly i would be surprised if someone rode all of it! +makes your bot slow!
Last : Please be specific
Not to be rude but i really don't see what do you expect from us. people won't just correct your code and give it to you and we cannot explain every single thing this enormous code have. so please next time be more specific

Why doesn't my discord bot go online without an error or anything?

So basically, I've tried to fix this issue for hours and hours without success. This is what happens when I try to launch the bot:
https://gyazo.com/3a941b4372c88be07c76c5b004327f71
I've checked that the main is right and that everything is right like the json files and the actual code.
bot.js ->
const botconfig = require("./botconfig.json");
const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
bot.on("ready", async () => {
console.log(`${bot.user.username} is online!`);
bot.user.setActivity("Tickets", {type: "WATCHING"});
});
bot.on('message', async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefix = botconfig.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if(cmd === `${prefix}new`){
let embed = new Discord.RichEmbed()
.setTitle("Ticket created")
.setDescription("Ticket #ticket- has been created successfully.")
.setColor("#15f153")
.setFooter("chefren#9582 | 2019")
return message.channel.send(embed);
}
if(cmd === `${prefix}ticketcreation`){
let embed = new Discord.RichEmbed()
.setTitle("Ticket")
.setDescription("Do you require help or support? React with :white_check_mark: ")
.setColor("#15f153")
.setFooter("dl121#9582 | 2019")
msg = await message.channel.send(embed);
await msg.react('✅')
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '✅') {
message.reply('you reacted with a thumbs up.');
}
});
bot.login(botconfig.token);
}
})
Package.json
{
"name": "bot",
"version": "1.0.0",
"description": "A bot",
"main": "bot.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "andrew",
"license": "ISC",
"dependencies": {
"cjs": "0.0.11",
"discord.js": "^11.5.1",
"fs": "0.0.1-security",
"node.js": "0.0.0"
},
"devDependencies": {}
}
There was this error message before that I fixed:
Error: Cannot find module 'C:\Users\Andrew\Desktop\Discord Bots\Bot\bot,js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Based on the code you provided, it looks like there's a bit of a problem with your curly braces. The bot.login({...}) call was actually inside of the bot.on('message' handler. Obviously you won't receive messages without first logging in, so that's probably what's going on.
I re-indented your code and added the necessary curly braces and parentheses to make the bot.login call run at the end of the script, outside of any handler functions.
const botconfig = require("./botconfig.json");
const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
bot.on("ready", async () => {
console.log(`${bot.user.username} is online!`);
bot.user.setActivity("Tickets", {type: "WATCHING"});
});
bot.on('message', async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefix = botconfig.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if (cmd === `${prefix}new`) {
let embed = new Discord.RichEmbed()
.setTitle("Ticket created")
.setDescription("Ticket #ticket- has been created successfully.")
.setColor("#15f153")
.setFooter("chefren#9582 | 2019")
return message.channel.send(embed);
}
if (cmd === `${prefix}ticketcreation`) {
let embed = new Discord.RichEmbed()
.setTitle("Ticket")
.setDescription("Do you require help or support? React with :white_check_mark: ")
.setColor("#15f153")
.setFooter("dl121#9582 | 2019")
let msg = await message.channel.send(embed);
await msg.react('✅')
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })'
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '✅') {
message.reply('you reacted with a thumbs up.');
}
});
}
});
// *** CHANGES WERE MADE ABOVE HERE ***
bot.login(botconfig.token);

Categories

Resources