-1

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']
}
User Command
  • 1
  • 1
  • 1
  • 2
    Welcome to Stack Overflow! Please read the [help pages](https://stackoverflow.com/help), take the [SO tour](https://stackoverflow.com/tour), read about [how to ask good questions](https://stackoverflow.com/help/how-to-ask), as well as this [question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Please make this question clearer by making an [MCVE](https://stackoverflow.com/help/minimal-reproducible-example) instead of dumping your code. – Ross Jacobs Oct 05 '19 at 18:52
  • If you're looking for information on [loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration), Mozilla documentation is good. – Ross Jacobs Oct 05 '19 at 18:52
  • Removed unnecessary text and corrected OP and added tags – Alejandro Teixeira Muñoz Oct 05 '19 at 22:38

1 Answers1

1

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

Jonas Deichelmann
  • 3,513
  • 1
  • 30
  • 45