Advertisement
Guest User

Untitled

a guest
Mar 29th, 2020
486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.59 KB | None | 0 0
  1.  
  2. const {Client, Collection, bot, Util } = require("discord.js");
  3. const { config } = require("dotenv");
  4. const fs = require("fs");
  5. const YouTube = require('simple-youtube-api')
  6. const util = require("util");
  7. const Discord = require('discord.js')
  8.  
  9. const dotenv = require('dotenv').config()
  10.  
  11. const youtube = new YouTube(process.env.GOOGLE_API_KEY);
  12.  
  13. // Import constructors, configuration and login the client
  14. const { RichEmbed, Emoji, MessageReaction } = require('discord.js');
  15. const CONFIG = require('./config');
  16.  
  17. const client = new Client({ disableEveryone: true });
  18.  
  19. // If there isn't a reaction for every role, alert the user
  20. if (CONFIG.roles.length !== CONFIG.reactions.length)
  21. throw "Roles list and reactions list are not the same length! Please double check this in the config.js file";
  22.  
  23. // Function to generate the role messages, based on your settings
  24. function generateMessages() {
  25. return CONFIG.roles.map((r, e) => {
  26. return {
  27. role: r,
  28. message: `React below to get the **"${r}"** role!`, //DONT CHANGE THIS,
  29. emoji: CONFIG.reactions[e]
  30. };
  31. });
  32. }
  33.  
  34. // Function to generate the embed fields, based on your settings and if you set "const embed = true;"
  35. function generateEmbedFields() {
  36. return CONFIG.roles.map((r, e) => {
  37. return {
  38. emoji: CONFIG.reactions[e],
  39. role: r
  40. };
  41. });
  42. }
  43.  
  44.  
  45.  
  46. // Handles the creation of the role reactions. Will either send the role messages separately or in an embed
  47. client.on("message", message => {
  48. // Make sure bots can't run this command
  49. if (message.author.bot) return;
  50.  
  51. // Make sure the command can only be ran in a server
  52. if (!message.guild) return;
  53.  
  54. // We don't want the bot to do anything further if it can't send messages in the channel
  55. if (message.guild && !message.channel.permissionsFor(message.guild.me).missing('SEND_MESSAGES')) return;
  56.  
  57. if ((message.author.id !== CONFIG.yourID) && (message.content.toLowerCase() !== CONFIG.setupCMD)) return;
  58.  
  59. if (CONFIG.deleteSetupCMD) {
  60. const missing = message.channel.permissionsFor(message.guild.me).missing('MANAGE_MESSAGES');
  61. // Here we check if the bot can actually delete messages in the channel the command is being ran in
  62. if (missing.includes('MANAGE_MESSAGES'))
  63. throw new Error("I need permission to delete your command message! Please assign the 'Manage Messages' permission to me in this channel!");
  64. message.delete().catch(O_o=>{});
  65. }
  66.  
  67. const missing = message.channel.permissionsFor(message.guild.me).missing('MANAGE_MESSAGES');
  68. // Here we check if the bot can actually add recations in the channel the command is being ran in
  69. if (missing.includes('ADD_REACTIONS'))
  70. throw new Error("I need permission to add reactions to these messages! Please assign the 'Add Reactions' permission to me in this channel!");
  71.  
  72. if (!CONFIG.embed) {
  73. if (!CONFIG.initialMessage || (CONFIG.initialMessage === ''))
  74. throw "The 'initialMessage' property is not set in the config.js file. Please do this!";
  75.  
  76. message.channel.send(CONFIG.initialMessage);
  77.  
  78. const messages = generateMessages();
  79. for (const { role, message: msg, emoji } of messages) {
  80. if (!message.guild.roles.find(r => r.name === role))
  81. throw `The role '${role}' does not exist!`;
  82.  
  83. message.channel.send(msg).then(async m => {
  84. const customCheck = message.guild.emojis.find(e => e.name === emoji);
  85. if (!customCheck) await m.react(emoji);
  86. else await m.react(customCheck.id);
  87. }).catch(console.error);
  88. }
  89. } else {
  90. if (!CONFIG.embedMessage || (CONFIG.embedMessage === ''))
  91. throw "The 'embedMessage' property is not set in the config.js file. Please do this!";
  92. if (!CONFIG.embedFooter || (CONFIG.embedMessage === ''))
  93. throw "The 'embedFooter' property is not set in the config.js file. Please do this!";
  94.  
  95. const roleEmbed = new RichEmbed()
  96. .setDescription(CONFIG.embedMessage)
  97. .setFooter(CONFIG.embedFooter);
  98.  
  99. if (CONFIG.embedColor) roleEmbed.setColor(CONFIG.embedColor);
  100.  
  101. if (CONFIG.embedThumbnail && (CONFIG.embedThumbnailLink !== ''))
  102. roleEmbed.setThumbnail(CONFIG.embedThumbnailLink);
  103. else if (CONFIG.embedThumbnail && message.guild.icon)
  104. roleEmbed.setThumbnail(message.guild.iconURL);
  105.  
  106. const fields = generateEmbedFields();
  107. if (fields.length > 25) throw "That maximum roles that can be set for an embed is 25!";
  108.  
  109. for (const { emoji, role } of fields) {
  110. if (!message.guild.roles.find(r => r.name === role))
  111. throw `The role '${role}' does not exist!`;
  112.  
  113. const customEmote = client.emojis.find(e => e.name === emoji);
  114.  
  115. if (!customEmote) roleEmbed.addField(emoji, role, true);
  116. else roleEmbed.addField(customEmote, role, true);
  117. }
  118.  
  119. message.channel.send(roleEmbed).then(async m => {
  120. for (const r of CONFIG.reactions) {
  121. const emoji = r;
  122. const customCheck = client.emojis.find(e => e.name === emoji);
  123.  
  124. if (!customCheck) await m.react(emoji);
  125. else await m.react(customCheck.id);
  126. }
  127. });
  128. }
  129. });
  130.  
  131. // This makes the events used a bit more readable
  132. const events = {
  133. MESSAGE_REACTION_ADD: 'messageReactionAdd',
  134. MESSAGE_REACTION_REMOVE: 'messageReactionRemove',
  135. };
  136.  
  137. // This event handles adding/removing users from the role(s) they chose based on message reactions
  138. client.on('raw', async event => {
  139. if (!events.hasOwnProperty(event.t)) return;
  140.  
  141. const { d: data } = event;
  142. const user = client.users.get(data.user_id);
  143. const channel = client.channels.get(data.channel_id);
  144.  
  145. const message = await channel.fetchMessage(data.message_id);
  146. const member = message.guild.members.get(user.id);
  147.  
  148. const emojiKey = (data.emoji.id) ? `${data.emoji.name}:${data.emoji.id}` : data.emoji.name;
  149. let reaction = message.reactions.get(emojiKey);
  150.  
  151. if (!reaction) {
  152. // Create an object that can be passed through the event like normal
  153. const emoji = new Emoji(client.guilds.get(data.guild_id), data.emoji);
  154. reaction = new MessageReaction(message, emoji, 1, data.user_id === client.user.id);
  155. }
  156.  
  157. let embedFooterText;
  158. if (message.embeds[0]) embedFooterText = message.embeds[0].footer.text;
  159.  
  160. if (
  161. (message.author.id === client.user.id) && (message.content !== CONFIG.initialMessage ||
  162. (message.embeds[0] && (embedFooterText !== CONFIG.embedFooter)))
  163. ) {
  164.  
  165. if (!CONFIG.embed && (message.embeds.length < 1)) {
  166. const re = `\\*\\*"(.+)?(?="\\*\\*)`;
  167. const role = message.content.match(re)[1];
  168.  
  169. if (member.id !== client.user.id) {
  170. const guildRole = message.guild.roles.find(r => r.name === role);
  171. if (event.t === "MESSAGE_REACTION_ADD") member.addRole(guildRole.id);
  172. else if (event.t === "MESSAGE_REACTION_REMOVE") member.removeRole(guildRole.id);
  173. }
  174. } else if (CONFIG.embed && (message.embeds.length >= 1)) {
  175. const fields = message.embeds[0].fields;
  176.  
  177. for (const { name, value } of fields) {
  178. if (member.id !== client.user.id) {
  179. const guildRole = message.guild.roles.find(r => r.name === value);
  180. if ((name === reaction.emoji.name) || (name === reaction.emoji.toString())) {
  181. if (event.t === "MESSAGE_REACTION_ADD") member.addRole(guildRole.id);
  182. else if (event.t === "MESSAGE_REACTION_REMOVE") member.removeRole(guildRole.id);
  183. }
  184. }
  185. }
  186. }
  187. }
  188. });
  189.  
  190. process.on('unhandledRejection', err => {
  191. const msg = err.stack.replace(new RegExp(`${__dirname}/`, 'g'), './');
  192. console.error("Unhandled Rejection", msg);
  193. });
  194.  
  195.  
  196.  
  197.  
  198. //Keeping bot online//
  199. const http = require("http");
  200. const express = require("express");
  201. const app = express();
  202.  
  203.  
  204. client.commands = new Collection();
  205. client.aliases = new Collection();
  206.  
  207. client.categories = fs.readdirSync("./commands/");
  208.  
  209. config({
  210. path: __dirname + "/.env"
  211. });
  212.  
  213. ["command"].forEach(handler => {
  214. require(`./handler/${handler}`)(client);
  215. });
  216.  
  217. client.on("ready", () => {
  218. console.log(`Hi, ${client.user.username} is now online!`);
  219. client.user.setActivity('!help | 24/24')
  220.  
  221. });
  222.  
  223. client.on("message", async message => {
  224. const prefix = "!";
  225.  
  226. if (message.author.bot) return;
  227. if (!message.guild) return;
  228. if (!message.content.startsWith(prefix)) return;
  229. if (!message.member)
  230. message.member = await message.guild.fetchMember(message);
  231.  
  232. const args = message.content
  233. .slice(prefix.length)
  234. .trim()
  235. .split(/ +/g);
  236. const cmd = args.shift().toLowerCase();
  237.  
  238. if (cmd.length === 0) return;
  239.  
  240. let command = client.commands.get(cmd);
  241. if (!command) command = client.commands.get(client.aliases.get(cmd));
  242.  
  243. if (command) command.run(client, message, args);
  244. });
  245.  
  246. //Music//
  247.  
  248. const queue = new Map();
  249.  
  250. const ytdl = require('ytdl-core');
  251. const prefix = "!"
  252.  
  253. client.on('message', async msg => {
  254. if (msg.author.bot) return undefined;
  255. if (!msg.content.startsWith(prefix)) return undefined;
  256. const args = msg.content.split(' ');
  257. const searchString = args.slice(1).join(' ');
  258. const url = args[0].replace(/<(.+)>/g, '$1');
  259. const serverQueue = queue.get(msg.guild.id);
  260.  
  261. if (msg.content.startsWith(`${prefix}play`)) {
  262. const voiceChannel = msg.member.voiceChannel;
  263. if(!voiceChannel) return msg.channel.send('You need to be in a voice channel');
  264. const permissions = voiceChannel.permissionsFor(msg.client.user);
  265. if(!permissions.has('CONNECT')) {
  266. return msg.channel.send('I cannot connect to your voice channel');
  267. }
  268. if(!permissions.has('SPEAK')) {
  269. return msg.channel.send('I Cannot speak in the Channel')
  270. }
  271.  
  272. try {
  273. var video = await youtube.getVideo(url);
  274. } catch (error) {
  275. try {
  276. var videos = await youtube.searchVideos(searchString, 1);
  277. var video = await youtube.getVideoByID(videos[0].id);
  278. } catch (err) {
  279. console.error(err);
  280. return msg.channel.send('I could not obtain any results');
  281. }
  282.  
  283. }
  284. console.log(video);
  285. const song = {
  286. id: video.id,
  287. title: video.title,
  288. duration: video.duration.minutes + video.duration.seconds / 120,
  289. url: `https://www.youtube.com/watch?v=${video.id}`
  290.  
  291. };
  292. if(!serverQueue) {
  293. const queueConstruct = {
  294. textChannel: msg.channel,
  295. voiceChannel: voiceChannel,
  296. connection: null,
  297. songs: [],
  298. volume: 5,
  299. playing:true
  300. };
  301. queue.set(msg.guild.id, queueConstruct);
  302.  
  303. queueConstruct.songs.push(song);
  304.  
  305. try {
  306. var connection = await voiceChannel.join();
  307. queueConstruct.connection = connection;
  308. play(msg.guild, queueConstruct.songs[0]);
  309. } catch (error) {
  310. console.error(`I could not join the voice channel: ${error}`);
  311. queue.delete(msg.guild.id);
  312. let embed = new Discord.RichEmbed()
  313. .setFooter('${song.title} Has been added to the queue')
  314.  
  315. }
  316.  
  317. } else {
  318. serverQueue.songs.push(song);
  319. const embed = new Discord.RichEmbed()
  320. .setTitle(`${client.user.username} Music Center`)
  321. .addField(`Has been added to the queue`, `${song.title}`)
  322. .addField(`Duration`, `${song.duration.toFixed(2)} minutes`)
  323. .setFooter("By Soratha#1792")
  324. serverQueue.textChannel.send(embed);
  325. }
  326. return undefined;
  327.  
  328. } else if (msg.content.startsWith(`${prefix}skip`)) {
  329. const embed = new Discord.RichEmbed()
  330. .setTitle(`${client.user.username} Music Center`)
  331. .setDescription(`Song has been succesfully skipped ✅`)
  332. .setFooter("By Soratha#1792")
  333. serverQueue.textChannel.send(embed);
  334. if(!msg.member.voiceChannel) return msg.channel.send('You are not in a voice Channel')
  335. if (!serverQueue) return msg.channel.send('There is nothing playing');
  336. serverQueue.connection.dispatcher.end('Skip command has been used');
  337. return undefined;
  338. } else if (msg.content.startsWith(`${prefix}stop`)) {
  339. const embed = new Discord.RichEmbed()
  340. .setTitle(`${client.user.username} Music Center`)
  341. .setDescription(`Song has been succesfully stopped ✅`)
  342. .setFooter("By Soratha#1792")
  343. serverQueue.textChannel.send(embed);
  344. if(!msg.member.voiceChannel) return msg.channel.send('You are not in a voice Channel')
  345. if (!serverQueue) return msg.channel.send('There is nothing playing');
  346. serverQueue.songs = [];
  347. serverQueue.connection.dispatcher.end('Stop command has been used');
  348. return undefined;
  349.  
  350. } else if (msg.content.startsWith(`${prefix}volume`)) {
  351. if(!msg.member.voiceChannel) return msg.channel.send('You are not in a voice Channel')
  352. if (!serverQueue) return msg.channel.send('There is nothing playing');
  353. if (!args[1]) return msg.channel.send(`The current volume: is ${serverQueue.volume}`);
  354. serverQueue.volume = args [1];
  355. serverQueue.connection.dispatcher.setVolumeLogarithmic(args[1] / 5);
  356. return msg.channel.send(`Set the volume to: ${args[1]}`);
  357. return undefined;
  358. } else if (msg.content.startsWith(`${prefix}np`)) {
  359. if (!serverQueue) return msg.channel.send('There is nothing playing');
  360. return msg.channel.send(`Now playing: ${serverQueue.songs[0].title}`);
  361. } else if (msg.content.startsWith(`${prefix}queue`)) {
  362. if (!serverQueue) return msg.channel.send('There is nothing playing');
  363. msg.channel.send
  364. const embed = new Discord.RichEmbed()
  365. .setTitle(`${client.user.username} Music Center`)
  366. .addField(`Songs Queues`,
  367. `${serverQueue.songs.map(song => `**${song.title}**`).join('\n')}`)
  368. .addField(`Now playing`, `**${serverQueue.songs[0].title}**`)
  369. .setFooter("By Soratha#1792")
  370. serverQueue.textChannel.send(embed).then(msg => {
  371. msg.delete(5000)
  372. });
  373.  
  374.  
  375. } else if (msg.content.startsWith(`${prefix}pause`)) {
  376. if (serverQueue && serverQueue.playing) {
  377. serverQueue.playing = false;
  378. serverQueue.connection.dispatcher.pause();
  379. return msg.channel.send('Paused the music')
  380. }
  381. return msg.channel.send('There is nothing playing');
  382. } else if (msg.content.startsWith(`${prefix}resume`)) {
  383. if (serverQueue && !serverQueue.playing) {
  384. serverQueue.playing = true;
  385. serverQueue.connection.dispatcher.resume();
  386. return msg.channel.send('Resumed the music');
  387. }
  388. return msg.channel.send('There is nothing playing');
  389.  
  390. }
  391.  
  392. return undefined;
  393. });
  394.  
  395. function play(guild, song) {
  396. const serverQueue = queue.get(guild.id);
  397.  
  398. if (!song) {
  399. serverQueue.voiceChannel.leave();
  400. queue.delete(guild.id);
  401. return;
  402. }
  403. console.log(serverQueue.songs);
  404.  
  405.  
  406. const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
  407. .on('end', reason => {
  408. if (reason === 'Stream is not generating quickly enough') console.log('Song ended');
  409. else console.log(reason)
  410. serverQueue.songs.shift();
  411. play(guild, serverQueue.songs[0]);
  412. })
  413. .on('error', error => console.error(error));
  414. dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
  415.  
  416. const embed = new Discord.RichEmbed()
  417. .setTitle(`${client.user.username} Music Center`)
  418. .addField(`Starting Playing`, `${song.title}`)
  419. .addField(`Duration`, `${song.duration.toFixed(2)} minutes`)
  420. .setFooter("By Soratha#1792")
  421. serverQueue.textChannel.send(embed);
  422. };
  423.  
  424.  
  425. //Auto Role//
  426. client.on('guildMemberAdd', member => {
  427. let embed = new Discord.RichEmbed()
  428. .setDescription('Bienvenue sur le serveur! ' + member.user + ' N\'hésite pas à lire les règles dans #reglement !')
  429. .setFooter('We are actually ' + member.guild.memberCount)
  430. member.guild.channels.get('680890176251363444').send(embed)
  431. member.addRole('663158887578337300')
  432.  
  433. });
  434.  
  435. client.on('guildMemberRemove', member => {
  436. let embed = new Discord.RichEmbed()
  437. .setDescription('See you soon ! ' + member.user)
  438. .setFooter('We are actually ' + member.guild.memberCount)
  439. member.guild.channels.get('680890176251363444').send(embed)
  440.  
  441. });
  442.  
  443. client.on('message', message => {
  444. let args = message.content.substring(prefix.length).split(" ");
  445.  
  446. switch(args[0]){
  447. case 'embed':
  448. const embed = new Discord.RichEmbed()
  449. .setTitle(' Welcome to the server dear people ! ')
  450. .setDescription(' There is some rules that you have to know so take a time to read them')
  451. .addField('```Number 1 : Respect each others```')
  452. .addField('```Number 2 : Don\'t spam```')
  453. message.channel.sendEmbed(embed);
  454. break;
  455.  
  456. }
  457. });
  458.  
  459. client.login(process.env.TOKEN);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement