Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const {Client, Collection, bot, Util } = require("discord.js");
- const { config } = require("dotenv");
- const fs = require("fs");
- const YouTube = require('simple-youtube-api')
- const util = require("util");
- const Discord = require('discord.js')
- const dotenv = require('dotenv').config()
- const youtube = new YouTube(process.env.GOOGLE_API_KEY);
- // Import constructors, configuration and login the client
- const { RichEmbed, Emoji, MessageReaction } = require('discord.js');
- const CONFIG = require('./config');
- const client = new Client({ disableEveryone: true });
- // If there isn't a reaction for every role, alert the user
- if (CONFIG.roles.length !== CONFIG.reactions.length)
- throw "Roles list and reactions list are not the same length! Please double check this in the config.js file";
- // Function to generate the role messages, based on your settings
- function generateMessages() {
- return CONFIG.roles.map((r, e) => {
- return {
- role: r,
- message: `React below to get the **"${r}"** role!`, //DONT CHANGE THIS,
- emoji: CONFIG.reactions[e]
- };
- });
- }
- // Function to generate the embed fields, based on your settings and if you set "const embed = true;"
- function generateEmbedFields() {
- return CONFIG.roles.map((r, e) => {
- return {
- emoji: CONFIG.reactions[e],
- role: r
- };
- });
- }
- // Handles the creation of the role reactions. Will either send the role messages separately or in an embed
- client.on("message", message => {
- // Make sure bots can't run this command
- if (message.author.bot) return;
- // Make sure the command can only be ran in a server
- if (!message.guild) return;
- // We don't want the bot to do anything further if it can't send messages in the channel
- if (message.guild && !message.channel.permissionsFor(message.guild.me).missing('SEND_MESSAGES')) return;
- if ((message.author.id !== CONFIG.yourID) && (message.content.toLowerCase() !== CONFIG.setupCMD)) return;
- if (CONFIG.deleteSetupCMD) {
- const missing = message.channel.permissionsFor(message.guild.me).missing('MANAGE_MESSAGES');
- // Here we check if the bot can actually delete messages in the channel the command is being ran in
- if (missing.includes('MANAGE_MESSAGES'))
- throw new Error("I need permission to delete your command message! Please assign the 'Manage Messages' permission to me in this channel!");
- message.delete().catch(O_o=>{});
- }
- const missing = message.channel.permissionsFor(message.guild.me).missing('MANAGE_MESSAGES');
- // Here we check if the bot can actually add recations in the channel the command is being ran in
- if (missing.includes('ADD_REACTIONS'))
- throw new Error("I need permission to add reactions to these messages! Please assign the 'Add Reactions' permission to me in this channel!");
- if (!CONFIG.embed) {
- if (!CONFIG.initialMessage || (CONFIG.initialMessage === ''))
- throw "The 'initialMessage' property is not set in the config.js file. Please do this!";
- message.channel.send(CONFIG.initialMessage);
- const messages = generateMessages();
- for (const { role, message: msg, emoji } of messages) {
- if (!message.guild.roles.find(r => r.name === role))
- throw `The role '${role}' does not exist!`;
- message.channel.send(msg).then(async m => {
- const customCheck = message.guild.emojis.find(e => e.name === emoji);
- if (!customCheck) await m.react(emoji);
- else await m.react(customCheck.id);
- }).catch(console.error);
- }
- } else {
- if (!CONFIG.embedMessage || (CONFIG.embedMessage === ''))
- throw "The 'embedMessage' property is not set in the config.js file. Please do this!";
- if (!CONFIG.embedFooter || (CONFIG.embedMessage === ''))
- throw "The 'embedFooter' property is not set in the config.js file. Please do this!";
- const roleEmbed = new RichEmbed()
- .setDescription(CONFIG.embedMessage)
- .setFooter(CONFIG.embedFooter);
- if (CONFIG.embedColor) roleEmbed.setColor(CONFIG.embedColor);
- if (CONFIG.embedThumbnail && (CONFIG.embedThumbnailLink !== ''))
- roleEmbed.setThumbnail(CONFIG.embedThumbnailLink);
- else if (CONFIG.embedThumbnail && message.guild.icon)
- roleEmbed.setThumbnail(message.guild.iconURL);
- const fields = generateEmbedFields();
- if (fields.length > 25) throw "That maximum roles that can be set for an embed is 25!";
- for (const { emoji, role } of fields) {
- if (!message.guild.roles.find(r => r.name === role))
- throw `The role '${role}' does not exist!`;
- const customEmote = client.emojis.find(e => e.name === emoji);
- if (!customEmote) roleEmbed.addField(emoji, role, true);
- else roleEmbed.addField(customEmote, role, true);
- }
- message.channel.send(roleEmbed).then(async m => {
- for (const r of CONFIG.reactions) {
- const emoji = r;
- const customCheck = client.emojis.find(e => e.name === emoji);
- if (!customCheck) await m.react(emoji);
- else await m.react(customCheck.id);
- }
- });
- }
- });
- // This makes the events used a bit more readable
- const events = {
- MESSAGE_REACTION_ADD: 'messageReactionAdd',
- MESSAGE_REACTION_REMOVE: 'messageReactionRemove',
- };
- // This event handles adding/removing users from the role(s) they chose based on message reactions
- client.on('raw', async event => {
- if (!events.hasOwnProperty(event.t)) return;
- const { d: data } = event;
- const user = client.users.get(data.user_id);
- const channel = client.channels.get(data.channel_id);
- const message = await channel.fetchMessage(data.message_id);
- const member = message.guild.members.get(user.id);
- const emojiKey = (data.emoji.id) ? `${data.emoji.name}:${data.emoji.id}` : data.emoji.name;
- let reaction = message.reactions.get(emojiKey);
- if (!reaction) {
- // Create an object that can be passed through the event like normal
- const emoji = new Emoji(client.guilds.get(data.guild_id), data.emoji);
- reaction = new MessageReaction(message, emoji, 1, data.user_id === client.user.id);
- }
- let embedFooterText;
- if (message.embeds[0]) embedFooterText = message.embeds[0].footer.text;
- if (
- (message.author.id === client.user.id) && (message.content !== CONFIG.initialMessage ||
- (message.embeds[0] && (embedFooterText !== CONFIG.embedFooter)))
- ) {
- if (!CONFIG.embed && (message.embeds.length < 1)) {
- const re = `\\*\\*"(.+)?(?="\\*\\*)`;
- const role = message.content.match(re)[1];
- if (member.id !== client.user.id) {
- const guildRole = message.guild.roles.find(r => r.name === role);
- if (event.t === "MESSAGE_REACTION_ADD") member.addRole(guildRole.id);
- else if (event.t === "MESSAGE_REACTION_REMOVE") member.removeRole(guildRole.id);
- }
- } else if (CONFIG.embed && (message.embeds.length >= 1)) {
- const fields = message.embeds[0].fields;
- for (const { name, value } of fields) {
- if (member.id !== client.user.id) {
- const guildRole = message.guild.roles.find(r => r.name === value);
- if ((name === reaction.emoji.name) || (name === reaction.emoji.toString())) {
- if (event.t === "MESSAGE_REACTION_ADD") member.addRole(guildRole.id);
- else if (event.t === "MESSAGE_REACTION_REMOVE") member.removeRole(guildRole.id);
- }
- }
- }
- }
- }
- });
- process.on('unhandledRejection', err => {
- const msg = err.stack.replace(new RegExp(`${__dirname}/`, 'g'), './');
- console.error("Unhandled Rejection", msg);
- });
- //Keeping bot online//
- const http = require("http");
- const express = require("express");
- const app = express();
- client.commands = new Collection();
- client.aliases = new Collection();
- client.categories = fs.readdirSync("./commands/");
- config({
- path: __dirname + "/.env"
- });
- ["command"].forEach(handler => {
- require(`./handler/${handler}`)(client);
- });
- client.on("ready", () => {
- console.log(`Hi, ${client.user.username} is now online!`);
- client.user.setActivity('!help | 24/24')
- });
- client.on("message", async message => {
- const prefix = "!";
- if (message.author.bot) return;
- if (!message.guild) return;
- if (!message.content.startsWith(prefix)) return;
- if (!message.member)
- message.member = await message.guild.fetchMember(message);
- const args = message.content
- .slice(prefix.length)
- .trim()
- .split(/ +/g);
- const cmd = args.shift().toLowerCase();
- if (cmd.length === 0) return;
- let command = client.commands.get(cmd);
- if (!command) command = client.commands.get(client.aliases.get(cmd));
- if (command) command.run(client, message, args);
- });
- //Music//
- const queue = new Map();
- const ytdl = require('ytdl-core');
- const prefix = "!"
- 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[0].replace(/<(.+)>/g, '$1');
- const serverQueue = queue.get(msg.guild.id);
- if (msg.content.startsWith(`${prefix}play`)) {
- const voiceChannel = msg.member.voiceChannel;
- if(!voiceChannel) return msg.channel.send('You need to be in a voice channel');
- const permissions = voiceChannel.permissionsFor(msg.client.user);
- if(!permissions.has('CONNECT')) {
- return msg.channel.send('I cannot connect to your voice channel');
- }
- if(!permissions.has('SPEAK')) {
- return msg.channel.send('I Cannot speak in the Channel')
- }
- try {
- var video = await youtube.getVideo(url);
- } catch (error) {
- try {
- var videos = await youtube.searchVideos(searchString, 1);
- var video = await youtube.getVideoByID(videos[0].id);
- } catch (err) {
- console.error(err);
- return msg.channel.send('I could not obtain any results');
- }
- }
- console.log(video);
- const song = {
- id: video.id,
- title: video.title,
- duration: video.duration.minutes + video.duration.seconds / 120,
- 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);
- let embed = new Discord.RichEmbed()
- .setFooter('${song.title} Has been added to the queue')
- }
- } else {
- serverQueue.songs.push(song);
- const embed = new Discord.RichEmbed()
- .setTitle(`${client.user.username} Music Center`)
- .addField(`Has been added to the queue`, `${song.title}`)
- .addField(`Duration`, `${song.duration.toFixed(2)} minutes`)
- .setFooter("By Soratha#1792")
- serverQueue.textChannel.send(embed);
- }
- return undefined;
- } else if (msg.content.startsWith(`${prefix}skip`)) {
- const embed = new Discord.RichEmbed()
- .setTitle(`${client.user.username} Music Center`)
- .setDescription(`Song has been succesfully skipped ✅`)
- .setFooter("By Soratha#1792")
- serverQueue.textChannel.send(embed);
- if(!msg.member.voiceChannel) return msg.channel.send('You are not in a voice Channel')
- if (!serverQueue) return msg.channel.send('There is nothing playing');
- serverQueue.connection.dispatcher.end('Skip command has been used');
- return undefined;
- } else if (msg.content.startsWith(`${prefix}stop`)) {
- const embed = new Discord.RichEmbed()
- .setTitle(`${client.user.username} Music Center`)
- .setDescription(`Song has been succesfully stopped ✅`)
- .setFooter("By Soratha#1792")
- serverQueue.textChannel.send(embed);
- if(!msg.member.voiceChannel) return msg.channel.send('You are not in a voice Channel')
- if (!serverQueue) return msg.channel.send('There is nothing playing');
- serverQueue.songs = [];
- serverQueue.connection.dispatcher.end('Stop command has been used');
- return undefined;
- } else if (msg.content.startsWith(`${prefix}volume`)) {
- if(!msg.member.voiceChannel) return msg.channel.send('You are not in a voice Channel')
- if (!serverQueue) return msg.channel.send('There is nothing playing');
- if (!args[1]) return msg.channel.send(`The current volume: is ${serverQueue.volume}`);
- serverQueue.volume = args [1];
- serverQueue.connection.dispatcher.setVolumeLogarithmic(args[1] / 5);
- return msg.channel.send(`Set the volume to: ${args[1]}`);
- return undefined;
- } else if (msg.content.startsWith(`${prefix}np`)) {
- if (!serverQueue) return msg.channel.send('There is nothing playing');
- return msg.channel.send(`Now playing: ${serverQueue.songs[0].title}`);
- } else if (msg.content.startsWith(`${prefix}queue`)) {
- if (!serverQueue) return msg.channel.send('There is nothing playing');
- msg.channel.send
- const embed = new Discord.RichEmbed()
- .setTitle(`${client.user.username} Music Center`)
- .addField(`Songs Queues`,
- `${serverQueue.songs.map(song => `**${song.title}**`).join('\n')}`)
- .addField(`Now playing`, `**${serverQueue.songs[0].title}**`)
- .setFooter("By Soratha#1792")
- serverQueue.textChannel.send(embed).then(msg => {
- msg.delete(5000)
- });
- } else if (msg.content.startsWith(`${prefix}pause`)) {
- if (serverQueue && serverQueue.playing) {
- serverQueue.playing = false;
- serverQueue.connection.dispatcher.pause();
- return msg.channel.send('Paused the music')
- }
- return msg.channel.send('There is nothing playing');
- } else if (msg.content.startsWith(`${prefix}resume`)) {
- if (serverQueue && !serverQueue.playing) {
- serverQueue.playing = true;
- serverQueue.connection.dispatcher.resume();
- return msg.channel.send('Resumed the music');
- }
- return msg.channel.send('There is nothing playing');
- }
- 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);
- const embed = new Discord.RichEmbed()
- .setTitle(`${client.user.username} Music Center`)
- .addField(`Starting Playing`, `${song.title}`)
- .addField(`Duration`, `${song.duration.toFixed(2)} minutes`)
- .setFooter("By Soratha#1792")
- serverQueue.textChannel.send(embed);
- };
- //Auto Role//
- client.on('guildMemberAdd', member => {
- let embed = new Discord.RichEmbed()
- .setDescription('Bienvenue sur le serveur! ' + member.user + ' N\'hésite pas à lire les règles dans #reglement !')
- .setFooter('We are actually ' + member.guild.memberCount)
- member.guild.channels.get('680890176251363444').send(embed)
- member.addRole('663158887578337300')
- });
- client.on('guildMemberRemove', member => {
- let embed = new Discord.RichEmbed()
- .setDescription('See you soon ! ' + member.user)
- .setFooter('We are actually ' + member.guild.memberCount)
- member.guild.channels.get('680890176251363444').send(embed)
- });
- client.on('message', message => {
- let args = message.content.substring(prefix.length).split(" ");
- switch(args[0]){
- case 'embed':
- const embed = new Discord.RichEmbed()
- .setTitle(' Welcome to the server dear people ! ')
- .setDescription(' There is some rules that you have to know so take a time to read them')
- .addField('```Number 1 : Respect each others```')
- .addField('```Number 2 : Don\'t spam```')
- message.channel.sendEmbed(embed);
- break;
- }
- });
- client.login(process.env.TOKEN);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement