diff --git a/commands/developer/deleteMap.js b/commands/developer/deleteMap.js
index 892bd22..5423970 100644
--- a/commands/developer/deleteMap.js
+++ b/commands/developer/deleteMap.js
@@ -1,13 +1,13 @@
module.exports = {
config: {
- name: "deleteMap",
- usage: "deleteMap",
+ name: 'deleteMap',
+ usage: 'deleteMap',
aliases: [],
- description: "deleteMap",
+ description: 'deleteMap',
ownerOnly: true,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- client.games.clear();
- },
-};
+ async run (client, message, args) {
+ client.games.clear()
+ }
+}
diff --git a/commands/fun/cattext.js b/commands/fun/cattext.js
index ee55d7b..728e330 100644
--- a/commands/fun/cattext.js
+++ b/commands/fun/cattext.js
@@ -1,18 +1,18 @@
-let neko = require("nekos.life");
-let owo = new neko();
-const { blueMessage, redMessage } = require("../../utils/message");
+const neko = require('nekos.life')
+const owo = new neko()
+const { blueMessage, redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "cattext",
- usage: "cattext",
+ name: 'cattext',
+ usage: 'cattext',
aliases: [],
- description: "Show random cat texts from neko.life server",
+ description: 'Show random cat texts from neko.life server',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let text = await owo.sfw.catText();
- if (!text) return redMessage(message, "Something happened", ":sad:");
- message.reply(text.cat);
- },
-};
+ async run (client, message, args) {
+ const text = await owo.sfw.catText()
+ if (!text) return redMessage(message, 'Something happened', ':sad:')
+ message.reply(text.cat)
+ }
+}
diff --git a/commands/fun/figlet.js b/commands/fun/figlet.js
index 46e4ea2..3f58ba7 100644
--- a/commands/fun/figlet.js
+++ b/commands/fun/figlet.js
@@ -1,30 +1,30 @@
-let figlet = require("figlet");
+const figlet = require('figlet')
module.exports = {
config: {
- name: "figlet",
- usage: "figlet [text]",
- description: "ASCII a text",
+ name: 'figlet',
+ usage: 'figlet [text]',
+ description: 'ASCII a text',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (!args[0]) {
message.channel.send({
embed: {
color: 15158332,
title: "__***YOU THINK I'M A FOOL?***__",
- description: "Input a text"
+ description: 'Input a text'
}
- });
+ })
} else {
- figlet(args.join(" "), function(err, data) {
+ figlet(args.join(' '), function (err, data) {
if (err) {
- console.log("Something went wrong...");
- console.dir(err);
- return;
+ console.log('Something went wrong...')
+ console.dir(err)
+ return
}
- message.channel.send("```" + data + "```");
- });
+ message.channel.send('```' + data + '```')
+ })
}
}
-};
+}
diff --git a/commands/fun/flight.js b/commands/fun/flight.js
index 7231862..558171d 100644
--- a/commands/fun/flight.js
+++ b/commands/fun/flight.js
@@ -1,30 +1,29 @@
module.exports = {
config: {
- name: "flight",
- usage: "flight ",
- description: "Bring a user on a server tour",
+ name: 'flight',
+ usage: 'flight ',
+ description: 'Bring a user on a server tour',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let blacklistArray = ["155622262660268033"];
+ async run (client, message, args) {
+ const blacklistArray = ['155622262660268033']
- let mention = message.mentions.users.first();
- for (let id of blacklistArray) {
- if (mention.id === id)
- return message.reply("Doctor said: Fuck you bicc boi");
+ const mention = message.mentions.users.first()
+ for (const id of blacklistArray) {
+ if (mention.id === id) { return message.reply('Doctor said: Fuck you bicc boi') }
}
- let user = message.guild.members.cache.get(mention.id);
+ const user = message.guild.members.cache.get(mention.id)
const channels = message.guild.channels.cache.filter(
- (c) => c.type === "voice"
- );
- let original = user.voice.channel.id;
+ (c) => c.type === 'voice'
+ )
+ const original = user.voice.channel.id
for (const [channelID, channel] of channels) {
user.voice
.setChannel(channelID)
.then(() => console.log(`Moved ${user.user.tag}.`))
- .catch(console.error);
+ .catch(console.error)
}
- user.voice.setChannel(original);
- },
-};
+ user.voice.setChannel(original)
+ }
+}
diff --git a/commands/fun/fortune.js b/commands/fun/fortune.js
index 4665176..7209938 100644
--- a/commands/fun/fortune.js
+++ b/commands/fun/fortune.js
@@ -1,26 +1,26 @@
-const fetch = require("node-fetch");
-const { MessageEmbed } = require("discord.js");
+const fetch = require('node-fetch')
+const { MessageEmbed } = require('discord.js')
module.exports = {
config: {
- name: "fortune",
- usage: "fortune",
+ name: 'fortune',
+ usage: 'fortune',
aliases: [],
- description: "Send random fortune text",
+ description: 'Send random fortune text',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
try {
- const res = await fetch("http://yerkee.com/api/fortune");
- const json = await res.json();
+ const res = await fetch('http://yerkee.com/api/fortune')
+ const json = await res.json()
const embed = new MessageEmbed()
- .setColor("RANDOM")
- .setTitle("Fortune Cookie")
- .setDescription(json.fortune);
- return message.channel.send(embed);
+ .setColor('RANDOM')
+ .setTitle('Fortune Cookie')
+ .setDescription(json.fortune)
+ return message.channel.send(embed)
} catch (e) {
- message.channel.send("Could not obtain fortune cookie :confused: ");
- return console.error(e);
+ message.channel.send('Could not obtain fortune cookie :confused: ')
+ return console.error(e)
}
- },
-};
+ }
+}
diff --git a/commands/fun/joke.js b/commands/fun/joke.js
index 966a99d..b310f8d 100644
--- a/commands/fun/joke.js
+++ b/commands/fun/joke.js
@@ -1,17 +1,17 @@
-const DadJokes = require("dadjokes-wrapper");
-const joke = new DadJokes();
+const DadJokes = require('dadjokes-wrapper')
+const joke = new DadJokes()
module.exports = {
config: {
- name: "joke",
- usage: "joke",
- description: "Get random joke",
+ name: 'joke',
+ usage: 'joke',
+ description: 'Get random joke',
aliases: [],
enabled: true,
- ownerOnly: false,
+ ownerOnly: false
},
- async run(client, message, args) {
- const dadjoke = await joke.randomJoke();
- message.reply(dadjoke);
- },
-};
+ async run (client, message, args) {
+ const dadjoke = await joke.randomJoke()
+ message.reply(dadjoke)
+ }
+}
diff --git a/commands/fun/renameAll.js b/commands/fun/renameAll.js
index c0bcf83..ed35287 100644
--- a/commands/fun/renameAll.js
+++ b/commands/fun/renameAll.js
@@ -1,55 +1,54 @@
-const { verify } = require("../../utils/utility");
+const { verify } = require('../../utils/utility')
module.exports = {
config: {
- name: "renameAll",
- usage: "renameAll",
+ name: 'renameAll',
+ usage: 'renameAll',
aliases: [],
- description: "Rename every single member of the server",
+ description: 'Rename every single member of the server',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- if (!message.member.hasPermission("ADMINISTRATOR")) return;
- message.channel.send("Nickname ?");
- let collected = await message.channel.awaitMessages(
+ async run (client, message, args) {
+ if (!message.member.hasPermission('ADMINISTRATOR')) return
+ message.channel.send('Nickname ?')
+ const collected = await message.channel.awaitMessages(
m => m.author.id === message.author.id,
{
max: 1,
time: 30000
}
- );
- let nickname = collected.first().content;
+ )
+ const nickname = collected.first().content
try {
await message.reply(
`Are you sure you want to ${
nickname
? `rename everyone to **${nickname}**`
- : "remove all nicknames"
+ : 'remove all nicknames'
}?`
- );
- const verification = await verify(message.channel, message.author);
- if (!verification) return message.say("Aborted.");
- await message.reply("Fetching members...");
- await message.guild.members.fetch();
- await message.reply("Fetched members! Renaming...");
- let i = 0;
+ )
+ const verification = await verify(message.channel, message.author)
+ if (!verification) return message.say('Aborted.')
+ await message.reply('Fetching members...')
+ await message.guild.members.fetch()
+ await message.reply('Fetched members! Renaming...')
+ let i = 0
for (const member of message.guild.members.cache.values()) {
try {
- await member.setNickname(nickname);
+ await member.setNickname(nickname)
} catch {
- i++;
- continue;
+ i++
+ continue
}
}
- if (!nickname)
- return message.reply("Successfully removed all nicknames!");
+ if (!nickname) { return message.reply('Successfully removed all nicknames!') }
return message.reply(
`Successfully renamed all but ${i} member${
- i === 1 ? "" : "s"
+ i === 1 ? '' : 's'
} to **${nickname}**!`
- );
+ )
} catch (err) {
- return message.reply(`Failed to rename everyone: \`${err.message}\``);
+ return message.reply(`Failed to rename everyone: \`${err.message}\``)
}
}
-};
+}
diff --git a/commands/game/mineSweeper.js b/commands/game/mineSweeper.js
index a06e030..a63a11c 100644
--- a/commands/game/mineSweeper.js
+++ b/commands/game/mineSweeper.js
@@ -1,227 +1,225 @@
-const { shuffle, randomRange, chunk } = require("../../utils/gameUtils");
+const { shuffle, randomRange, chunk } = require('../../utils/gameUtils')
const bombcount = [
- ". 1 .",
- ". 2 .",
- ". 3 .",
- ". 4 .",
- ". 5 .",
- ". 6 .",
- ". 7 .",
- ". 8 .",
-];
-const sessions = new Set();
-const { MessageEmbed } = require("discord.js");
+ '. 1 .',
+ '. 2 .',
+ '. 3 .',
+ '. 4 .',
+ '. 5 .',
+ '. 6 .',
+ '. 7 .',
+ '. 8 .'
+]
+const sessions = new Set()
+const { MessageEmbed } = require('discord.js')
module.exports = {
config: {
- name: "mineSweeper",
- usage: "mineSweeper",
+ name: 'mineSweeper',
+ usage: 'mineSweeper',
aliases: [],
- description: "Start a mine sweeper game.",
+ description: 'Start a mine sweeper game.',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- if (sessions.has(message.channel.id))
+ async run (client, message, args) {
+ if (sessions.has(message.channel.id)) {
return message.channel.send(
- "❌ | This game already played in this channel."
- );
- sessions.add(message.channel.id);
+ '❌ | This game already played in this channel.'
+ )
+ }
+ sessions.add(message.channel.id)
try {
- let table = createTable();
- const now = Date.now();
- let mess = null;
- let isDoughBomb = false;
- let escaped = 0;
- let passes = 0;
+ let table = createTable()
+ const now = Date.now()
+ let mess = null
+ let isDoughBomb = false
+ let escaped = 0
+ let passes = 0
while (escaped < 36 - table.bombCount && !isDoughBomb) {
const embed = new MessageEmbed()
- .setColor("BLUE")
- .setDescription(parseTable(table));
+ .setColor('BLUE')
+ .setDescription(parseTable(table))
if (!mess || passes % 4 === 0) {
- if (mess) await mess.delete();
+ if (mess) await mess.delete()
mess = await message.channel.send(
`${message.author}, please response with colum and line. *e.g: A4*, for flagging just passing suffix **F** *e.g: A4F*`,
{ embed }
- );
+ )
} else {
await mess.edit(
`${message.author}, please response with colum and line. *e.g: A4*, for flagging just passing suffix **F** *e.g: A4F*`,
{ embed }
- );
+ )
}
const filter = (m) => {
- const alphabet = ["a", "b", "c", "d", "e", "f"];
- const num = ["1", "2", "3", "4", "5", "6"];
- const [colum, line] = m.content.toLowerCase().split("");
- if (!alphabet.includes(colum) || !num.includes(line)) return false;
- if (table[post(line || "")][post(colum || "")].isDough) return false;
- if (m.content.length > 2 && m.content[2].toLowerCase() !== "f")
- return false;
- return true;
- };
+ const alphabet = ['a', 'b', 'c', 'd', 'e', 'f']
+ const num = ['1', '2', '3', '4', '5', '6']
+ const [colum, line] = m.content.toLowerCase().split('')
+ if (!alphabet.includes(colum) || !num.includes(line)) return false
+ if (table[post(line || '')][post(colum || '')].isDough) return false
+ if (m.content.length > 2 && m.content[2].toLowerCase() !== 'f') { return false }
+ return true
+ }
const response = await message.channel.awaitMessages(filter, {
max: 1,
- time: 30000,
- });
+ time: 30000
+ })
if (!response.size) {
await message.channel.send(
`⏱️ | ${message.author}, you took to long to response. ended game`
- );
- break;
+ )
+ break
}
const [colum, line, flag] = response
.first()
.content.toUpperCase()
- .split("")
- .map((x, i) => (i > 1 ? Boolean(x) : post(x)));
+ .split('')
+ .map((x, i) => (i > 1 ? Boolean(x) : post(x)))
if (flag) {
- table[line][colum].isFlaged = true;
- passes++;
- continue;
+ table[line][colum].isFlaged = true
+ passes++
+ continue
}
- table[line][colum].type === "bomb" ? (isDoughBomb = true) : escaped++;
- table = dig(table, colum, line);
- passes++;
+ table[line][colum].type === 'bomb' ? (isDoughBomb = true) : escaped++
+ table = dig(table, colum, line)
+ passes++
}
- sessions.delete(message.channel.id);
- await mess.delete();
- if (!isDoughBomb && escaped < 36 - table.bombCount) return;
+ sessions.delete(message.channel.id)
+ await mess.delete()
+ if (!isDoughBomb && escaped < 36 - table.bombCount) return
const embed = new MessageEmbed()
- .setColor(isDoughBomb ? "RED" : "GREEN")
- .setDescription(parseTable(table));
+ .setColor(isDoughBomb ? 'RED' : 'GREEN')
+ .setDescription(parseTable(table))
return message.channel.send(
- `${isDoughBomb ? "❌" : "✅"} | ${message.author}, you ended the match${
- isDoughBomb ? " with dug a bomb " : " "
+ `${isDoughBomb ? '❌' : '✅'} | ${message.author}, you ended the match${
+ isDoughBomb ? ' with dug a bomb ' : ' '
}in ${parseTime(Date.now() - now)}`,
{ embed }
- );
+ )
} catch (e) {
- sessions.delete(message.channel.id);
- throw e;
+ sessions.delete(message.channel.id)
+ throw e
}
- function dig(table, colum, line) {
- const init = table[line][colum];
- if (init.type === "bomb") {
+ function dig (table, colum, line) {
+ const init = table[line][colum]
+ if (init.type === 'bomb') {
for (let i = 0; i < 6; i++) {
for (let ii = 0; ii < 6; ii++) {
- if (table[i][ii].type === "floor") continue;
- table[i][ii].isDough = true;
+ if (table[i][ii].type === 'floor') continue
+ table[i][ii].isDough = true
}
}
}
- table[line][colum].isDough = true;
- table[line][colum].isFlaged = false;
- if (!init.count && init.type === "floor") {
+ table[line][colum].isDough = true
+ table[line][colum].isFlaged = false
+ if (!init.count && init.type === 'floor') {
const finalize = (x, y) => {
- table[y][x].isDough = true;
- table[y][x].isFlaged = false;
- if (!table[y][x].count) table = dig(table, x, y);
- };
+ table[y][x].isDough = true
+ table[y][x].isFlaged = false
+ if (!table[y][x].count) table = dig(table, x, y)
+ }
if (
table[line + 1] &&
!table[line + 1][colum].isDough &&
- table[line + 1][colum].type === "floor"
+ table[line + 1][colum].type === 'floor'
) {
- finalize(colum, line + 1);
+ finalize(colum, line + 1)
}
if (
table[line - 1] &&
!table[line - 1][colum].isDough &&
- table[line - 1][colum].type === "floor"
+ table[line - 1][colum].type === 'floor'
) {
- finalize(colum, line - 1);
+ finalize(colum, line - 1)
}
if (
table[line][colum + 1] &&
!table[line][colum + 1].isDough &&
- table[line][colum + 1].type === "floor"
+ table[line][colum + 1].type === 'floor'
) {
- finalize(colum + 1, line);
+ finalize(colum + 1, line)
}
if (
table[line][colum - 1] &&
!table[line][colum - 1].isDough &&
- table[line][colum - 1].type === "floor"
+ table[line][colum - 1].type === 'floor'
) {
- finalize(colum - 1, line);
+ finalize(colum - 1, line)
}
}
- return table;
+ return table
}
- function createTable() {
- let table = [];
- const bombCount = randomRange(8, 13);
+ function createTable () {
+ let table = []
+ const bombCount = randomRange(8, 13)
for (let i = 0; i < 36; i++) {
table.push({
- type: i < bombCount ? "bomb" : "floor",
+ type: i < bombCount ? 'bomb' : 'floor',
isFlaged: false,
isDough: false,
- count: 0,
- });
+ count: 0
+ })
}
- table = shuffle(table);
- table = chunk(table, 6);
- table.bombCount = bombCount;
+ table = shuffle(table)
+ table = chunk(table, 6)
+ table.bombCount = bombCount
for (let x = 0; x < 6; x++) {
for (let y = 0; y < 6; y++) {
- if (table[x][y].type === "bomb") continue;
- if (table[x + 1] && table[x + 1][y].type === "bomb")
- table[x][y].count++;
- if (table[x - 1] && table[x - 1][y].type === "bomb")
- table[x][y].count++;
- if (table[x][y + 1] && table[x][y + 1].type === "bomb") {
- table[x][y].count++;
+ if (table[x][y].type === 'bomb') continue
+ if (table[x + 1] && table[x + 1][y].type === 'bomb') { table[x][y].count++ }
+ if (table[x - 1] && table[x - 1][y].type === 'bomb') { table[x][y].count++ }
+ if (table[x][y + 1] && table[x][y + 1].type === 'bomb') {
+ table[x][y].count++
}
- if (table[x][y - 1] && table[x][y - 1].type === "bomb") {
- table[x][y].count++;
+ if (table[x][y - 1] && table[x][y - 1].type === 'bomb') {
+ table[x][y].count++
}
if (table[x + 1]) {
- if (table[x + 1][y + 1] && table[x + 1][y + 1].type === "bomb") {
- table[x][y].count++;
+ if (table[x + 1][y + 1] && table[x + 1][y + 1].type === 'bomb') {
+ table[x][y].count++
}
- if (table[x + 1][y - 1] && table[x + 1][y - 1].type === "bomb") {
- table[x][y].count++;
+ if (table[x + 1][y - 1] && table[x + 1][y - 1].type === 'bomb') {
+ table[x][y].count++
}
}
if (table[x - 1]) {
- if (table[x - 1][y + 1] && table[x - 1][y + 1].type === "bomb") {
- table[x][y].count++;
+ if (table[x - 1][y + 1] && table[x - 1][y + 1].type === 'bomb') {
+ table[x][y].count++
}
- if (table[x - 1][y - 1] && table[x - 1][y - 1].type === "bomb") {
- table[x][y].count++;
+ if (table[x - 1][y - 1] && table[x - 1][y - 1].type === 'bomb') {
+ table[x][y].count++
}
}
}
}
- return table;
+ return table
}
- function parseTable(table) {
- let result = "⬛🇦 🇧 🇨 🇩 🇪 🇫";
- const numbers = "1⃣ 2⃣ 3⃣ 4⃣ 5⃣ 6⃣".split(" ");
+ function parseTable (table) {
+ let result = '⬛🇦 🇧 🇨 🇩 🇪 🇫'
+ const numbers = '1⃣ 2⃣ 3⃣ 4⃣ 5⃣ 6⃣'.split(' ')
const getEmo = (piece) => {
- if (piece.isFlaged) return "🚩";
- if (!piece.isDough) return "⬜";
- if (piece.count) return bombcount[piece.count - 1];
- return piece.type === "bomb" ? "💣" : "⬛";
- };
+ if (piece.isFlaged) return '🚩'
+ if (!piece.isDough) return '⬜'
+ if (piece.count) return bombcount[piece.count - 1]
+ return piece.type === 'bomb' ? '💣' : '⬛'
+ }
for (let i = 0; i < 6; i++) {
- result += `\n${numbers[i]}${table[i].map(getEmo).join(" ")}`;
+ result += `\n${numbers[i]}${table[i].map(getEmo).join(' ')}`
}
- return result;
+ return result
}
- function post(inpt) {
+ function post (inpt) {
return (
({ A: 1, B: 2, C: 3, D: 4, E: 5, F: 6 }[inpt.toUpperCase()] ||
parseInt(inpt, 10)) - 1
- );
+ )
}
- function parseTime(ms) {
- if (ms >= 59999) return `${Math.round(ms / 60000)}m`;
- return `${ms}ms`;
+ function parseTime (ms) {
+ if (ms >= 59999) return `${Math.round(ms / 60000)}m`
+ return `${ms}ms`
}
- },
-};
+ }
+}
diff --git a/commands/game/slot.js b/commands/game/slot.js
index be98a8c..ac5a55b 100644
--- a/commands/game/slot.js
+++ b/commands/game/slot.js
@@ -1,27 +1,27 @@
-const { stripIndents } = require("common-tags");
-const slots = ["🍇", "🍊", "🍐", "🍒", "🍋"];
+const { stripIndents } = require('common-tags')
+const slots = ['🍇', '🍊', '🍐', '🍒', '🍋']
module.exports = {
config: {
- name: "slot",
- usage: "slot",
- description: "Play slot game.",
- aliases:[],
+ name: 'slot',
+ usage: 'slot',
+ description: 'Play slot game.',
+ aliases: [],
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- const slotOne = slots[Math.floor(Math.random() * slots.length)];
- const slotTwo = slots[Math.floor(Math.random() * slots.length)];
- const slotThree = slots[Math.floor(Math.random() * slots.length)];
+ async run (client, message, args) {
+ const slotOne = slots[Math.floor(Math.random() * slots.length)]
+ const slotTwo = slots[Math.floor(Math.random() * slots.length)]
+ const slotThree = slots[Math.floor(Math.random() * slots.length)]
if (slotOne === slotTwo && slotOne === slotThree) {
return message.reply(stripIndents`
${slotOne}|${slotTwo}|${slotThree}
Wow! You won! Great job... er... luck!
- `);
+ `)
}
return message.reply(stripIndents`
${slotOne}|${slotTwo}|${slotThree}
Aww... You lost... Guess it's just bad luck, huh?
- `);
+ `)
}
-};
+}
diff --git a/commands/game/tictactoe.js b/commands/game/tictactoe.js
index 1a60c7e..54f6b32 100644
--- a/commands/game/tictactoe.js
+++ b/commands/game/tictactoe.js
@@ -1,39 +1,39 @@
-const { stripIndents } = require("common-tags");
+const { stripIndents } = require('common-tags')
const util = require('../../utils/utility')
module.exports = {
config: {
- name: "tictactoe",
- usage: "tictactoe [mention a user]",
+ name: 'tictactoe',
+ usage: 'tictactoe [mention a user]',
aliases: [],
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let opponent = message.mentions.users.first();
- if (opponent.bot) return message.reply("Bots may not be played against.");
- if (opponent.id === message.author.id)
- return message.reply("You may not play against yourself.");
- const current = client.games.get(message.channel.id);
- if (current)
+ async run (client, message, args) {
+ const opponent = message.mentions.users.first()
+ if (opponent.bot) return message.reply('Bots may not be played against.')
+ if (opponent.id === message.author.id) { return message.reply('You may not play against yourself.') }
+ const current = client.games.get(message.channel.id)
+ if (current) {
return message.reply(
`Please wait until the current game of \`${current.name}\` is finished.`
- );
- client.games.set(message.channel.id, { name: this.config.name });
+ )
+ }
+ client.games.set(message.channel.id, { name: this.config.name })
try {
- await message.channel.send(`${opponent}, do you accept this challenge?`);
- const verification = await util.verify(message.channel, opponent);
+ await message.channel.send(`${opponent}, do you accept this challenge?`)
+ const verification = await util.verify(message.channel, opponent)
if (!verification) {
- client.games.delete(message.channel.id);
- return message.channel.send("Looks like they declined...");
+ client.games.delete(message.channel.id)
+ return message.channel.send('Looks like they declined...')
}
- const sides = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
- const taken = [];
- let userTurn = true;
- let winner = null;
+ const sides = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
+ const taken = []
+ let userTurn = true
+ let winner = null
while (!winner && taken.length < 9) {
- const user = userTurn ? message.author : opponent;
- const sign = userTurn ? "X" : "O";
+ const user = userTurn ? message.author : opponent
+ const sign = userTurn ? 'X' : 'O'
await message.channel.send(stripIndents`
${user}, which side do you pick? Type \`end\` to forefeit.
\`\`\`
@@ -43,41 +43,41 @@ module.exports = {
—————————
${sides[6]} | ${sides[7]} | ${sides[8]}
\`\`\`
- `);
+ `)
const filter = res => {
- if (res.author.id !== user.id) return false;
- const choice = res.content;
- if (choice.toLowerCase() === "end") return true;
- return sides.includes(choice) && !taken.includes(choice);
- };
+ if (res.author.id !== user.id) return false
+ const choice = res.content
+ if (choice.toLowerCase() === 'end') return true
+ return sides.includes(choice) && !taken.includes(choice)
+ }
const turn = await message.channel.awaitMessages(filter, {
max: 1,
time: 30000
- });
+ })
if (!turn.size) {
- await message.channel.send("Sorry, time is up!");
- userTurn = !userTurn;
- continue;
+ await message.channel.send('Sorry, time is up!')
+ userTurn = !userTurn
+ continue
}
- const choice = turn.first().content;
- if (choice.toLowerCase() === "end") {
- winner = userTurn ? opponent : message.author;
- break;
+ const choice = turn.first().content
+ if (choice.toLowerCase() === 'end') {
+ winner = userTurn ? opponent : message.author
+ break
}
- sides[Number.parseInt(choice, 10) - 1] = sign;
- taken.push(choice);
- if (verifyWin(sides)) winner = userTurn ? message.author : opponent;
- userTurn = !userTurn;
+ sides[Number.parseInt(choice, 10) - 1] = sign
+ taken.push(choice)
+ if (verifyWin(sides)) winner = userTurn ? message.author : opponent
+ userTurn = !userTurn
}
- client.games.delete(message.channel.id);
+ client.games.delete(message.channel.id)
return message.channel.send(
- winner ? `Congrats, ${winner}!` : "Oh... The cat won."
- );
+ winner ? `Congrats, ${winner}!` : 'Oh... The cat won.'
+ )
} catch (err) {
- client.games.delete(message.channel.id);
- throw err;
+ client.games.delete(message.channel.id)
+ throw err
}
- function verifyWin(sides) {
+ function verifyWin (sides) {
return (
(sides[0] === sides[1] && sides[0] === sides[2]) ||
(sides[0] === sides[3] && sides[0] === sides[6]) ||
@@ -87,7 +87,7 @@ module.exports = {
(sides[2] === sides[5] && sides[2] === sides[8]) ||
(sides[0] === sides[4] && sides[0] === sides[8]) ||
(sides[2] === sides[4] && sides[2] === sides[6])
- );
+ )
}
}
-};
+}
diff --git a/commands/game/warewolf.js b/commands/game/warewolf.js
index bb09e2b..7e172e1 100644
--- a/commands/game/warewolf.js
+++ b/commands/game/warewolf.js
@@ -1,54 +1,54 @@
-let gameModel = require("../../model/warewolf");
-let rules = require("../../config/rules.json");
-let { redMessage, blueMessage } = require("../../utils/message");
+const gameModel = require('../../model/warewolf')
+const rules = require('../../config/rules.json')
+const { redMessage, blueMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "warewolf",
- usage: "warewolf",
+ name: 'warewolf',
+ usage: 'warewolf',
aliases: [],
- description: "Start a warewolf game [9+ users required]",
+ description: 'Start a warewolf game [9+ users required]',
ownerOnly: true,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const serverGame = client.warewolf.get(message.guild.id);
+ async run (client, message, args) {
+ const serverGame = client.warewolf.get(message.guild.id)
if (serverGame) {
message.channel.send(
- "Please stop the previous game before you initialize a new game."
- );
+ 'Please stop the previous game before you initialize a new game.'
+ )
}
if (!serverGame) {
- let ruleFields = [];
- for (let key in rules) {
- ruleFields.push({ name: key, value: rules[key] });
+ const ruleFields = []
+ for (const key in rules) {
+ ruleFields.push({ name: key, value: rules[key] })
}
- let msg = await message.channel.send({
+ const msg = await message.channel.send({
embed: {
- title: "***WELCOME TO TOWN OF WAREWOLF***",
+ title: '***WELCOME TO TOWN OF WAREWOLF***',
color: 3447003,
description:
- "Please read the rule below, and click ✅ to mark yourself ready.",
- fields: ruleFields,
- },
- });
- await msg.react("✅");
- let collected = await message.channel.awaitMessages(
+ 'Please read the rule below, and click ✅ to mark yourself ready.',
+ fields: ruleFields
+ }
+ })
+ await msg.react('✅')
+ const collected = await message.channel.awaitMessages(
(m) =>
m.author.id === message.author.id &&
- m.content.toLowerCase() === "start",
+ m.content.toLowerCase() === 'start',
{
max: 1,
- time: 60000,
+ time: 60000
}
- );
- let user_list = msg.reactions.cache.first().users.cache;
- let players = [];
- for (let user of user_list) {
- if (!user[1].bot) await players.push(user[1]);
+ )
+ const user_list = msg.reactions.cache.first().users.cache
+ const players = []
+ for (const user of user_list) {
+ if (!user[1].bot) await players.push(user[1])
}
if (players.length === 0) {
- throw message.reply("Stop spamming!");
- } else gameModel.init(client, message, players);
+ throw message.reply('Stop spamming!')
+ } else gameModel.init(client, message, players)
}
- },
-};
+ }
+}
diff --git a/commands/game/wordChain.js b/commands/game/wordChain.js
index 307d327..9b32233 100644
--- a/commands/game/wordChain.js
+++ b/commands/game/wordChain.js
@@ -1,126 +1,126 @@
-const { stripIndents } = require("common-tags");
-const startWords = require("../../assets/json/word-list");
-const util = require("../../utils/utility");
-const { redMessage } = require("../../utils/message");
-var checkWord = require("spellchecker");
-var request = require("request");
+const { stripIndents } = require('common-tags')
+const startWords = require('../../assets/json/word-list')
+const util = require('../../utils/utility')
+const { redMessage } = require('../../utils/message')
+var checkWord = require('spellchecker')
+var request = require('request')
module.exports = {
config: {
- name: "wordChain",
- usage: "wordChain",
- description: "Challenge a user to play word following game.",
+ name: 'wordChain',
+ usage: 'wordChain',
+ description: 'Challenge a user to play word following game.',
aliases: [],
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, msg, args) {
- let message = msg;
- let time = 10;
- const opponent = message.mentions.users.first();
+ async run (client, msg, args) {
+ const message = msg
+ const time = 10
+ const opponent = message.mentions.users.first()
- if (opponent.bot) return msg.reply("Bots may not be played against.");
- if (opponent.id === msg.author.id)
- return msg.reply("You may not play against yourself.");
- const current = client.games.get(msg.channel.id);
- if (current)
+ if (opponent.bot) return msg.reply('Bots may not be played against.')
+ if (opponent.id === msg.author.id) { return msg.reply('You may not play against yourself.') }
+ const current = client.games.get(msg.channel.id)
+ if (current) {
return msg.reply(
`Please wait until the current game of \`${current.name}\` is finished.`
- );
- client.games.set(msg.channel.id, { name: this.name });
+ )
+ }
+ client.games.set(msg.channel.id, { name: this.name })
try {
- await msg.reply(`${opponent}, do you accept this challenge?`);
- const verification = await util.verify(msg.channel, opponent);
+ await msg.reply(`${opponent}, do you accept this challenge?`)
+ const verification = await util.verify(msg.channel, opponent)
if (!verification) {
- client.games.delete(msg.channel.id);
- return msg.reply("Looks like they declined...");
+ client.games.delete(msg.channel.id)
+ return msg.reply('Looks like they declined...')
}
const startWord =
- startWords[Math.floor(Math.random() * startWords.length)];
+ startWords[Math.floor(Math.random() * startWords.length)]
await msg.reply(stripIndents`
The start word will be **${startWord}**! You must answer within **${time}** seconds!
If you think your opponent has played a word that doesn't exist, respond with **challenge** on your turn.
Words cannot contain anything but letters. No numbers, spaces, or hyphens may be used.
The game will start in 5 seconds...
- `);
- await util.delay(5000);
- let userTurn = Boolean(Math.floor(Math.random() * 2));
- const words = [];
- let winner = null;
- let lastWord = startWord;
+ `)
+ await util.delay(5000)
+ let userTurn = Boolean(Math.floor(Math.random() * 2))
+ const words = []
+ let winner = null
+ let lastWord = startWord
while (!winner) {
- const player = userTurn ? msg.author : opponent;
- const letter = lastWord.charAt(lastWord.length - 1);
+ const player = userTurn ? msg.author : opponent
+ const letter = lastWord.charAt(lastWord.length - 1)
await msg.channel.send(
`It's ${player}'s turn! The letter is **${letter}**.`
- );
+ )
const filter = (res) =>
res.author.id === player.id &&
/^[a-zA-Z']+$/i.test(res.content) &&
- res.content.length < 50;
+ res.content.length < 50
const wordChoice = await msg.channel.awaitMessages(filter, {
max: 1,
- time: time * 1000,
- });
+ time: time * 1000
+ })
const misspelled = await checkWord.isMisspelled(
wordChoice.first().content.toLowerCase()
- );
+ )
if (misspelled) {
- await msg.reply("Sorry! You lose!");
- winner = opponent;
- break;
+ await msg.reply('Sorry! You lose!')
+ winner = opponent
+ break
}
if (!wordChoice.size) {
- await msg.reply("Time!");
- winner = userTurn ? opponent : msg.author;
- break;
+ await msg.reply('Time!')
+ winner = userTurn ? opponent : msg.author
+ break
}
- const choice = wordChoice.first().content.toLowerCase();
- if (choice === "challenge") {
- const checked = await verifyWord(lastWord);
+ const choice = wordChoice.first().content.toLowerCase()
+ if (choice === 'challenge') {
+ const checked = await verifyWord(lastWord)
if (!checked) {
- await msg.reply(`Caught red-handed! **${lastWord}** is not valid!`);
- winner = player;
- break;
+ await msg.reply(`Caught red-handed! **${lastWord}** is not valid!`)
+ winner = player
+ break
}
- await msg.reply(`Sorry, **${lastWord}** is indeed valid!`);
- continue;
+ await msg.reply(`Sorry, **${lastWord}** is indeed valid!`)
+ continue
}
if (!choice.startsWith(letter) || words.includes(choice)) {
- await msg.reply("Sorry! You lose!");
- winner = userTurn ? opponent : msg.author;
- break;
+ await msg.reply('Sorry! You lose!')
+ winner = userTurn ? opponent : msg.author
+ break
}
- words.push(choice);
- lastWord = choice;
- userTurn = !userTurn;
+ words.push(choice)
+ lastWord = choice
+ userTurn = !userTurn
}
- client.games.delete(msg.channel.id);
- if (!winner) return msg.reply("Oh... No one won.");
- msg.channel.send(`The game is over! The winner is ${winner}!`);
- let a = "";
- for (let word of words) {
- a = a + word + ", ";
+ client.games.delete(msg.channel.id)
+ if (!winner) return msg.reply('Oh... No one won.')
+ msg.channel.send(`The game is over! The winner is ${winner}!`)
+ let a = ''
+ for (const word of words) {
+ a = a + word + ', '
}
- redMessage(message, "Game result", a);
+ redMessage(message, 'Game result', a)
} catch (err) {
- client.games.delete(msg.channel.id);
- throw err;
+ client.games.delete(msg.channel.id)
+ throw err
}
- async function verifyWord(word) {
- if (startWords.includes(word.toLowerCase())) return true;
+ async function verifyWord (word) {
+ if (startWords.includes(word.toLowerCase())) return true
try {
const { body } = await request
.get(
`https://www.dictionaryapi.com/api/v3/references/collegiate/json/${word}`
)
- .query({ key: "032fbf78-d658-49c9-afc7-4c6f1d420d15" });
- console.log(body);
- if (!body.length) return false;
- return true;
+ .query({ key: '032fbf78-d658-49c9-afc7-4c6f1d420d15' })
+ console.log(body)
+ if (!body.length) return false
+ return true
} catch (err) {
- if (err.status === 404) return false;
- return null;
+ if (err.status === 404) return false
+ return null
}
}
- },
-};
+ }
+}
diff --git a/commands/image/achievement.js b/commands/image/achievement.js
index f6ac43a..665a4b2 100644
--- a/commands/image/achievement.js
+++ b/commands/image/achievement.js
@@ -1,41 +1,41 @@
-const { createCanvas, loadImage, registerFont } = require("canvas");
-const path = require("path");
-const util = require("../../utils/utility");
+const { createCanvas, loadImage, registerFont } = require('canvas')
+const path = require('path')
+const util = require('../../utils/utility')
registerFont(
- path.join(__dirname, "..", "..", "assets", "fonts", "Minecraftia.ttf"),
- { family: "Minecraftia" }
-);
+ path.join(__dirname, '..', '..', 'assets', 'fonts', 'Minecraftia.ttf'),
+ { family: 'Minecraftia' }
+)
module.exports = {
config: {
- name: "achievement",
- usage: "achievement",
- description: "Draw custom achievement",
+ name: 'achievement',
+ usage: 'achievement',
+ description: 'Draw custom achievement',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- message.channel.send("What text you wanna create ?");
- let collected = await message.channel.awaitMessages(
+ async run (client, message, args) {
+ message.channel.send('What text you wanna create ?')
+ const collected = await message.channel.awaitMessages(
m => m.author.id === message.author.id,
{
max: 1,
time: 30000
}
- );
+ )
const base = await loadImage(
- path.join(__dirname, "..", "..", "assets", "achievement.png")
- );
- const canvas = createCanvas(base.width, base.height);
- const ctx = canvas.getContext("2d");
- ctx.drawImage(base, 0, 0);
- ctx.font = "17px Minecraftia";
- ctx.fillStyle = "#ffff00";
- ctx.fillText("Achievement Get!", 60, 40);
- ctx.fillStyle = "#ffffff";
- ctx.fillText(util.shortenText(ctx, collected.first().content, 230), 60, 60);
+ path.join(__dirname, '..', '..', 'assets', 'achievement.png')
+ )
+ const canvas = createCanvas(base.width, base.height)
+ const ctx = canvas.getContext('2d')
+ ctx.drawImage(base, 0, 0)
+ ctx.font = '17px Minecraftia'
+ ctx.fillStyle = '#ffff00'
+ ctx.fillText('Achievement Get!', 60, 40)
+ ctx.fillStyle = '#ffffff'
+ ctx.fillText(util.shortenText(ctx, collected.first().content, 230), 60, 60)
return message.channel.send({
- files: [{ attachment: canvas.toBuffer(), name: "achievement.png" }]
- });
+ files: [{ attachment: canvas.toBuffer(), name: 'achievement.png' }]
+ })
}
-};
+}
diff --git a/commands/image/anime.js b/commands/image/anime.js
index 44766a8..a2516ae 100644
--- a/commands/image/anime.js
+++ b/commands/image/anime.js
@@ -1,22 +1,21 @@
-const fetch = require("node-fetch");
+const fetch = require('node-fetch')
module.exports = {
config: {
- name: "anime",
- usage: "anime",
- description: "Show random anime gif",
+ name: 'anime',
+ usage: 'anime',
+ description: 'Show random anime gif',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
fetch(
`https://api.tenor.com/v1/random?key=${process.env.tenorAPI}&q=anime&limit=1`
)
.then((res) => res.json())
.then((json) => message.channel.send(json.results[0].url))
.catch((e) => {
- message.channel.send("Failed to find a gif :slight_frown:");
+ message.channel.send('Failed to find a gif :slight_frown:')
// console.error(e);
- return;
- });
- },
-};
+ })
+ }
+}
diff --git a/commands/image/bobRoss.js b/commands/image/bobRoss.js
index 8edfc5d..4e3cdf0 100644
--- a/commands/image/bobRoss.js
+++ b/commands/image/bobRoss.js
@@ -1,38 +1,38 @@
-const { createCanvas, loadImage } = require("canvas");
-const request = require("node-superfetch");
-const path = require("path");
+const { createCanvas, loadImage } = require('canvas')
+const request = require('node-superfetch')
+const path = require('path')
module.exports = {
config: {
- name: "bobRoss",
- usage: "bobRoss",
+ name: 'bobRoss',
+ usage: 'bobRoss',
aliases: [],
- description: "Tell Bob Ross to draw a picture of you",
+ description: 'Tell Bob Ross to draw a picture of you',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
const avatarURL = await message.guild.members.cache
.get(message.author.id)
- .user.displayAvatarURL({ format: "png", size: 512 });
+ .user.displayAvatarURL({ format: 'png', size: 512 })
try {
const base = await loadImage(
- path.join(__dirname, "..", "..", "assets", "bob-ross.png")
- );
- const { body } = await request.get(avatarURL);
- const avatar = await loadImage(body);
- const canvas = createCanvas(base.width, base.height);
- const ctx = canvas.getContext("2d");
- ctx.fillStyle = "white";
- ctx.fillRect(0, 0, base.width, base.height);
- ctx.drawImage(avatar, 15, 20, 440, 440);
- ctx.drawImage(base, 0, 0);
+ path.join(__dirname, '..', '..', 'assets', 'bob-ross.png')
+ )
+ const { body } = await request.get(avatarURL)
+ const avatar = await loadImage(body)
+ const canvas = createCanvas(base.width, base.height)
+ const ctx = canvas.getContext('2d')
+ ctx.fillStyle = 'white'
+ ctx.fillRect(0, 0, base.width, base.height)
+ ctx.drawImage(avatar, 15, 20, 440, 440)
+ ctx.drawImage(base, 0, 0)
return message.channel.send({
- files: [{ attachment: canvas.toBuffer(), name: "bob-ross.png" }]
- });
+ files: [{ attachment: canvas.toBuffer(), name: 'bob-ross.png' }]
+ })
} catch (err) {
return message.reply(
`Oh no, an error occurred: \`${err.message}\`. Try again later!`
- );
+ )
}
}
-};
+}
diff --git a/commands/image/cat.js b/commands/image/cat.js
index c98d4bd..65eb0dc 100644
--- a/commands/image/cat.js
+++ b/commands/image/cat.js
@@ -1,52 +1,52 @@
-let request = require("request-promise-native");
-let cheerio = require("cheerio");
+const request = require('request-promise-native')
+const cheerio = require('cheerio')
module.exports = {
config: {
- name: "cat",
- usage: "cat",
- description: "Show random cat image",
+ name: 'cat',
+ usage: 'cat',
+ description: 'Show random cat image',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let fact = await request(
- "https://some-random-api.ml/facts/cat",
- async function(error, response, body) {
- let data = await JSON.parse(body);
- return data;
+ async run (client, message, args) {
+ const fact = await request(
+ 'https://some-random-api.ml/facts/cat',
+ async function (error, response, body) {
+ const data = await JSON.parse(body)
+ return data
}
- );
- let options = {
- method: "HEAD",
- url: "https://thecatapi.com/api/images/get",
+ )
+ const options = {
+ method: 'HEAD',
+ url: 'https://thecatapi.com/api/images/get',
followAllRedirects: true,
resolveWithFullResponse: true
- };
- var r = request(options.url, function(e, response) {
- //console.log(response.request.uri.Url.href);
- });
- if (message.content.includes("--fact")) {
- request(options).then(function(body) {
+ }
+ var r = request(options.url, function (e, response) {
+ // console.log(response.request.uri.Url.href);
+ })
+ if (message.content.includes('--fact')) {
+ request(options).then(function (body) {
message.channel.send({
embed: {
color: 3447003,
- fields: [{ name: "Fact", value: JSON.parse(fact).fact }],
+ fields: [{ name: 'Fact', value: JSON.parse(fact).fact }],
image: {
url: r.uri.href
},
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
- });
+ })
+ })
} else {
- request(options).then(function(body) {
+ request(options).then(function (body) {
message.channel.send({
embed: {
color: 3447003,
@@ -56,14 +56,14 @@ module.exports = {
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
- });
+ })
+ })
}
}
-};
+}
diff --git a/commands/image/catStatusCode.js b/commands/image/catStatusCode.js
index 83684a5..8eceeeb 100644
--- a/commands/image/catStatusCode.js
+++ b/commands/image/catStatusCode.js
@@ -1,18 +1,18 @@
module.exports = {
config: {
- name: "catStatusCode",
- usage: "",
- aliases: ["catus"],
- description: "",
+ name: 'catStatusCode',
+ usage: '',
+ aliases: ['catus'],
+ description: '',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- if (!args[0]) return message.reply("Please provide a status code.");
+ async run (client, message, args) {
+ if (!args[0]) return message.reply('Please provide a status code.')
const referenceUrl =
- "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/";
+ 'https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/'
try {
- const statusCode = args[0];
+ const statusCode = args[0]
const status_codes = [
100,
101,
@@ -70,21 +70,21 @@ module.exports = {
509,
510,
511,
- 599,
- ];
+ 599
+ ]
if (status_codes.includes(parseInt(statusCode))) {
- message.reply(`https://http.cat/${statusCode}`);
+ message.reply(`https://http.cat/${statusCode}`)
message.reply(
`For more information, see: <${referenceUrl}${statusCode}>`
- );
+ )
} else {
message.reply(
"Sorry, the cats of the HTTP underworld don't recognize that code."
- );
+ )
}
} catch (error) {
- console.error(error);
+ console.error(error)
}
- },
-};
+ }
+}
diff --git a/commands/image/fox.js b/commands/image/fox.js
index 37d0270..197b4b0 100644
--- a/commands/image/fox.js
+++ b/commands/image/fox.js
@@ -1,23 +1,23 @@
-let request = require("request-promise-native");
-let cheerio = require("cheerio");
-let req = require("request");
+const request = require('request-promise-native')
+const cheerio = require('cheerio')
+const req = require('request')
module.exports = {
config: {
- name: "fox",
- usage: "fox",
- description: "Show random fox image",
+ name: 'fox',
+ usage: 'fox',
+ description: 'Show random fox image',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- req("https://randomfox.ca/floof/", function(error, response, body) {
+ async run (client, message, args) {
+ req('https://randomfox.ca/floof/', function (error, response, body) {
if (error) {
return message.channel.send({
embed: {
color: 15158332,
- title: "__***N I G G E R***__ something went wrong"
+ title: '__***N I G G E R***__ something went wrong'
}
- });
+ })
}
message.channel.send({
embed: {
@@ -28,13 +28,13 @@ module.exports = {
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
- });
+ })
+ })
}
-};
+}
diff --git a/commands/image/hqimage.js b/commands/image/hqimage.js
index b99f666..b2cd856 100644
--- a/commands/image/hqimage.js
+++ b/commands/image/hqimage.js
@@ -1,25 +1,25 @@
-let request = require("request-promise-native");
-let cheerio = require("cheerio");
-let rq = require("request");
+const request = require('request-promise-native')
+const cheerio = require('cheerio')
+const rq = require('request')
module.exports = {
config: {
- name: "hqimage",
- usage: "hqimage",
- description: "Show random high quality image",
+ name: 'hqimage',
+ usage: 'hqimage',
+ description: 'Show random high quality image',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let options = {
- method: "GET",
- url: "https://picsum.photos/1920/1080",
+ async run (client, message, args) {
+ const options = {
+ method: 'GET',
+ url: 'https://picsum.photos/1920/1080',
followAllRedirects: true,
resolveWithFullResponse: true
- };
- var r = request(options.url, function(e, response) {
- //console.log(response.request.uri.Url.href);
- });
- request(options).then(function(body) {
+ }
+ var r = request(options.url, function (e, response) {
+ // console.log(response.request.uri.Url.href);
+ })
+ request(options).then(function (body) {
message.channel.send({
embed: {
color: 3447003,
@@ -29,13 +29,13 @@ module.exports = {
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
- });
+ })
+ })
}
-};
+}
diff --git a/commands/image/invert.js b/commands/image/invert.js
index 6931c95..cfd0e3d 100644
--- a/commands/image/invert.js
+++ b/commands/image/invert.js
@@ -1,35 +1,34 @@
-const { createCanvas, loadImage } = require("canvas");
-const request = require("node-superfetch");
-const util = require("../../utils/utility");
+const { createCanvas, loadImage } = require('canvas')
+const request = require('node-superfetch')
+const util = require('../../utils/utility')
module.exports = {
config: {
- name: "invert",
- usage: "invert",
+ name: 'invert',
+ usage: 'invert',
aliases: [],
- description: "Your avatar but inverted color",
+ description: 'Your avatar but inverted color',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let image = message.author.displayAvatarURL({ format: "png", size: 512 });
+ async run (client, message, args) {
+ const image = message.author.displayAvatarURL({ format: 'png', size: 512 })
try {
- const { body } = await request.get(image);
- const data = await loadImage(body);
- const canvas = createCanvas(data.width, data.height);
- const ctx = canvas.getContext("2d");
- ctx.drawImage(data, 0, 0);
- util.invert(ctx, 0, 0, data.width, data.height);
- const attachment = canvas.toBuffer();
- if (Buffer.byteLength(attachment) > 8e6)
- return msg.reply("Resulting image was above 8 MB.");
+ const { body } = await request.get(image)
+ const data = await loadImage(body)
+ const canvas = createCanvas(data.width, data.height)
+ const ctx = canvas.getContext('2d')
+ ctx.drawImage(data, 0, 0)
+ util.invert(ctx, 0, 0, data.width, data.height)
+ const attachment = canvas.toBuffer()
+ if (Buffer.byteLength(attachment) > 8e6) { return msg.reply('Resulting image was above 8 MB.') }
return message.channel.send({
- files: [{ attachment, name: "invert.png" }]
- });
+ files: [{ attachment, name: 'invert.png' }]
+ })
} catch (err) {
return message.reply(
`Oh no, an error occurred: \`${err.message}\`. Try again later!`
- );
+ )
}
}
-};
+}
diff --git a/commands/image/meme.js b/commands/image/meme.js
index 1736246..311979c 100644
--- a/commands/image/meme.js
+++ b/commands/image/meme.js
@@ -1,27 +1,27 @@
-let request = require("request-promise-native");
-let cheerio = require("cheerio");
+const request = require('request-promise-native')
+const cheerio = require('cheerio')
module.exports = {
config: {
- name: "meme",
- usage: "meme",
- description: "Show random meme",
+ name: 'meme',
+ usage: 'meme',
+ description: 'Show random meme',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- request("https://some-random-api.ml/meme", function(error, response, body) {
- let data = JSON.parse(body);
- console.log(data);
+ async run (client, message, args) {
+ request('https://some-random-api.ml/meme', function (error, response, body) {
+ const data = JSON.parse(body)
+ console.log(data)
message.channel.send({
embed: {
color: 3447003,
fields: [
{
- name: "Caption",
+ name: 'Caption',
value: data.caption
},
{
- name: "Category",
+ name: 'Category',
value: data.category
}
],
@@ -29,7 +29,7 @@ module.exports = {
url: data.image
}
}
- });
- });
+ })
+ })
}
-};
+}
diff --git a/commands/image/nekoAvatar.js b/commands/image/nekoAvatar.js
index 1f0ef73..6da1c7f 100644
--- a/commands/image/nekoAvatar.js
+++ b/commands/image/nekoAvatar.js
@@ -1,18 +1,18 @@
-let neko = require("nekos.life");
-let owo = new neko();
-const { blueMessage, redMessage } = require("../../utils/message");
+const neko = require('nekos.life')
+const owo = new neko()
+const { blueMessage, redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "nekoAvatar",
- usage: "nekoAvatar",
+ name: 'nekoAvatar',
+ usage: 'nekoAvatar',
aliases: [],
- description: "Show random neko avatar",
+ description: 'Show random neko avatar',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let img = await owo.sfw.avatar();
- if (!img) return redMessage(message, "Something happened", ":sad:");
- message.channel.send(img.url);
- },
-};
+ async run (client, message, args) {
+ const img = await owo.sfw.avatar()
+ if (!img) return redMessage(message, 'Something happened', ':sad:')
+ message.channel.send(img.url)
+ }
+}
diff --git a/commands/image/nekogif.js b/commands/image/nekogif.js
index ef2c4b7..9dd7f89 100644
--- a/commands/image/nekogif.js
+++ b/commands/image/nekogif.js
@@ -1,18 +1,18 @@
-let neko = require("nekos.life");
-let owo = new neko();
-const { blueMessage, redMessage } = require("../../utils/message");
+const neko = require('nekos.life')
+const owo = new neko()
+const { blueMessage, redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "nekogif",
- usage: "nekogif",
+ name: 'nekogif',
+ usage: 'nekogif',
aliases: [],
- description: "Show random neko gif",
+ description: 'Show random neko gif',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let img = (await owo.sfw.nekoGif());
- if (!img) return redMessage(message, "Something happened", ":sad:");
+ async run (client, message, args) {
+ const img = (await owo.sfw.nekoGif())
+ if (!img) return redMessage(message, 'Something happened', ':sad:')
message.channel.send(img.url)
- },
-};
+ }
+}
diff --git a/commands/image/newspaper.js b/commands/image/newspaper.js
index a5bbb46..52e208b 100644
--- a/commands/image/newspaper.js
+++ b/commands/image/newspaper.js
@@ -1,41 +1,41 @@
-const request = require("node-superfetch");
-const moment = require("moment");
+const request = require('node-superfetch')
+const moment = require('moment')
module.exports = {
config: {
- name: "newspaper",
- usage: "newspaper",
+ name: 'newspaper',
+ usage: 'newspaper',
aliases: [],
- description: "Draw a fake newspaper",
+ description: 'Draw a fake newspaper',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- message.channel.send("Nhap headline va body trong 2 tin nhan");
- let collected = await message.channel.awaitMessages(
+ async run (client, message, args) {
+ message.channel.send('Nhap headline va body trong 2 tin nhan')
+ const collected = await message.channel.awaitMessages(
(m) => m.author.id === message.author.id,
{
max: 2,
- time: 30000,
+ time: 30000
}
- );
- let headline = collected.array()[0].content;
- let body = collected.array()[1].content;
- if (!headline || !body) return message.reply("STOP SPAMMING NIGGER!");
+ )
+ const headline = collected.array()[0].content
+ const body = collected.array()[1].content
+ if (!headline || !body) return message.reply('STOP SPAMMING NIGGER!')
try {
const { text } = await request
- .post("https://www.fodey.com/generators/newspaper/snippet.asp")
- .attach("name", "The Daily Whatever")
- .attach("date", moment().format("dddd, MMMM D, YYYY"))
- .attach("headline", headline)
- .attach("text", body);
+ .post('https://www.fodey.com/generators/newspaper/snippet.asp')
+ .attach('name', 'The Daily Whatever')
+ .attach('date', moment().format('dddd, MMMM D, YYYY'))
+ .attach('headline', headline)
+ .attach('text', body)
const newspaperURL = text.match(
/
8e6)
- return message.reply("Resulting image was above 8 MB.");
+ )
+ const attachment = canvas.toBuffer()
+ if (Buffer.byteLength(attachment) > 8e6) { return message.reply('Resulting image was above 8 MB.') }
return message.channel.send({
- files: [{ attachment, name: "pixelize.png" }]
- });
+ files: [{ attachment, name: 'pixelize.png' }]
+ })
} catch (err) {
return message.reply(
`Oh no, an error occurred: \`${err.message}\`. Try again later!`
- );
+ )
}
}
-};
+}
diff --git a/commands/image/qrCode.js b/commands/image/qrCode.js
index 41a65d4..211f418 100644
--- a/commands/image/qrCode.js
+++ b/commands/image/qrCode.js
@@ -1,33 +1,33 @@
-const request = require("node-superfetch");
+const request = require('node-superfetch')
module.exports = {
config: {
- name: "qrCode",
- usage: "qrCode",
+ name: 'qrCode',
+ usage: 'qrCode',
aliases: [],
- description: "Create qrCode for custom text",
+ description: 'Create qrCode for custom text',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- message.channel.send("What text you wanna create ?");
- let collected = await message.channel.awaitMessages(
+ async run (client, message, args) {
+ message.channel.send('What text you wanna create ?')
+ const collected = await message.channel.awaitMessages(
m => m.author.id === message.author.id,
{
max: 1,
time: 30000
}
- );
- let text = collected.first().content;
+ )
+ const text = collected.first().content
try {
const { body } = await request
- .get("https://api.qrserver.com/v1/create-qr-code/")
- .query({ data: text });
- return message.channel.send({ files: [{ attachment: body, name: "qr-code.png" }] });
+ .get('https://api.qrserver.com/v1/create-qr-code/')
+ .query({ data: text })
+ return message.channel.send({ files: [{ attachment: body, name: 'qr-code.png' }] })
} catch (err) {
return message.reply(
`Oh no, an error occurred: \`${err.message}\`. Try again later!`
- );
+ )
}
}
-};
+}
diff --git a/commands/image/rejected.js b/commands/image/rejected.js
index e2130a5..4283945 100644
--- a/commands/image/rejected.js
+++ b/commands/image/rejected.js
@@ -1,40 +1,39 @@
-const { createCanvas, loadImage } = require("canvas");
-const request = require("node-superfetch");
-const path = require("path");
-const util = require("../../utils/utility");
+const { createCanvas, loadImage } = require('canvas')
+const request = require('node-superfetch')
+const path = require('path')
+const util = require('../../utils/utility')
module.exports = {
config: {
- name: "rejected",
- usage: "rejected",
+ name: 'rejected',
+ usage: 'rejected',
aliases: [],
- description: "Put a rejected stamp on your avatar",
+ description: 'Put a rejected stamp on your avatar',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let image = message.author.displayAvatarURL({ format: "png", size: 512 });
+ async run (client, message, args) {
+ const image = message.author.displayAvatarURL({ format: 'png', size: 512 })
try {
const base = await loadImage(
- path.join(__dirname, "..", "..", "assets", "rejected.png")
- );
- const { body } = await request.get(image);
- const data = await loadImage(body);
- const canvas = createCanvas(data.width, data.height);
- const ctx = canvas.getContext("2d");
- ctx.drawImage(data, 0, 0);
- const { x, y, width, height } = util.centerImage(base, data);
- ctx.drawImage(base, x, y, width, height);
- const attachment = canvas.toBuffer();
- if (Buffer.byteLength(attachment) > 8e6)
- return message.reply("Resulting image was above 8 MB.");
+ path.join(__dirname, '..', '..', 'assets', 'rejected.png')
+ )
+ const { body } = await request.get(image)
+ const data = await loadImage(body)
+ const canvas = createCanvas(data.width, data.height)
+ const ctx = canvas.getContext('2d')
+ ctx.drawImage(data, 0, 0)
+ const { x, y, width, height } = util.centerImage(base, data)
+ ctx.drawImage(base, x, y, width, height)
+ const attachment = canvas.toBuffer()
+ if (Buffer.byteLength(attachment) > 8e6) { return message.reply('Resulting image was above 8 MB.') }
return message.channel.send({
- files: [{ attachment, name: "rejected.png" }]
- });
+ files: [{ attachment, name: 'rejected.png' }]
+ })
} catch (err) {
return message.reply(
`Oh no, an error occurred: \`${err.message}\`. Try again later!`
- );
+ )
}
}
-};
+}
diff --git a/commands/image/robohash.js b/commands/image/robohash.js
index d3ba708..a3d300c 100644
--- a/commands/image/robohash.js
+++ b/commands/image/robohash.js
@@ -1,30 +1,30 @@
-const request = require("node-superfetch");
+const request = require('node-superfetch')
module.exports = {
config: {
- name: "roboHash",
- usage: "roboHash",
+ name: 'roboHash',
+ usage: 'roboHash',
aliases: [],
- description: "idk",
+ description: 'idk',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- message.channel.send("Input a text to create random robo");
- let collected = await message.channel.awaitMessages(
+ async run (client, message, args) {
+ message.channel.send('Input a text to create random robo')
+ const collected = await message.channel.awaitMessages(
m => m.author.id === message.author.id,
{
max: 1,
time: 30000
}
- );
- let text = collected.first().content;
+ )
+ const text = collected.first().content
try {
- const { body } = await request.get(`https://robohash.org/${text}`);
- return message.channel.send({ files: [{ attachment: body, name: "robohash.png" }] });
+ const { body } = await request.get(`https://robohash.org/${text}`)
+ return message.channel.send({ files: [{ attachment: body, name: 'robohash.png' }] })
} catch (err) {
return message.reply(
`Oh no, an error occurred: \`${err.message}\`. Try again later!`
- );
+ )
}
}
-};
+}
diff --git a/commands/info/autonews.js b/commands/info/autonews.js
index 7e7d842..59545f2 100644
--- a/commands/info/autonews.js
+++ b/commands/info/autonews.js
@@ -1,21 +1,21 @@
-let util = require("../../utils/utility");
-let config = require("../../config/config.json");
+const util = require('../../utils/utility')
+const config = require('../../config/config.json')
module.exports = {
config: {
- name: "autonews",
- usage: "autonews",
- description: "Enable auto update news from VNEXPRESS",
+ name: 'autonews',
+ usage: 'autonews',
+ description: 'Enable auto update news from VNEXPRESS',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- if (message.content.includes("--stop")) {
- clearInterval(newsInterval);
+ async run (client, message, args) {
+ if (message.content.includes('--stop')) {
+ clearInterval(newsInterval)
} else {
- newsInterval = setInterval(async function() {
- await util.sendNews(message);
- util.updateNews();
- }, config.timer);
+ newsInterval = setInterval(async function () {
+ await util.sendNews(message)
+ util.updateNews()
+ }, config.timer)
}
}
-};
+}
diff --git a/commands/info/avatar.js b/commands/info/avatar.js
index 5998815..46302b9 100644
--- a/commands/info/avatar.js
+++ b/commands/info/avatar.js
@@ -1,46 +1,46 @@
module.exports = {
config: {
- name: "avatar",
- usage: "avatar @user",
- aliases: ["avt"],
- description: "Show the default resolution of a user avatar",
+ name: 'avatar',
+ usage: 'avatar @user',
+ aliases: ['avt'],
+ description: 'Show the default resolution of a user avatar',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (message.mentions.users.first()) {
message.channel.send({
embed: {
color: 3447003,
fields: [
{
- name: "Avatar",
+ name: 'Avatar',
value: message.mentions.users.first().tag
}
],
image: {
url: message.mentions.users
.first()
- .avatarURL({ format: "png", dynamic: true, size: 1024 })
+ .avatarURL({ format: 'png', dynamic: true, size: 1024 })
},
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
}
if (!message.mentions.users.first()) {
return message.channel.send({
embed: {
color: 15158332,
- title: "You have to mention the one who want me to get avatar"
+ title: 'You have to mention the one who want me to get avatar'
}
- });
+ })
}
}
-};
+}
diff --git a/commands/info/channelInfo.js b/commands/info/channelInfo.js
index 470d617..a728da1 100644
--- a/commands/info/channelInfo.js
+++ b/commands/info/channelInfo.js
@@ -1,54 +1,54 @@
-const moment = require("moment");
-const { MessageEmbed } = require("discord.js");
+const moment = require('moment')
+const { MessageEmbed } = require('discord.js')
const types = {
- dm: "DM",
- group: "Group DM",
- text: "Text Channel",
- voice: "Voice Channel",
- category: "Category",
- unknown: "Unknown"
-};
+ dm: 'DM',
+ group: 'Group DM',
+ text: 'Text Channel',
+ voice: 'Voice Channel',
+ category: 'Category',
+ unknown: 'Unknown'
+}
module.exports = {
config: {
- name: "channelInfo",
- usage: "channelInfo",
+ name: 'channelInfo',
+ usage: 'channelInfo',
aliases: [],
- description: "Show current channel info",
+ description: 'Show current channel info',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let channel;
- if (!args[0]) channel = message.channel;
+ async run (client, message, args) {
+ let channel
+ if (!args[0]) channel = message.channel
else {
- let temp = message.guild.channels.cache.get(x => x.name === args[0]);
- if (!temp) channel = message.channel;
+ const temp = message.guild.channels.cache.get(x => x.name === args[0])
+ if (!temp) channel = message.channel
else {
- channel = message.guild.channels.cache.get(x => x.name === args[0]);
+ channel = message.guild.channels.cache.get(x => x.name === args[0])
}
}
const embed = new MessageEmbed()
.setColor(0x00ae86)
.addField(
- "❯ Name",
- channel.type === "dm" ? `@${channel.recipient.username}` : channel.name,
+ '❯ Name',
+ channel.type === 'dm' ? `@${channel.recipient.username}` : channel.name,
true
)
- .addField("❯ ID", channel.id, true)
- .addField("❯ NSFW", channel.nsfw ? "Yes" : "No", true)
+ .addField('❯ ID', channel.id, true)
+ .addField('❯ NSFW', channel.nsfw ? 'Yes' : 'No', true)
.addField(
- "❯ Category",
- channel.parent ? channel.parent.name : "None",
+ '❯ Category',
+ channel.parent ? channel.parent.name : 'None',
true
)
- .addField("❯ Type", types[channel.type], true)
+ .addField('❯ Type', types[channel.type], true)
.addField(
- "❯ Creation Date",
- moment.utc(channel.createdAt).format("MM/DD/YYYY h:mm A"),
+ '❯ Creation Date',
+ moment.utc(channel.createdAt).format('MM/DD/YYYY h:mm A'),
true
)
- .addField("❯ Topic", channel.topic || "None");
- return message.channel.send(embed);
+ .addField('❯ Topic', channel.topic || 'None')
+ return message.channel.send(embed)
}
-};
+}
diff --git a/commands/info/commands.js b/commands/info/commands.js
index 74f450f..a11c6d1 100644
--- a/commands/info/commands.js
+++ b/commands/info/commands.js
@@ -1,16 +1,16 @@
-const Discord = require("discord.js");
-const conf = require("../../config/config.json");
-const Pagination = require("discord-paginationembed");
-const { MessageEmbed } = require("discord.js");
+const Discord = require('discord.js')
+const conf = require('../../config/config.json')
+const Pagination = require('discord-paginationembed')
+const { MessageEmbed } = require('discord.js')
module.exports = {
config: {
- name: "commands",
- usage: "commands",
- description: "Show available commands",
+ name: 'commands',
+ usage: 'commands',
+ description: 'Show available commands',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
// let embed = new Discord.MessageEmbed()
// .setColor("#0390fc")
// .setTitle("Commands that i can execute")
@@ -24,40 +24,40 @@ module.exports = {
// embed.addField(command.config.name, value);
// });
// message.channel.send(embed);
- let embeds = [];
+ const embeds = []
client.commands.forEach(command => {
- let status = command.config.enabled ? "✅" : "❌";
- let value = `${conf.prefix}${command.config.usage}` + " " + `${status}`;
- let data = {
+ const status = command.config.enabled ? '✅' : '❌'
+ const value = `${conf.prefix}${command.config.usage}` + ' ' + `${status}`
+ const data = {
name: command.config.name,
usage: command.config.usage,
status: status
- };
- embeds.push(data);
- });
- embeds.sort(function(a, b) {
- var textA = a.name;
- var textB = b.name;
- return textA < textB ? -1 : textA > textB ? 1 : 0;
- });
+ }
+ embeds.push(data)
+ })
+ embeds.sort(function (a, b) {
+ var textA = a.name
+ var textB = b.name
+ return textA < textB ? -1 : textA > textB ? 1 : 0
+ })
const commands = new Pagination.FieldsEmbed()
.setArray(embeds)
.setAuthorizedUsers([])
.setChannel(message.channel)
.setPageIndicator(true)
- .formatField("Name", i => i.name + "\n")
- .formatField("Usage", i => i.usage + "\n")
- .formatField("Status", i => i.status + "\n")
+ .formatField('Name', i => i.name + '\n')
+ .formatField('Usage', i => i.usage + '\n')
+ .formatField('Status', i => i.status + '\n')
.setDeleteOnTimeout(true)
.setElementsPerPage(10)
.setEmojisFunctionAfterNavigation(true)
- commands.embed
+ commands.embed
.setThumbnail(
- client.user.avatarURL({ format: "png", dynamic: true, size: 1024 })
+ client.user.avatarURL({ format: 'png', dynamic: true, size: 1024 })
)
- .setColor("#0390fc")
- .setFooter("Created by wrose");
- await commands.build();
+ .setColor('#0390fc')
+ .setFooter('Created by wrose')
+ await commands.build()
}
-};
+}
diff --git a/commands/info/corona.js b/commands/info/corona.js
index 61a9336..391bc78 100644
--- a/commands/info/corona.js
+++ b/commands/info/corona.js
@@ -1,72 +1,72 @@
-let util = require("../../utils/utility");
-let config = require("../../config/config.json");
-let request = require("request");
+const util = require('../../utils/utility')
+const config = require('../../config/config.json')
+const request = require('request')
module.exports = {
config: {
- name: "corona",
- usage: "corona || [--track] || [--stop]",
- description: "Enable auto update COVID-19 status",
+ name: 'corona',
+ usage: 'corona || [--track] || [--stop]',
+ description: 'Enable auto update COVID-19 status',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- if (message.content.includes("--stop")) {
- clearInterval(coronaInterval);
+ async run (client, message, args) {
+ if (message.content.includes('--stop')) {
+ clearInterval(coronaInterval)
}
- if (message.content.includes("--track")) {
- coronaInterval = setInterval(async function() {
- await util.updateCorona(message);
- }, 3600000);
+ if (message.content.includes('--track')) {
+ coronaInterval = setInterval(async function () {
+ await util.updateCorona(message)
+ }, 3600000)
} else {
- request("https://coronavirus-tracker-api.herokuapp.com/all", function(
+ request('https://coronavirus-tracker-api.herokuapp.com/all', function (
error,
response,
body
) {
- let data = JSON.parse(body);
+ const data = JSON.parse(body)
message.channel.send({
embed: {
color: 14177041,
- title: "Corona(COVID-19) global update",
+ title: 'Corona(COVID-19) global update',
fields: [
{
- name: "Cases",
+ name: 'Cases',
value: data.latest.confirmed
},
{
- name: "Deaths confirmed",
+ name: 'Deaths confirmed',
value: data.latest.deaths
},
{
- name: "Recoverd",
+ name: 'Recoverd',
value: data.latest.recovered
}
]
}
- });
+ })
message.channel.send({
embed: {
color: 14177041,
- title: "Corona(COVID-19) updates",
+ title: 'Corona(COVID-19) updates',
fields: [
{
- name: "Infected",
+ name: 'Infected',
value: data.latest.confirmed
},
{
- name: "Deaths confirmed",
+ name: 'Deaths confirmed',
value: data.latest.deaths
},
{
- name: "Recoverd",
+ name: 'Recoverd',
value: data.latest.recovered
}
]
}
- });
- });
+ })
+ })
}
}
-};
+}
diff --git a/commands/info/firstMessage.js b/commands/info/firstMessage.js
index 12de67d..1a18710 100644
--- a/commands/info/firstMessage.js
+++ b/commands/info/firstMessage.js
@@ -1,37 +1,37 @@
-const { MessageEmbed } = require("discord.js");
+const { MessageEmbed } = require('discord.js')
module.exports = {
config: {
- name: "firstMessage",
- usage: "firstMessage",
+ name: 'firstMessage',
+ usage: 'firstMessage',
aliases: [],
- description: "Show the first ever message sent to the channel",
+ description: 'Show the first ever message sent to the channel',
ownerOnly: false,
enabled: true
},
- async run(client, msg, args) {
+ async run (client, msg, args) {
if (
- msg.channel.type === "text" &&
- !msg.channel.permissionsFor(client.user).has("READ_MESSAGE_HISTORY")
+ msg.channel.type === 'text' &&
+ !msg.channel.permissionsFor(client.user).has('READ_MESSAGE_HISTORY')
) {
return msg.reply(
`Sorry, I don't have permission to read ${msg.channel}...`
- );
+ )
}
- const messages = await msg.channel.messages.fetch({ after: 1, limit: 1 });
- const message = messages.first();
+ const messages = await msg.channel.messages.fetch({ after: 1, limit: 1 })
+ const message = messages.first()
const embed = new MessageEmbed()
.setColor(message.member ? message.member.displayHexColor : 0x00ae86)
.setThumbnail(
- message.author.displayAvatarURL({ format: "png", dynamic: true })
+ message.author.displayAvatarURL({ format: 'png', dynamic: true })
)
.setAuthor(
message.author.tag,
- message.author.displayAvatarURL({ format: "png", dynamic: true })
+ message.author.displayAvatarURL({ format: 'png', dynamic: true })
)
.setDescription(message.content)
.setTimestamp(message.createdAt)
.setFooter(`ID: ${message.id}`)
- .addField("❯ Jump", message.url);
- return msg.channel.send(embed);
+ .addField('❯ Jump', message.url)
+ return msg.channel.send(embed)
}
-};
+}
diff --git a/commands/info/help.js b/commands/info/help.js
index 65598c0..e5326e7 100644
--- a/commands/info/help.js
+++ b/commands/info/help.js
@@ -1,76 +1,76 @@
-let conf = require("../../config/config.json");
+const conf = require('../../config/config.json')
module.exports = {
config: {
- name: "help",
- usage: "help [command name]",
- aliases: ["h", "help"],
+ name: 'help',
+ usage: 'help [command name]',
+ aliases: ['h', 'help'],
description:
- "Show helps for commands, use ```.commands``` for the list of commands",
+ 'Show helps for commands, use ```.commands``` for the list of commands',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
try {
if (!args[0]) {
message.channel.send({
embed: {
color: 3447003,
- title: "This is the property of wrose",
+ title: 'This is the property of wrose',
description: "Honestly it's a bot made by wrose",
fields: [
{
- name: "Prefix",
+ name: 'Prefix',
value:
- client.guildSettings.get(message.guild.id).prefix || "\u200b",
+ client.guildSettings.get(message.guild.id).prefix || '\u200b'
},
{
- name: "Running in ",
- value: client.guilds.cache.size + " servers" || "\u200b",
- },
+ name: 'Running in ',
+ value: client.guilds.cache.size + ' servers' || '\u200b'
+ }
],
thumbnail: {
url: client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
+ size: 1024
+ })
+ }
+ }
+ })
}
if (args[0]) {
- let usage =
+ const usage =
`${client.guildSettings.get(message.guild.id).prefix}` +
- client.commands.get(args[0]).config.usage;
+ client.commands.get(args[0]).config.usage
message.channel.send({
embed: {
color: 3447003,
fields: [
{
- name: "Name",
- value: client.commands.get(args[0]).config.name,
+ name: 'Name',
+ value: client.commands.get(args[0]).config.name
},
{
- name: "Usage",
- value: usage,
+ name: 'Usage',
+ value: usage
},
{
- name: "Description",
- value: client.commands.get(args[0]).config.description,
- },
+ name: 'Description',
+ value: client.commands.get(args[0]).config.description
+ }
],
thumbnail: {
url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
+ size: 1024
+ })
+ }
+ }
+ })
}
} catch (error) {
- console.log(error);
+ console.log(error)
}
- },
-};
+ }
+}
diff --git a/commands/info/league.js b/commands/info/league.js
index b2e2336..62b1fe7 100644
--- a/commands/info/league.js
+++ b/commands/info/league.js
@@ -1,148 +1,148 @@
-const { MessageEmbed } = require("discord.js");
-const request = require("node-superfetch");
-const buttons = ["Q", "W", "E", "R"];
+const { MessageEmbed } = require('discord.js')
+const request = require('node-superfetch')
+const buttons = ['Q', 'W', 'E', 'R']
module.exports = {
config: {
- name: "league",
- usage: "league",
+ name: 'league',
+ usage: 'league',
aliases: [],
- description: "Send information about a League of Legends champion",
+ description: 'Send information about a League of Legends champion',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let version = null;
- message.channel.send("Champion ?");
- let collected = await message.channel.awaitMessages(
+ async run (client, message, args) {
+ let version = null
+ message.channel.send('Champion ?')
+ const collected = await message.channel.awaitMessages(
(m) => m.author.id === message.author.id,
{
max: 1,
- time: 30000,
+ time: 30000
}
- );
- let champions;
- let champion = collected.first().content;
- if (champion === "satan") champion = "teemo";
+ )
+ let champions
+ let champion = collected.first().content
+ if (champion === 'satan') champion = 'teemo'
try {
- if (!version) await fetchVersion();
- const data = await fetchChampion(champion.toLowerCase());
- if (!data) return message.channel.send("Could not find any results.");
- const tips = [].concat(data.allytips, data.enemytips);
+ if (!version) await fetchVersion()
+ const data = await fetchChampion(champion.toLowerCase())
+ if (!data) return message.channel.send('Could not find any results.')
+ const tips = [].concat(data.allytips, data.enemytips)
const embed = new MessageEmbed()
.setColor(0x002366)
.setAuthor(
- "League of Legends",
- "https://i.imgur.com/2JL4Rko.png",
- "https://leagueoflegends.com/"
+ 'League of Legends',
+ 'https://i.imgur.com/2JL4Rko.png',
+ 'https://leagueoflegends.com/'
)
.setTitle(`${data.name} ${data.title}`)
.setDescription(data.blurb)
.setThumbnail(
`https://ddragon.leagueoflegends.com/cdn/${version}/img/champion/${data.image.full}`
)
- .addField("❯ Attack", data.info.attack, true)
- .addField("❯ Defense", data.info.defense, true)
- .addField("❯ Magic", data.info.magic, true)
- .addField("❯ Difficulty", data.info.difficulty, true)
+ .addField('❯ Attack', data.info.attack, true)
+ .addField('❯ Defense', data.info.defense, true)
+ .addField('❯ Magic', data.info.magic, true)
+ .addField('❯ Difficulty', data.info.difficulty, true)
.addField(
- "❯ HP",
+ '❯ HP',
`${data.stats.hp} (${data.stats.hpperlevel}/level)`,
true
)
.addField(
- "❯ HP Regen",
+ '❯ HP Regen',
`${data.stats.hpregen} (${data.stats.hpregenperlevel}/level)`,
true
)
.addField(
- "❯ MP",
+ '❯ MP',
`${data.stats.mp} (${data.stats.mpperlevel}/level)`,
true
)
.addField(
- "❯ MP Regen",
+ '❯ MP Regen',
`${data.stats.mpregen} (${data.stats.mpregenperlevel}/level)`,
true
)
- .addField("❯ Resource", data.partype, true)
+ .addField('❯ Resource', data.partype, true)
.addField(
- "❯ Armor",
+ '❯ Armor',
`${data.stats.armor} (${data.stats.armorperlevel}/level)`,
true
)
.addField(
- "❯ Attack Damage",
+ '❯ Attack Damage',
`${data.stats.attackdamage} (${data.stats.attackdamageperlevel}/level)`,
true
)
- .addField("❯ Attack Range", data.stats.attackrange, true)
+ .addField('❯ Attack Range', data.stats.attackrange, true)
.addField(
- "❯ Attack Speed Offset",
+ '❯ Attack Speed Offset',
`${data.stats.attackspeedoffset} (${data.stats.attackspeedperlevel}/level)`,
true
)
.addField(
- "❯ Crit",
+ '❯ Crit',
`${data.stats.crit} (${data.stats.critperlevel}/level)`,
true
)
- .addField("❯ Move Speed", data.stats.movespeed, true)
+ .addField('❯ Move Speed', data.stats.movespeed, true)
.addField(
- "❯ Spell Block",
+ '❯ Spell Block',
`${data.stats.spellblock} (${data.stats.spellblockperlevel}/level)`,
true
)
- .addField("❯ Passive", data.passive.name, true)
+ .addField('❯ Passive', data.passive.name, true)
.addField(
- "❯ Spells",
+ '❯ Spells',
data.spells
.map((spell, i) => `${spell.name} (${buttons[i]})`)
- .join("\n"),
+ .join('\n'),
true
- );
+ )
return message.channel.send(
`Tip: ${tips[Math.floor(Math.random() * tips.length)]}`,
{
- embed,
+ embed
}
- );
+ )
} catch (err) {
return message.reply(
`Oh no, an error occurred: \`${err.message}\`. Try again later!`
- );
+ )
}
- async function fetchVersion() {
+ async function fetchVersion () {
const { body } = await request.get(
- "https://ddragon.leagueoflegends.com/api/versions.json"
+ 'https://ddragon.leagueoflegends.com/api/versions.json'
);
- [version] = body;
+ [version] = body
setTimeout(() => {
- version = null;
- }, 3.6e6);
- return body;
+ version = null
+ }, 3.6e6)
+ return body
}
- async function fetchChampions() {
- if (champions && champions.version === version) return champions;
+ async function fetchChampions () {
+ if (champions && champions.version === version) return champions
const { body } = await request.get(
`https://ddragon.leagueoflegends.com/cdn/${version}/data/en_US/champion.json`
- );
- champions = body;
- return body;
+ )
+ champions = body
+ return body
}
- async function fetchChampion(champion) {
- const champions = await fetchChampions();
+ async function fetchChampion (champion) {
+ const champions = await fetchChampions()
const name = Object.keys(champions.data).find(
(key) => key.toLowerCase() === champion
- );
- if (!name) return null;
- const { id } = champions.data[name];
+ )
+ if (!name) return null
+ const { id } = champions.data[name]
const { body } = await request.get(
`https://ddragon.leagueoflegends.com/cdn/${version}/data/vn_VN/champion/${id}.json`
- );
- return body.data[id];
+ )
+ return body.data[id]
}
- },
-};
+ }
+}
diff --git a/commands/info/monitor.js b/commands/info/monitor.js
index 8654d81..bc93e68 100644
--- a/commands/info/monitor.js
+++ b/commands/info/monitor.js
@@ -1,116 +1,109 @@
-const { Canvas } = require('canvas-constructor');
-const { get } = require('node-superfetch');
-const Discord = require('discord.js');
+const { Canvas } = require('canvas-constructor')
+const { get } = require('node-superfetch')
+const Discord = require('discord.js')
module.exports = {
config: {
- name: "",
- usage: "",
+ name: '',
+ usage: '',
aliases: [],
- description: "",
+ description: '',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let curOnline = message.guild.members.cache.filter(m=> m.presence.status == 'online').size;
- let curOffline = message.guild.members.cache.filter(m=> m.presence.status == 'offline').size;
- let curDnd = message.guild.members.cache.filter(m=> m.presence.status == 'dnd').size;
- let curIdle = message.guild.members.cache.filter(m=> m.presence.status == 'idle').size;
- let guildMembers = message.guild.memberCount;
- if(curOnline == 0) {
- var differenceOnline = 10;
+ async run (client, message, args) {
+ const curOnline = message.guild.members.cache.filter(m => m.presence.status == 'online').size
+ const curOffline = message.guild.members.cache.filter(m => m.presence.status == 'offline').size
+ const curDnd = message.guild.members.cache.filter(m => m.presence.status == 'dnd').size
+ const curIdle = message.guild.members.cache.filter(m => m.presence.status == 'idle').size
+ const guildMembers = message.guild.memberCount
+ if (curOnline == 0) {
+ var differenceOnline = 10
} else {
- var differenceOnline = curOnline/guildMembers *240;
+ var differenceOnline = curOnline / guildMembers * 240
}
- if(curOffline == 0) {
- var differenceOffline = 10;
+ if (curOffline == 0) {
+ var differenceOffline = 10
} else {
- var differenceOffline = curOffline/guildMembers *240;
+ var differenceOffline = curOffline / guildMembers * 240
}
- if(curDnd == 0) {
- var differenceDnd = 10;
+ if (curDnd == 0) {
+ var differenceDnd = 10
} else {
- var differenceDnd = curDnd/guildMembers *240;
+ var differenceDnd = curDnd / guildMembers * 240
}
- if(curIdle == 0) {
- var differenceIdle = 10;
+ if (curIdle == 0) {
+ var differenceIdle = 10
} else {
- var differenceIdle = curIdle/guildMembers *240;
+ var differenceIdle = curIdle / guildMembers * 240
}
- var backGroundArray = await new Array('https://cdn.probot.io/profile/ScumID-1.jpg','https://cdn.probot.io/profile/ScumID-2.jpg','https://cdn.probot.io/profile/17.png','https://cdn.probot.io/profile/boy1.jpg',
- 'https://cdn.probot.io/profile/bg-8.png','https://cdn.probot.io/profile/breakingbad.jpg','https://cdn.probot.io/profile/03404.png','https://cdn.probot.io/profile/123123123.png','https://cdn.probot.io/profile/sdffdssdf.png',
- 'https://cdn.probot.io/profile/walking_dead2.png','https://cdn.probot.io/profile/got2.png','https://cdn.probot.io/profile/ragnar.jpg')
- var mathBackGround = await backGroundArray[Math.floor(Math.random() * backGroundArray.length)]
- if(message.guild.iconURL() == null) {
-
- var {body: guildIcon} = await get("https://www.net-aware.org.uk/siteassets/images-and-icons/application-icons/app-icons-discord.png?w=585&scale=down")
-
- } else if(message.guild.iconURL() !== null){
-
- var {body: guildIcon} = await get(message.guild.iconURL({ format: 'png', dynamic: false, size: 128}))
-
- }
- var {body: backGround} = await get(mathBackGround)
-
- const buffer = await new Canvas(540, 250)
- .setGlobalAlpha(0.5)
- .setColor('#33cc99')
- .addBeveledRect(490, 47, 50, 30)
- .setColor('#A9A9A9')
- .addBeveledRect(490, 90, 50, 30)
- .setColor('#ff3333')
- .addBeveledRect(490, 133, 50, 30)
- .setColor('#ff9933')
- .addBeveledRect(490, 176, 50, 30)
- .setGlobalAlpha(1)
- .setTextAlign('center')
- .setTextFont('bold 15px Impact')
- .setColor('#000000')
- .addText(curOnline, 519, 68)
- .addText(curOffline, 519, 111)
- .addText(curDnd, 519, 154)
- .addText(curIdle, 519, 197)
- .addBeveledImage(backGround, 0, 0, 500, 250)
- .setColor('BLACK')
- .addBeveledRect(495, -2, 5, 255, 15)
- .setColor('#303030')
- .setGlobalAlpha(0.5)
- .addBeveledRect(20, 20, 460, 210, 15)
- .fill().restore()
- .setColor("white")
- .setGlobalAlpha(0.2)
- .addBeveledRect(225,47,240, 30)
- .addBeveledRect(225,90,240, 30)
- .addBeveledRect(225,133,240, 30)
- .addBeveledRect(225,176,240, 30)
- .setGlobalAlpha(1)
- .setColor('#33cc99')
- .addBeveledRect(225,47,differenceOnline, 30)
- .setColor('#A9A9A9')
- .addBeveledRect(225,90,differenceOffline, 30)
- .setColor('#ff3333')
- .addBeveledRect(225,133,differenceDnd, 30)
- .setColor('#ff9933')
- .addBeveledRect(225,176,differenceIdle, 30)
- .setColor('#FFFFFF')
- .addBeveledRect(40, 40, 170, 170, 40)
- .fill().restore()
- .addBeveledImage(guildIcon, 40, 40, 170, 170, 16)
- .save()
- .toBuffer()
-
- try {
+ var backGroundArray = await new Array('https://cdn.probot.io/profile/ScumID-1.jpg', 'https://cdn.probot.io/profile/ScumID-2.jpg', 'https://cdn.probot.io/profile/17.png', 'https://cdn.probot.io/profile/boy1.jpg',
+ 'https://cdn.probot.io/profile/bg-8.png', 'https://cdn.probot.io/profile/breakingbad.jpg', 'https://cdn.probot.io/profile/03404.png', 'https://cdn.probot.io/profile/123123123.png', 'https://cdn.probot.io/profile/sdffdssdf.png',
+ 'https://cdn.probot.io/profile/walking_dead2.png', 'https://cdn.probot.io/profile/got2.png', 'https://cdn.probot.io/profile/ragnar.jpg')
+ var mathBackGround = await backGroundArray[Math.floor(Math.random() * backGroundArray.length)]
+ if (message.guild.iconURL() == null) {
+ var { body: guildIcon } = await get('https://www.net-aware.org.uk/siteassets/images-and-icons/application-icons/app-icons-discord.png?w=585&scale=down')
+ } else if (message.guild.iconURL() !== null) {
+ var { body: guildIcon } = await get(message.guild.iconURL({ format: 'png', dynamic: false, size: 128 }))
+ }
+ var { body: backGround } = await get(mathBackGround)
- const filename = `${message.guild.name}-members.jpg`;
- const attachment = new Discord.MessageAttachment(buffer, filename);
- await message.channel.send(attachment);
+ const buffer = await new Canvas(540, 250)
+ .setGlobalAlpha(0.5)
+ .setColor('#33cc99')
+ .addBeveledRect(490, 47, 50, 30)
+ .setColor('#A9A9A9')
+ .addBeveledRect(490, 90, 50, 30)
+ .setColor('#ff3333')
+ .addBeveledRect(490, 133, 50, 30)
+ .setColor('#ff9933')
+ .addBeveledRect(490, 176, 50, 30)
+ .setGlobalAlpha(1)
+ .setTextAlign('center')
+ .setTextFont('bold 15px Impact')
+ .setColor('#000000')
+ .addText(curOnline, 519, 68)
+ .addText(curOffline, 519, 111)
+ .addText(curDnd, 519, 154)
+ .addText(curIdle, 519, 197)
+ .addBeveledImage(backGround, 0, 0, 500, 250)
+ .setColor('BLACK')
+ .addBeveledRect(495, -2, 5, 255, 15)
+ .setColor('#303030')
+ .setGlobalAlpha(0.5)
+ .addBeveledRect(20, 20, 460, 210, 15)
+ .fill().restore()
+ .setColor('white')
+ .setGlobalAlpha(0.2)
+ .addBeveledRect(225, 47, 240, 30)
+ .addBeveledRect(225, 90, 240, 30)
+ .addBeveledRect(225, 133, 240, 30)
+ .addBeveledRect(225, 176, 240, 30)
+ .setGlobalAlpha(1)
+ .setColor('#33cc99')
+ .addBeveledRect(225, 47, differenceOnline, 30)
+ .setColor('#A9A9A9')
+ .addBeveledRect(225, 90, differenceOffline, 30)
+ .setColor('#ff3333')
+ .addBeveledRect(225, 133, differenceDnd, 30)
+ .setColor('#ff9933')
+ .addBeveledRect(225, 176, differenceIdle, 30)
+ .setColor('#FFFFFF')
+ .addBeveledRect(40, 40, 170, 170, 40)
+ .fill().restore()
+ .addBeveledImage(guildIcon, 40, 40, 170, 170, 16)
+ .save()
+ .toBuffer()
-} catch (error) {
- return message.channel.send(`An error ocurred: **${error.message}**`);
-}
-
+ try {
+ const filename = `${message.guild.name}-members.jpg`
+ const attachment = new Discord.MessageAttachment(buffer, filename)
+ await message.channel.send(attachment)
+ } catch (error) {
+ return message.channel.send(`An error ocurred: **${error.message}**`)
+ }
}
-};
+}
diff --git a/commands/info/server.js b/commands/info/server.js
index 03d81f3..6f3a851 100644
--- a/commands/info/server.js
+++ b/commands/info/server.js
@@ -1,29 +1,28 @@
-const moment = require("moment");
-const { MessageEmbed } = require("discord.js");
-const { stripIndents } = require("common-tags");
-const filterLevels = ["Off", "No Role", "Everyone"];
+const moment = require('moment')
+const { MessageEmbed } = require('discord.js')
+const { stripIndents } = require('common-tags')
+const filterLevels = ['Off', 'No Role', 'Everyone']
const verificationLevels = [
- "None",
- "Low",
- "Medium",
- "(╯°□°)╯︵ ┻━┻",
- "┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻"
-];
+ 'None',
+ 'Low',
+ 'Medium',
+ '(╯°□°)╯︵ ┻━┻',
+ '┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻'
+]
module.exports = {
config: {
- name: "server",
- usage: "server",
+ name: 'server',
+ usage: 'server',
aliases: [],
- description: "Show description for current Discord server",
+ description: 'Show description for current Discord server',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- if (!message.guild.members.cache.has(message.guild.ownerID))
- await message.guild.members.fetch(message.guild.ownerID);
+ async run (client, message, args) {
+ if (!message.guild.members.cache.has(message.guild.ownerID)) { await message.guild.members.fetch(message.guild.ownerID) }
const embed = new MessageEmbed()
.setColor(0x00ae86)
- .setThumbnail(message.guild.iconURL({ format: "png" }))
+ .setThumbnail(message.guild.iconURL({ format: 'png' }))
.setAuthor(message.guild.name).setDescription(stripIndents`
**General Info:**
• ID: ${message.guild.id}
@@ -31,7 +30,7 @@ module.exports = {
• Region: ${message.guild.region.toUpperCase()}
• Creation Date: ${moment
.utc(message.guild.createdAt)
- .format("MM/DD/YYYY h:mm A")}
+ .format('MM/DD/YYYY h:mm A')}
• Explicit Filter: ${
filterLevels[message.guild.explicitContentFilter]
}
@@ -43,10 +42,10 @@ module.exports = {
• Roles: ${message.guild.roles.cache.size}
• Channels: ${
message.guild.channels.cache.filter(
- channel => channel.type !== "category"
+ channel => channel.type !== 'category'
).size
}
- `);
- return message.channel.send(embed);
+ `)
+ return message.channel.send(embed)
}
-};
+}
diff --git a/commands/info/stats.js b/commands/info/stats.js
index 15bc3f0..7e79e6a 100644
--- a/commands/info/stats.js
+++ b/commands/info/stats.js
@@ -1,57 +1,57 @@
-const { MessageEmbed } = require("discord.js");
-const { stripIndents } = require("common-tags");
-const moment = require("moment");
-const osu = require("node-os-utils");
-const os = require("os");
-require("moment-duration-format");
-let { Colors } = require("../../utils/canvas");
+const { MessageEmbed } = require('discord.js')
+const { stripIndents } = require('common-tags')
+const moment = require('moment')
+const osu = require('node-os-utils')
+const os = require('os')
+require('moment-duration-format')
+const { Colors } = require('../../utils/canvas')
module.exports = {
config: {
- name: "stats",
- usage: "stats",
+ name: 'stats',
+ usage: 'stats',
aliases: [],
- description: "Show bot statistics",
+ description: 'Show bot statistics',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let freeRAM = os.freemem();
- let usedRAM = os.totalmem() - freeRAM;
- let full = "▰";
- let empty = "▱";
- let diagramMaker = (used, free) => {
- let total = used + free;
- used = Math.round((used / total) * 10);
- free = Math.round((free / total) * 10);
- return full.repeat(used) + empty.repeat(free);
- };
+ async run (client, message, args) {
+ const freeRAM = os.freemem()
+ const usedRAM = os.totalmem() - freeRAM
+ const full = '▰'
+ const empty = '▱'
+ const diagramMaker = (used, free) => {
+ const total = used + free
+ used = Math.round((used / total) * 10)
+ free = Math.round((free / total) * 10)
+ return full.repeat(used) + empty.repeat(free)
+ }
- let cpuUsage;
+ let cpuUsage
const p1 = osu.cpu.usage().then((cpuPercentage) => {
- cpuUsage = cpuPercentage;
- });
+ cpuUsage = cpuPercentage
+ })
- await Promise.all([p1]);
+ await Promise.all([p1])
- const roleColor = message.guild.me.roles.highest.hexColor;
+ const roleColor = message.guild.me.roles.highest.hexColor
const statsEmbed = new MessageEmbed()
- .setColor(roleColor === "#000000" ? Colors.CUSTOM : roleColor)
+ .setColor(roleColor === '#000000' ? Colors.CUSTOM : roleColor)
.setAuthor(
`${client.user.username}'s statistics information`,
client.user.avatarURL({ dynamic: true })
)
- .setDescription("Here are some stats about the bot and other stuff")
+ .setDescription('Here are some stats about the bot and other stuff')
.setThumbnail(
client.user.displayAvatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 4096,
+ size: 4096
})
)
.addField(
- "__**Performance**__",
+ '__**Performance**__',
stripIndents`
RAM: ${diagramMaker(usedRAM, freeRAM)} [${Math.round(
(100 * usedRAM) / (usedRAM + freeRAM)
@@ -62,7 +62,7 @@ module.exports = {
false
)
.addField(
- "__**System**__",
+ '__**System**__',
stripIndents`
Processor: ${os.cpus()[0].model} (${osu.cpu.count()} Cores)
Total RAM: ${(usedRAM / 1024 / 1024 / 1024).toFixed(2)} GB / ${(
@@ -74,33 +74,33 @@ module.exports = {
false
)
.addField(
- "__**Operation System**__",
+ '__**Operation System**__',
`${os.type} ${os.release} ${os.arch}`,
false
)
- .addField("__**Total Users**__", client.users.cache.size, true)
- .addField("__**Total Emotes**__", client.emojis.cache.size, true)
- .addField("__**Total Guilds**__", client.guilds.cache.size, true)
+ .addField('__**Total Users**__', client.users.cache.size, true)
+ .addField('__**Total Emotes**__', client.emojis.cache.size, true)
+ .addField('__**Total Guilds**__', client.guilds.cache.size, true)
.addField(
- "__**Bot Uptime**__",
+ '__**Bot Uptime**__',
moment
.duration(client.uptime)
- .format("D [days], H [hrs], m [mins], s [secs]"),
+ .format('D [days], H [hrs], m [mins], s [secs]'),
true
)
.addField(
- "__**Host Uptime**__",
+ '__**Host Uptime**__',
moment
.duration(os.uptime * 1000)
- .format("D [days], H [hrs], m [mins], s [secs]"),
+ .format('D [days], H [hrs], m [mins], s [secs]'),
true
)
.setFooter(
`Created by wrose | Last started on ${moment(client.readyAt).format(
- "ddd, DD MMMM YYYY HH:mm [GMT]Z"
+ 'ddd, DD MMMM YYYY HH:mm [GMT]Z'
)}`
- );
+ )
- message.channel.send(statsEmbed);
- },
-};
+ message.channel.send(statsEmbed)
+ }
+}
diff --git a/commands/info/topSongs.js b/commands/info/topSongs.js
index f323e94..6a421d1 100644
--- a/commands/info/topSongs.js
+++ b/commands/info/topSongs.js
@@ -1,74 +1,74 @@
-const music = require("../../model/musicData");
-const Discord = require("discord.js");
-const Pagination = require("discord-paginationembed");
+const music = require('../../model/musicData')
+const Discord = require('discord.js')
+const Pagination = require('discord-paginationembed')
module.exports = {
config: {
- name: "topSongs",
- usage: "topSongs",
- description: "Show top songs played. Use --server to show guild stats",
+ name: 'topSongs',
+ usage: 'topSongs',
+ description: 'Show top songs played. Use --server to show guild stats',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
// let global = await music.getSongs();
// let
- let songs = args.includes("--server")
+ const songs = args.includes('--server')
? await music.guildTop(message.guild.id)
- : await music.getSongs();
+ : await music.getSongs()
if (songs) {
- let embed = new Discord.MessageEmbed()
- .setColor("#0390fc")
- .setTitle("Top requested song my storage")
+ const embed = new Discord.MessageEmbed()
+ .setColor('#0390fc')
+ .setTitle('Top requested song my storage')
.setThumbnail(
- client.user.avatarURL({ format: "png", dynamic: true, size: 1024 })
- );
+ client.user.avatarURL({ format: 'png', dynamic: true, size: 1024 })
+ )
songs.forEach((entry) => {
- embed.addField(entry.name, entry.count);
- });
- message.channel.send(embed);
+ embed.addField(entry.name, entry.count)
+ })
+ message.channel.send(embed)
// sendPage(songs)
}
if (!songs) {
message.channel.send({
embed: {
color: 15158332,
- title: "My storage is empty",
+ title: 'My storage is empty',
thumbnail: {
url: client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
+ size: 1024
+ })
+ }
+ }
+ })
}
- async function sendPage(songs) {
- let embeds = [];
+ async function sendPage (songs) {
+ const embeds = []
songs.forEach((entry) => {
- let data = {
+ const data = {
name: entry.name,
- count: entry.count,
- };
- embeds.push(data);
- });
- let msg = new Pagination.FieldsEmbed()
+ count: entry.count
+ }
+ embeds.push(data)
+ })
+ const msg = new Pagination.FieldsEmbed()
.setArray(embeds)
.setAuthorizedUsers([])
.setChannel(message.channel)
.setPageIndicator(true)
- .formatField(`Name`, (i) => i.name)
- .formatField("Count", (i) => i.count, true)
+ .formatField('Name', (i) => i.name)
+ .formatField('Count', (i) => i.count, true)
.setElementsPerPage(5)
.setDeleteOnTimeout(true)
- .setEmojisFunctionAfterNavigation(true);
+ .setEmojisFunctionAfterNavigation(true)
msg.embed
.setThumbnail(
- client.user.avatarURL({ format: "png", dynamic: true, size: 1024 })
+ client.user.avatarURL({ format: 'png', dynamic: true, size: 1024 })
)
- .setColor("#0390fc")
- .setFooter("Created by wrose");
- await msg.build();
+ .setColor('#0390fc')
+ .setFooter('Created by wrose')
+ await msg.build()
}
- },
-};
+ }
+}
diff --git a/commands/info/userInfo.js b/commands/info/userInfo.js
index 6ed5486..c8c6b4f 100644
--- a/commands/info/userInfo.js
+++ b/commands/info/userInfo.js
@@ -1,65 +1,65 @@
-const moment = require("moment");
-const { MessageEmbed } = require("discord.js");
-const { stripIndents } = require("common-tags");
-const { trimArray } = require("../../utils/utility");
+const moment = require('moment')
+const { MessageEmbed } = require('discord.js')
+const { stripIndents } = require('common-tags')
+const { trimArray } = require('../../utils/utility')
module.exports = {
config: {
- name: "userInfo",
- usage: "userInfo",
+ name: 'userInfo',
+ usage: 'userInfo',
aliases: [],
- description: "Send message author information",
+ description: 'Send message author information',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let user;
- if (!message.mentions.users.first()) user = message.author;
- else user = message.mentions.users.first();
+ async run (client, message, args) {
+ let user
+ if (!message.mentions.users.first()) user = message.author
+ else user = message.mentions.users.first()
const embed = new MessageEmbed()
.setAuthor(user.tag)
- .setThumbnail(user.displayAvatarURL({ format: "png", dynamic: true }));
+ .setThumbnail(user.displayAvatarURL({ format: 'png', dynamic: true }))
let description = stripIndents`
**General User Info:**
• ID: ${user.id}
• Discord Join Date: ${moment
.utc(user.createdAt)
- .format("MM/DD/YYYY h:mm A")}
- • ${user.bot ? "Bot" : "Not a Bot"}
-`;
- if (message.channel.type === "text") {
+ .format('MM/DD/YYYY h:mm A')}
+ • ${user.bot ? 'Bot' : 'Not a Bot'}
+`
+ if (message.channel.type === 'text') {
try {
- const member = await message.guild.members.fetch(user.id);
- const defaultRole = message.guild.roles.cache.get(message.guild.id);
+ const member = await message.guild.members.fetch(user.id)
+ const defaultRole = message.guild.roles.cache.get(message.guild.id)
const roles = member.roles.cache
.filter(role => role.id !== defaultRole.id)
.sort((a, b) => b.position - a.position)
- .map(role => role);
- description += "\n\n";
+ .map(role => role)
+ description += '\n\n'
description += stripIndents`
**Server Member Info:**
- • Nickname: ${member.nickname || "None"}
+ • Nickname: ${member.nickname || 'None'}
• Server Join Date: ${moment
.utc(member.joinedAt)
- .format("MM/DD/YYYY h:mm A")}
+ .format('MM/DD/YYYY h:mm A')}
• Highest Role: ${
member.roles.highest.id === defaultRole.id
- ? "None"
+ ? 'None'
: member.roles.highest.name
}
• Hoist Role: ${
- member.roles.hoist ? member.roles.hoist.name : "None"
+ member.roles.hoist ? member.roles.hoist.name : 'None'
}
**Roles (${roles.length})**
- • ${roles.length ? trimArray(roles, 6).join(", ") : "None"}
- `;
- embed.setColor(member.displayHexColor);
+ • ${roles.length ? trimArray(roles, 6).join(', ') : 'None'}
+ `
+ embed.setColor(member.displayHexColor)
} catch {
embed.setFooter(
- "Failed to resolve member, showing basic user information instead."
- );
+ 'Failed to resolve member, showing basic user information instead.'
+ )
}
}
- embed.setDescription(description);
- return message.channel.send(embed);
+ embed.setDescription(description)
+ return message.channel.send(embed)
}
-};
+}
diff --git a/commands/info/webCapture.js b/commands/info/webCapture.js
index ce92d55..d2e8854 100644
--- a/commands/info/webCapture.js
+++ b/commands/info/webCapture.js
@@ -1,43 +1,43 @@
-const request = require("request-promise-native");
-const fs = require("fs");
-const Discord = require("discord.js");
+const request = require('request-promise-native')
+const fs = require('fs')
+const Discord = require('discord.js')
module.exports = {
config: {
- name: "webCapture",
- usage: "webCapture [website]",
+ name: 'webCapture',
+ usage: 'webCapture [website]',
aliases: [],
- description: "Show capture of a given website",
+ description: 'Show capture of a given website',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
message.channel.send(
- "The process may take up to 1 minute to complete. Please wait ..."
- );
+ 'The process may take up to 1 minute to complete. Please wait ...'
+ )
request(
{
url:
- "https://api.apiflash.com/v1/urltoimage?full_page=true&scroll_page=true&quality=100&delay=10&format=png",
- encoding: "binary",
+ 'https://api.apiflash.com/v1/urltoimage?full_page=true&scroll_page=true&quality=100&delay=10&format=png',
+ encoding: 'binary',
qs: {
- access_key: "2e3e6c58615e4e1b8f42dbca498aedc9",
- url: args[0],
- },
+ access_key: '2e3e6c58615e4e1b8f42dbca498aedc9',
+ url: args[0]
+ }
},
async (error, response, body) => {
if (error) {
- console.log(error);
+ console.log(error)
} else {
- fs.writeFile("screenshot.png", body, "binary", (error) => {
- console.log(error);
- });
- let attachment = new Discord.MessageAttachment("screenshot.png");
- await message.channel.send(attachment);
- await fs.unlink("screenshot.png", (error) => {
- if (error) message.channel.send(error.message);
- });
+ fs.writeFile('screenshot.png', body, 'binary', (error) => {
+ console.log(error)
+ })
+ const attachment = new Discord.MessageAttachment('screenshot.png')
+ await message.channel.send(attachment)
+ await fs.unlink('screenshot.png', (error) => {
+ if (error) message.channel.send(error.message)
+ })
}
}
- );
- },
-};
+ )
+ }
+}
diff --git a/commands/meme/beLikeBill.js b/commands/meme/beLikeBill.js
index 2421bf4..22c9e30 100644
--- a/commands/meme/beLikeBill.js
+++ b/commands/meme/beLikeBill.js
@@ -1,39 +1,39 @@
-const { createCanvas, loadImage, registerFont } = require("canvas");
-const { stripIndents } = require("common-tags");
-const path = require("path");
-const { wrapText } = require("../../utils/canvas");
-const texts = require("../../assets/json/be-like-bill");
+const { createCanvas, loadImage, registerFont } = require('canvas')
+const { stripIndents } = require('common-tags')
+const path = require('path')
+const { wrapText } = require('../../utils/canvas')
+const texts = require('../../assets/json/be-like-bill')
registerFont(
- path.join(__dirname, "..", "..", "assets", "fonts", "arialbd.ttf"),
- { family: "Arial", weight: "bold" }
-);
+ path.join(__dirname, '..', '..', 'assets', 'fonts', 'arialbd.ttf'),
+ { family: 'Arial', weight: 'bold' }
+)
module.exports = {
config: {
- name: "beLikeBill",
- usage: "beLikeBill",
+ name: 'beLikeBill',
+ usage: 'beLikeBill',
aliases: [],
- description: "Send a beLikeBill meme",
+ description: 'Send a beLikeBill meme',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- message.channel.send("Input meme name");
- let collected = await message.channel.awaitMessages(
+ async run (client, message, args) {
+ message.channel.send('Input meme name')
+ const collected = await message.channel.awaitMessages(
m => m.author.id === message.author.id,
{
max: 1,
time: 30000
}
- );
- let name = collected.first().content;
+ )
+ const name = collected.first().content
const base = await loadImage(
- path.join(__dirname, "..", "..", "assets", "be-like-bill.png")
- );
- const canvas = createCanvas(base.width, base.height);
- const ctx = canvas.getContext("2d");
- ctx.drawImage(base, 0, 0);
- ctx.font = "normal bold 23px Arial";
+ path.join(__dirname, '..', '..', 'assets', 'be-like-bill.png')
+ )
+ const canvas = createCanvas(base.width, base.height)
+ const ctx = canvas.getContext('2d')
+ ctx.drawImage(base, 0, 0)
+ ctx.font = 'normal bold 23px Arial'
const text = await wrapText(
ctx,
texts[Math.floor(Math.random() * texts.length)].replace(
@@ -41,19 +41,19 @@ module.exports = {
name
),
569
- );
+ )
ctx.fillText(
stripIndents`
This is ${name}.
- ${text.join("\n")}
+ ${text.join('\n')}
${name} is smart.
Be like ${name}.
`,
31,
80
- );
+ )
return message.channel.send({
- files: [{ attachment: canvas.toBuffer(), name: "be-like-bill.png" }]
- });
+ files: [{ attachment: canvas.toBuffer(), name: 'be-like-bill.png' }]
+ })
}
-};
+}
diff --git a/commands/meme/cursedSponge.js b/commands/meme/cursedSponge.js
index 8033ead..825c12d 100644
--- a/commands/meme/cursedSponge.js
+++ b/commands/meme/cursedSponge.js
@@ -1,45 +1,43 @@
-const { createCanvas, loadImage } = require("canvas");
-const path = require("path");
+const { createCanvas, loadImage } = require('canvas')
+const path = require('path')
module.exports = {
config: {
- name: "cursedSponge",
- usage: "cursedSponge",
+ name: 'cursedSponge',
+ usage: 'cursedSponge',
aliases: [],
- description: "cursedSponge image",
+ description: 'cursedSponge image',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
message.channel.send(
- "How many times do you want to duplicate the cursed sponge?"
- );
- let collected = await message.channel.awaitMessages(
+ 'How many times do you want to duplicate the cursed sponge?'
+ )
+ const collected = await message.channel.awaitMessages(
m => m.author.id === message.author.id,
{
max: 1,
time: 30000
}
- );
- let amount = parseInt(collected.first().content);
+ )
+ const amount = parseInt(collected.first().content)
const sponge = await loadImage(
- path.join(__dirname, "..", "..", "assets", "cursed-sponge.png")
- );
- const rows = Math.ceil(amount / 10);
+ path.join(__dirname, '..', '..', 'assets', 'cursed-sponge.png')
+ )
+ const rows = Math.ceil(amount / 10)
const canvas = createCanvas(
sponge.width * (rows > 1 ? 10 : amount),
sponge.height * rows
- );
- const ctx = canvas.getContext("2d");
- let width = 0;
+ )
+ const ctx = canvas.getContext('2d')
+ let width = 0
for (let i = 0; i < amount; i++) {
- const row = Math.ceil((i + 1) / 10);
- ctx.drawImage(sponge, width, sponge.height * (row - 1));
- if (width + sponge.width === sponge.width * (rows > 1 ? 10 : amount))
- width = 0;
- else width += sponge.width;
+ const row = Math.ceil((i + 1) / 10)
+ ctx.drawImage(sponge, width, sponge.height * (row - 1))
+ if (width + sponge.width === sponge.width * (rows > 1 ? 10 : amount)) { width = 0 } else width += sponge.width
}
return message.channel.send({
- files: [{ attachment: canvas.toBuffer(), name: "cursed-sponge.png" }]
- });
+ files: [{ attachment: canvas.toBuffer(), name: 'cursed-sponge.png' }]
+ })
}
-};
+}
diff --git a/commands/meme/drake.js b/commands/meme/drake.js
index d93801c..fe17f13 100644
--- a/commands/meme/drake.js
+++ b/commands/meme/drake.js
@@ -1,53 +1,53 @@
-const { createCanvas, loadImage } = require("canvas");
-const request = require("node-superfetch");
-const path = require("path");
+const { createCanvas, loadImage } = require('canvas')
+const request = require('node-superfetch')
+const path = require('path')
module.exports = {
config: {
- name: "drake",
- usage: "drake",
+ name: 'drake',
+ usage: 'drake',
aliases: [],
- description: "Send a drake meme",
+ description: 'Send a drake meme',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- message.channel.send("Tag 2 users");
- let collected = await message.channel.awaitMessages(
+ async run (client, message, args) {
+ message.channel.send('Tag 2 users')
+ const collected = await message.channel.awaitMessages(
m => m.author.id === message.author.id,
{
max: 2,
time: 30000
}
- );
- let nahAvatarURL = await message.guild.members.cache
+ )
+ const nahAvatarURL = await message.guild.members.cache
.get(collected.array()[0].content)
- .user.displayAvatarURL({ format: "png", size: 512 });
- let yeahAvatarURL = await message.guild.members.cache
+ .user.displayAvatarURL({ format: 'png', size: 512 })
+ const yeahAvatarURL = await message.guild.members.cache
.get(collected.array()[1].content)
- .user.displayAvatarURL({ format: "png", size: 512 });
- //const nahAvatarURL = nah.displayAvatarURL({ format: "png", size: 512 });
- // const yeahAvatarURL = yeah.displayAvatarURL({ format: "png", size: 512 });
+ .user.displayAvatarURL({ format: 'png', size: 512 })
+ // const nahAvatarURL = nah.displayAvatarURL({ format: "png", size: 512 });
+ // const yeahAvatarURL = yeah.displayAvatarURL({ format: "png", size: 512 });
try {
const base = await loadImage(
- path.join(__dirname, "..", "..", "assets", "drakeposting.png")
- );
- const nahAvatarData = await request.get(nahAvatarURL);
- const nahAvatar = await loadImage(nahAvatarData.body);
- const yeahAvatarData = await request.get(yeahAvatarURL);
- const yeahAvatar = await loadImage(yeahAvatarData.body);
- const canvas = createCanvas(base.width, base.height);
- const ctx = canvas.getContext("2d");
- ctx.drawImage(base, 0, 0);
- ctx.drawImage(nahAvatar, 512, 0, 512, 512);
- ctx.drawImage(yeahAvatar, 512, 512, 512, 512);
+ path.join(__dirname, '..', '..', 'assets', 'drakeposting.png')
+ )
+ const nahAvatarData = await request.get(nahAvatarURL)
+ const nahAvatar = await loadImage(nahAvatarData.body)
+ const yeahAvatarData = await request.get(yeahAvatarURL)
+ const yeahAvatar = await loadImage(yeahAvatarData.body)
+ const canvas = createCanvas(base.width, base.height)
+ const ctx = canvas.getContext('2d')
+ ctx.drawImage(base, 0, 0)
+ ctx.drawImage(nahAvatar, 512, 0, 512, 512)
+ ctx.drawImage(yeahAvatar, 512, 512, 512, 512)
return message.channel.send({
- files: [{ attachment: canvas.toBuffer(), name: "drakeposting.png" }]
- });
+ files: [{ attachment: canvas.toBuffer(), name: 'drakeposting.png' }]
+ })
} catch (err) {
return message.reply(
`Oh no, an error occurred: \`${err.message}\`. Try again later!`
- );
+ )
}
}
-};
+}
diff --git a/commands/meme/vietnamFlashback.js b/commands/meme/vietnamFlashback.js
index b12c4ec..6a7b6a8 100644
--- a/commands/meme/vietnamFlashback.js
+++ b/commands/meme/vietnamFlashback.js
@@ -1,34 +1,34 @@
-const { createCanvas, loadImage } = require('canvas');
-const request = require('node-superfetch');
-const path = require('path');
+const { createCanvas, loadImage } = require('canvas')
+const request = require('node-superfetch')
+const path = require('path')
module.exports = {
config: {
- name: "vietnamFlashback",
- usage: "vietnamFlashback",
+ name: 'vietnamFlashback',
+ usage: 'vietnamFlashback',
aliases: [],
- description: "Send user avatar with vietnamFlashback at behind",
+ description: 'Send user avatar with vietnamFlashback at behind',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let image = message.author.displayAvatarURL({ format: "png", size: 512 });
+ async run (client, message, args) {
+ const image = message.author.displayAvatarURL({ format: 'png', size: 512 })
try {
- const base = await loadImage(path.join(__dirname, '..', '..', 'assets', 'vietnam-flashbacks.png'));
- const { body } = await request.get(image);
- const data = await loadImage(body);
- const canvas = createCanvas(data.width, data.height);
- const ctx = canvas.getContext('2d');
- const ratio = base.width / base.height;
- const width = Math.round(data.height * ratio);
- ctx.drawImage(base, (data.width / 2) - (width / 2), 0, width, data.height);
- ctx.globalAlpha = 0.675;
- ctx.drawImage(data, 0, 0);
- const attachment = canvas.toBuffer();
- if (Buffer.byteLength(attachment) > 8e+6) return message.reply('Resulting image was above 8 MB.');
- return message.channel.send({ files: [{ attachment, name: 'vietnam-flashbacks.png' }] });
+ const base = await loadImage(path.join(__dirname, '..', '..', 'assets', 'vietnam-flashbacks.png'))
+ const { body } = await request.get(image)
+ const data = await loadImage(body)
+ const canvas = createCanvas(data.width, data.height)
+ const ctx = canvas.getContext('2d')
+ const ratio = base.width / base.height
+ const width = Math.round(data.height * ratio)
+ ctx.drawImage(base, (data.width / 2) - (width / 2), 0, width, data.height)
+ ctx.globalAlpha = 0.675
+ ctx.drawImage(data, 0, 0)
+ const attachment = canvas.toBuffer()
+ if (Buffer.byteLength(attachment) > 8e+6) return message.reply('Resulting image was above 8 MB.')
+ return message.channel.send({ files: [{ attachment, name: 'vietnam-flashbacks.png' }] })
} catch (err) {
- return message.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`);
+ return message.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`)
}
}
-};
+}
diff --git a/commands/millionaire/game.js b/commands/millionaire/game.js
index f4b3d99..1576639 100644
--- a/commands/millionaire/game.js
+++ b/commands/millionaire/game.js
@@ -1,72 +1,71 @@
-const Discord = require("discord.js");
+const Discord = require('discord.js')
const questionsModel = require(process.env.NODE_PATH +
- "/model/questionsModel.js");
+ '/model/questionsModel.js')
module.exports = {
config: {
- name: "game",
+ name: 'game',
aliases: [],
- category: "millionaire",
+ category: 'millionaire',
description:
- "[game] \n [game set category :id] \n [game set difficulty {easy|medium|hard}] \n [game set totalQues {0 {
- let config = client.guildSettings.get(message.guild.id).gameConfig;
+ const config = client.guildSettings.get(message.guild.id).gameConfig
if (args.length == 0) {
return await message.channel.send(
new Discord.MessageEmbed()
.addField(
- "Category:",
+ 'Category:',
`ID:${config.category}| Name:${config.categoryName}`
)
- .addField("difficulty", config.difficulty ? config.difficulty : "ALL")
- .addField("Total questions", config.numberQuestions)
- );
+ .addField('difficulty', config.difficulty ? config.difficulty : 'ALL')
+ .addField('Total questions', config.numberQuestions)
+ )
}
- if (args[0] == "get") {
- let categorys = await questionsModel.getCategoryDetail();
- let embed = new Discord.MessageEmbed()
- .setTitle("CATEGORY")
- .setColor("RED");
- for (let car of categorys) {
+ if (args[0] == 'get') {
+ const categorys = await questionsModel.getCategoryDetail()
+ const embed = new Discord.MessageEmbed()
+ .setTitle('CATEGORY')
+ .setColor('RED')
+ for (const car of categorys) {
embed.addField(
`**${car.id}**. ${car.name}`,
`Easy: ${car.category_question_count.total_easy_question_count}
Medium: ${car.category_question_count.total_medium_question_count}
Hard: ${car.category_question_count.total_hard_question_count}`,
true
- );
+ )
}
- return message.channel.send(embed);
+ return message.channel.send(embed)
}
- if (args[0] == "set") {
- if (args.length <= 2)
- return message.reply("WHAT THE FUCK IS THE VARIBLE AND VALUE?");
- let varible = args[1].toLowerCase();
- let value = args[2].toLowerCase();
- if (varible == "category") {
- config[varible] = value;
- config.categoryName = await questionsModel.getCategoryName(value);
- if (config.categoryName == "ALL") config[varible] = undefined;
- return message.reply(`Set ${varible} to ${config.categoryName}`);
+ if (args[0] == 'set') {
+ if (args.length <= 2) { return message.reply('WHAT THE FUCK IS THE VARIBLE AND VALUE?') }
+ const varible = args[1].toLowerCase()
+ const value = args[2].toLowerCase()
+ if (varible == 'category') {
+ config[varible] = value
+ config.categoryName = await questionsModel.getCategoryName(value)
+ if (config.categoryName == 'ALL') config[varible] = undefined
+ return message.reply(`Set ${varible} to ${config.categoryName}`)
}
- if (varible == "difficulty") {
- config[varible] = value;
- if (!["easy", "medium", "hard"].includes(value)) {
- config[varible] = undefined;
+ if (varible == 'difficulty') {
+ config[varible] = value
+ if (!['easy', 'medium', 'hard'].includes(value)) {
+ config[varible] = undefined
}
return message.reply(
- `Set ${varible} to ${config.difficulty ? config.difficulty : "ALL"}`
- );
+ `Set ${varible} to ${config.difficulty ? config.difficulty : 'ALL'}`
+ )
}
- if (varible == "totalques") {
+ if (varible == 'totalques') {
if (value > 0 && value <= 50) {
- config.numberQuestions = value;
- return message.reply(`Set Total questions to ${config[varible]}`);
+ config.numberQuestions = value
+ return message.reply(`Set Total questions to ${config[varible]}`)
}
}
}
- },
-};
+ }
+}
diff --git a/commands/millionaire/info.js b/commands/millionaire/info.js
index c07ab89..0a647b4 100644
--- a/commands/millionaire/info.js
+++ b/commands/millionaire/info.js
@@ -1,34 +1,34 @@
-const Discord = require("discord.js");
+const Discord = require('discord.js')
module.exports = {
config: {
- name: "info",
+ name: 'info',
aliases: [],
- category: "millionaire",
- description: "Info of this game",
+ category: 'millionaire',
+ description: 'Info of this game',
// usage: '[command]',
enabled: true,
ownerOnly: false
},
run: async (client, message, args) => {
- let game = message.guild.game;
- let state = game ? game.state : null;
- if (state == null || state == "preInit") {
- message.reply("game not setup yet");
- return;
+ const game = message.guild.game
+ const state = game ? game.state : null
+ if (state == null || state == 'preInit') {
+ message.reply('game not setup yet')
+ return
}
- let currentQuestion = game.currentQuestion;
- let totalQuestion = game.config.numberQuestions;
- let playersList = game
+ const currentQuestion = game.currentQuestion
+ const totalQuestion = game.config.numberQuestions
+ const playersList = game
.getTopPlayer()
- .map(e => `${e.currentQuestion} ${e.user} ${e.alive ? "✅" : ":x:"}\n`);
+ .map(e => `${e.currentQuestion} ${e.user} ${e.alive ? '✅' : ':x:'}\n`)
await message.channel.send(
new Discord.MessageEmbed()
- .setColor("#28f7dc")
- .setTitle("Thông tin")
+ .setColor('#28f7dc')
+ .setTitle('Thông tin')
.setTimestamp()
- .addField("Câu hỏi hiện tại:", currentQuestion + "/" + totalQuestion)
- .addField("Danh sách người chơi:", playersList)
- );
+ .addField('Câu hỏi hiện tại:', currentQuestion + '/' + totalQuestion)
+ .addField('Danh sách người chơi:', playersList)
+ )
}
-};
+}
diff --git a/commands/millionaire/start.js b/commands/millionaire/start.js
index 04d27f7..6b03fe7 100644
--- a/commands/millionaire/start.js
+++ b/commands/millionaire/start.js
@@ -1,99 +1,97 @@
-const Discord = require("discord.js");
+const Discord = require('discord.js')
const questionsModel = require(process.env.NODE_PATH +
- "/model/questionsModel.js");
-const Game = require(process.env.NODE_PATH + "/model/gameModel.js");
+ '/model/questionsModel.js')
+const Game = require(process.env.NODE_PATH + '/model/gameModel.js')
module.exports = {
config: {
- name: "start",
+ name: 'start',
aliases: [],
- category: "millionaire",
- description: "Start the game",
+ category: 'millionaire',
+ description: 'Start the game',
enabled: true,
- ownerOnly: false,
+ ownerOnly: false
},
run: async (client, message, args) => {
try {
- let game = message.guild.game;
- if (game && (game.state === "playing" || game.state === "preInit"))
- return message.reply("ANOTHER GAME IS PLAYING!!!!");
- await setup(client, message);
- game = message.guild.game;
- game.play(message);
+ let game = message.guild.game
+ if (game && (game.state === 'playing' || game.state === 'preInit')) { return message.reply('ANOTHER GAME IS PLAYING!!!!') }
+ await setup(client, message)
+ game = message.guild.game
+ game.play(message)
} catch (e) {
- console.log(e);
- return e;
+ console.log(e)
+ return e
}
- },
-};
+ }
+}
-async function setup(client, message) {
- //checkAPI
- let checkDb = await questionsModel.checkDb();
+async function setup (client, message) {
+ // checkAPI
+ const checkDb = await questionsModel.checkDb()
if (!checkDb) {
- throw message.channel.send("QUESTION API ERRORS,CANT PLAY NOW");
+ throw message.channel.send('QUESTION API ERRORS,CANT PLAY NOW')
}
- //game Object
- if (!message.guild.game || message.guild.game.state !== "playing") {
- let config = client.guildSettings.get(message.guild.id).gameConfig;
- message.guild.game = new Game(config);
+ // game Object
+ if (!message.guild.game || message.guild.game.state !== 'playing') {
+ const config = client.guildSettings.get(message.guild.id).gameConfig
+ message.guild.game = new Game(config)
}
- let game = message.guild.game;
- game.state = "preInit";
- if (game.state === "playing") {
- throw message.reply("ANOTHER GAME IS PLAYING!!!!");
+ const game = message.guild.game
+ game.state = 'preInit'
+ if (game.state === 'playing') {
+ throw message.reply('ANOTHER GAME IS PLAYING!!!!')
}
- let config = game.config;
+ const config = game.config
const embed = new Discord.MessageEmbed()
- .setColor("#a3b5a5")
+ .setColor('#a3b5a5')
.setTitle('Ai là thằng lú <(")')
- .addField("Category", config.categoryName)
- .addField("Difficulty", config.difficulty, true)
- .addField("Number Of Questions", config.numberQuestions, true)
+ .addField('Category', config.categoryName)
+ .addField('Difficulty', config.difficulty, true)
+ .addField('Number Of Questions', config.numberQuestions, true)
.setThumbnail(
- "https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG"
+ 'https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG'
)
- .setDescription("✅ To Play")
+ .setDescription('✅ To Play')
.setTimestamp()
.setFooter(
- "Ai là thằng lú",
- "https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG"
+ 'Ai là thằng lú',
+ 'https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG'
)
- .addField("Command", 'type "confirm" if you ready!');
- const msg = await message.channel.send(embed);
- await msg.react("✅");
+ .addField('Command', 'type "confirm" if you ready!')
+ const msg = await message.channel.send(embed)
+ await msg.react('✅')
- let collected = await message.channel.awaitMessages(
+ const collected = await message.channel.awaitMessages(
(m) =>
m.author.id === message.author.id &&
- m.content.toLowerCase() === "confirm",
+ m.content.toLowerCase() === 'confirm',
{
max: 1,
- time: 60000,
+ time: 60000
}
- );
- let user_list = msg.reactions.cache.first().users.cache;
- let players = [];
- for (let user of user_list) {
- if (!user[1].bot) players.push(user[1]);
+ )
+ const user_list = msg.reactions.cache.first().users.cache
+ const players = []
+ for (const user of user_list) {
+ if (!user[1].bot) players.push(user[1])
}
if (players.length === 0) {
- throw message.reply("No one want to play :((");
+ throw message.reply('No one want to play :((')
}
- await game.init(players);
- if (game.questions.length == 0)
- return "SOMETHING ERRORS WITH THE QUESTIONS :) PLEASE CHANGE ";
+ await game.init(players)
+ if (game.questions.length == 0) { return 'SOMETHING ERRORS WITH THE QUESTIONS :) PLEASE CHANGE ' }
const embed2 = new Discord.MessageEmbed()
- .setColor("#a3b5a5")
+ .setColor('#a3b5a5')
.setTitle('Ai là triệu phú <(")')
.setThumbnail(
- "https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG"
+ 'https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG'
)
.setTimestamp()
.setFooter(
- "Ai la trieu phu",
- "https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG"
+ 'Ai la trieu phu',
+ 'https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG'
)
- .addField("Players:", players.join("\n"));
- message.channel.send(embed2);
+ .addField('Players:', players.join('\n'))
+ message.channel.send(embed2)
}
diff --git a/commands/moderation/automute.js b/commands/moderation/automute.js
index d1968aa..09c08b8 100644
--- a/commands/moderation/automute.js
+++ b/commands/moderation/automute.js
@@ -1,69 +1,65 @@
-const muteModel = require("../../model/mute.model");
-const Pagination = require("discord-paginationembed");
+const muteModel = require('../../model/mute.model')
+const Pagination = require('discord-paginationembed')
module.exports = {
config: {
- name: "automute",
- usage: "automute",
+ name: 'automute',
+ usage: 'automute',
aliases: [],
- description: "Auto mute target user.",
+ description: 'Auto mute target user.',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- if (!message.member.hasPermission("MUTE_MEMBERS"))
- return message.reply("Insufficient permission");
- let target = await message.mentions.members.first();
- let targetId = target ? target.id : message.guild.ownerID;
- let userData = await message.guild.members.cache.get(targetId);
- if (!userData)
- message.reply("Something happened, please tag the user probably");
- let user = {
+ async run (client, message, args) {
+ if (!message.member.hasPermission('MUTE_MEMBERS')) { return message.reply('Insufficient permission') }
+ const target = await message.mentions.members.first()
+ const targetId = target ? target.id : message.guild.ownerID
+ const userData = await message.guild.members.cache.get(targetId)
+ if (!userData) { message.reply('Something happened, please tag the user probably') }
+ const user = {
id: userData.user.id,
username: userData.user.username,
discriminator: userData.user.discriminator,
- guildID: message.guild.id,
- };
- if (args.includes("--remove")) {
- muteModel.remove(user);
- message.reply("Automute unbanned for " + user.username);
- } else if (args.includes("--list")) {
- let listdata = await muteModel.list(message.guild.id);
- sendPage(listdata);
+ guildID: message.guild.id
+ }
+ if (args.includes('--remove')) {
+ muteModel.remove(user)
+ message.reply('Automute unbanned for ' + user.username)
+ } else if (args.includes('--list')) {
+ const listdata = await muteModel.list(message.guild.id)
+ sendPage(listdata)
} else {
- const check = await muteModel.exist(user);
- if (check.length !== 0)
- message.reply("User has already in the automute list");
- else await muteModel.add(user);
+ const check = await muteModel.exist(user)
+ if (check.length !== 0) { message.reply('User has already in the automute list') } else await muteModel.add(user)
}
- async function sendPage(users) {
- let embeds = [];
+ async function sendPage (users) {
+ const embeds = []
users.forEach((entry) => {
- let data = {
+ const data = {
id: entry.id,
username: entry.username,
- guildID: entry.guildID,
- };
- embeds.push(data);
- });
- let msg = new Pagination.FieldsEmbed()
+ guildID: entry.guildID
+ }
+ embeds.push(data)
+ })
+ const msg = new Pagination.FieldsEmbed()
.setArray(embeds)
.setAuthorizedUsers([])
.setChannel(message.channel)
.setPageIndicator(true)
- .formatField(`ID`, (i) => i.id)
- .formatField("Username", (i) => i.username)
- .formatField(`GuildID`, (i) => i.guildID)
+ .formatField('ID', (i) => i.id)
+ .formatField('Username', (i) => i.username)
+ .formatField('GuildID', (i) => i.guildID)
.setElementsPerPage(5)
.setDeleteOnTimeout(true)
- .setEmojisFunctionAfterNavigation(true);
+ .setEmojisFunctionAfterNavigation(true)
msg.embed
.setThumbnail(
- client.user.avatarURL({ format: "png", dynamic: true, size: 1024 })
+ client.user.avatarURL({ format: 'png', dynamic: true, size: 1024 })
)
- .setColor("#0390fc")
- .setFooter("Created by wrose");
- await msg.build();
+ .setColor('#0390fc')
+ .setFooter('Created by wrose')
+ await msg.build()
}
- },
-};
+ }
+}
diff --git a/commands/moderation/backup.js b/commands/moderation/backup.js
index f974208..6c86598 100644
--- a/commands/moderation/backup.js
+++ b/commands/moderation/backup.js
@@ -1,31 +1,30 @@
-let { sendError, verify } = require("../../utils/utility");
-const { MessageEmbed } = require("discord.js");
-const fs = require("fs");
-var backups = JSON.parse(fs.readFileSync("./data/backups.json", "utf8"));
+const { sendError, verify } = require('../../utils/utility')
+const { MessageEmbed } = require('discord.js')
+const fs = require('fs')
+var backups = JSON.parse(fs.readFileSync('./data/backups.json', 'utf8'))
module.exports = {
config: {
- name: "backup",
- usage: "backup [--arguement]",
- description: "Create a backup version of current Discord server.",
- aliases: [""],
+ name: 'backup',
+ usage: 'backup [--arguement]',
+ description: 'Create a backup version of current Discord server.',
+ aliases: [''],
enabled: true,
- ownerOnly: false,
+ ownerOnly: false
},
- async run(client, message, args) {
- if (message.author.id !== message.guild.ownerID)
- return message.reply("This can only be executed by the server owner");
+ async run (client, message, args) {
+ if (message.author.id !== message.guild.ownerID) { return message.reply('This can only be executed by the server owner') }
try {
- let info = client.emojis.cache.get("655091815401127966") || "ℹ️"; //https://cdn.discordapp.com/emojis/655091815401127966.png?v=1
- let waiting = client.emojis.cache.get("655695570769412096") || "⌛"; //https://images-ext-1.discordapp.net/external/lWj3uW4qvfFB9t0QgGsDJ8vLvh5bSObQ-wwUxYFH4wo/https/images-ext-1.discordapp.net/external/AzWR8HxPJ4t4rPA1DagxJkZsOCOMp4OTgwxL3QAjF4U/https/cdn.discordapp.com/emojis/424900448663633920.gif
- let green = client.emojis.cache.get("655696285286006784") || "✅"; //https://images-ext-2.discordapp.net/external/NU9I3Vhi79KV6srTXLJuHxOgiyzmEwgS5nFAbA13_YQ/https/cdn0.iconfinder.com/data/icons/small-n-flat/24/678134-sign-check-512.png
- let error = client.emojis.cache.get("655704809483141141") || "❌"; //https://cdn.discordapp.com/emojis/655704809483141141.png?v=1
- let warning = client.emojis.cache.get("656030540310380574") || "⚠️"; //https://cdn.discordapp.com/emojis/656030540310380574.png?v=1
- await message.reply("Are you sure you want to backup your server ?");
- const verification = await verify(message.channel, message.author);
- if (!verification) return message.reply("Aborted");
- await message.reply("Creating backup on your server. Please wait ...");
- if (args[0] === "create" || args[0] === "c") {
+ const info = client.emojis.cache.get('655091815401127966') || 'ℹ️' // https://cdn.discordapp.com/emojis/655091815401127966.png?v=1
+ const waiting = client.emojis.cache.get('655695570769412096') || '⌛' // https://images-ext-1.discordapp.net/external/lWj3uW4qvfFB9t0QgGsDJ8vLvh5bSObQ-wwUxYFH4wo/https/images-ext-1.discordapp.net/external/AzWR8HxPJ4t4rPA1DagxJkZsOCOMp4OTgwxL3QAjF4U/https/cdn.discordapp.com/emojis/424900448663633920.gif
+ const green = client.emojis.cache.get('655696285286006784') || '✅' // https://images-ext-2.discordapp.net/external/NU9I3Vhi79KV6srTXLJuHxOgiyzmEwgS5nFAbA13_YQ/https/cdn0.iconfinder.com/data/icons/small-n-flat/24/678134-sign-check-512.png
+ const error = client.emojis.cache.get('655704809483141141') || '❌' // https://cdn.discordapp.com/emojis/655704809483141141.png?v=1
+ const warning = client.emojis.cache.get('656030540310380574') || '⚠️' // https://cdn.discordapp.com/emojis/656030540310380574.png?v=1
+ await message.reply('Are you sure you want to backup your server ?')
+ const verification = await verify(message.channel, message.author)
+ if (!verification) return message.reply('Aborted')
+ await message.reply('Creating backup on your server. Please wait ...')
+ if (args[0] === 'create' || args[0] === 'c') {
await message.guild.roles.cache
.filter(
(r) =>
@@ -38,36 +37,36 @@ module.exports = {
) > 0
) {
return message.channel.send(
- "My role is not the highest role. Aborting...!"
- );
+ 'My role is not the highest role. Aborting...!'
+ )
}
- });
+ })
- let creatingEmbed = new MessageEmbed()
+ const creatingEmbed = new MessageEmbed()
.setTitle(`${waiting} Please wait ...`)
- .setDescription("Creating backup ... Please wait");
+ .setDescription('Creating backup ... Please wait')
message.channel.send(creatingEmbed).then((m) => {
- let id = makeid(16);
+ const id = makeid(16)
const channels = message.guild.channels.cache
.sort(function (a, b) {
- return a.position - b.position;
+ return a.position - b.position
})
.array()
.map((c) => {
const channel = {
type: c.type,
name: c.name,
- postion: c.calculatedPosition,
- };
- if (c.parent) channel.parent = c.parent.name;
- return channel;
- });
+ postion: c.calculatedPosition
+ }
+ if (c.parent) channel.parent = c.parent.name
+ return channel
+ })
const roles = message.guild.roles.cache
- .filter((r) => r.name !== "@everyone")
+ .filter((r) => r.name !== '@everyone')
.sort(function (a, b) {
- return a.position - b.position;
+ return a.position - b.position
})
.array()
.map((r) => {
@@ -77,12 +76,12 @@ module.exports = {
hoist: r.hoist,
permissions: r.permissions,
mentionable: r.mentionable,
- position: r.position,
- };
- return role;
- });
+ position: r.position
+ }
+ return role
+ })
- if (!backups[message.author.id]) backups[message.author.id] = {};
+ if (!backups[message.author.id]) backups[message.author.id] = {}
backups[message.author.id][id] = {
icon: message.guild.iconURL,
name: message.guild.name,
@@ -90,92 +89,90 @@ module.exports = {
members: message.guild.memberCount,
createdAt: message.guild.createdAt,
roles,
- channels,
- };
+ channels
+ }
- save();
- let result = new MessageEmbed()
+ save()
+ const result = new MessageEmbed()
.setTitle(`${info} Info`)
.setDescription(
`Created backup of **${message.guild.name}** with the Backup id \`${id}\``
)
.addField(
- "Usage",
+ 'Usage',
`\`\`\`backup load ${id}\`\`\`
\`\`\` info ${id}\`\`\``
)
- .setColor("#5DBCD2");
+ .setColor('#5DBCD2')
- message.author.send(result);
+ message.author.send(result)
- let resultPublic = new MessageEmbed()
+ const resultPublic = new MessageEmbed()
.setTitle(`${green} Voila!`)
.setDescription(
`Created backup of **${message.guild.name}** with the Backup id \`${id}\``
)
.addField(
- "Usage",
+ 'Usage',
`\`\`\` backup load ${id}\`\`\`
\`\`\` backup info ${id}\`\`\``
)
- .setColor("#59C57B");
+ .setColor('#59C57B')
- m.edit(resultPublic);
- });
+ m.edit(resultPublic)
+ })
}
- if (args[0] === "delete") {
- let code = args[1];
- let errorEmbed = new MessageEmbed()
+ if (args[0] === 'delete') {
+ const code = args[1]
+ const errorEmbed = new MessageEmbed()
.setTitle(`${error} Error`)
.setDescription(
`You forgot to define the argument backup_id. Use help backup load for more information.
[Support](https://discord.club/discord)`
)
- .setColor("#a11616");
- if (!code) return message.channel.send(errorEmbed);
+ .setColor('#a11616')
+ if (!code) return message.channel.send(errorEmbed)
- let cantfindbackup = new MessageEmbed()
+ const cantfindbackup = new MessageEmbed()
.setTitle(`${error} Error`)
.setTitle(`You have no backup with the id ${code}.`)
- .setColor("#a11616");
- if (!backups[message.author.id][code])
- return message.channel.send(cantfindbackup);
+ .setColor('#a11616')
+ if (!backups[message.author.id][code]) { return message.channel.send(cantfindbackup) }
- delete backups[message.author.id][code];
- save();
+ delete backups[message.author.id][code]
+ save()
- let deletedsuc = new MessageEmbed()
+ const deletedsuc = new MessageEmbed()
.setTitle(`${green} Voila!`)
- .setDescription(`Successfully **deleted backup**.`)
- .setColor("#59C57B");
- message.channel.send(deletedsuc);
+ .setDescription('Successfully **deleted backup**.')
+ .setColor('#59C57B')
+ message.channel.send(deletedsuc)
}
- if (args[0] === "load" || args[0] === "l") {
- let error = client.emojis.cache.get("655704809483141141") || "❌";
- let code = args[1];
- let errorEmbed = new MessageEmbed().setTitle(`${error} Error`)
+ if (args[0] === 'load' || args[0] === 'l') {
+ const error = client.emojis.cache.get('655704809483141141') || '❌'
+ const code = args[1]
+ const errorEmbed = new MessageEmbed().setTitle(`${error} Error`)
.setDescription(`You forgot to define the argument backup_id. Use help backup load for more information.
-[Support](https://discord.gg/NDgrJc2)`);
- if (!code) return message.channel.send(errorEmbed);
- let cantfindbackup = new MessageEmbed()
+[Support](https://discord.gg/NDgrJc2)`)
+ if (!code) return message.channel.send(errorEmbed)
+ const cantfindbackup = new MessageEmbed()
.setTitle(`${error} Error`)
.setTitle(`You have no backup with the id ${code}.`)
- .setDescription("[Support](https://discord.club/discord)")
- .setColor("#a11616");
- if (!backups[message.author.id][code])
- return message.channel.send(cantfindbackup);
+ .setDescription('[Support](https://discord.club/discord)')
+ .setColor('#a11616')
+ if (!backups[message.author.id][code]) { return message.channel.send(cantfindbackup) }
message.guild.channels.cache.forEach((channel) => {
- channel.delete("For Loading A Backup");
- });
+ channel.delete('For Loading A Backup')
+ })
message.guild.roles.cache
.filter((role) => role.members.every((member) => !member.user.bot))
.forEach((role) => {
- role.delete("For Loading A Backup");
- });
+ role.delete('For Loading A Backup')
+ })
await backups[message.author.id][code].roles.forEach(async function (
role
) {
@@ -186,166 +183,164 @@ module.exports = {
permissions: role.permissions,
hoist: role.hoist,
mentionable: role.mentionable,
- position: role.position,
+ position: role.position
})
.then((role) => {
- role.setPosition(role.position);
- });
- });
+ role.setPosition(role.position)
+ })
+ })
await backups[message.author.id][code].channels
- .filter((c) => c.type === "category")
+ .filter((c) => c.type === 'category')
.forEach(async function (ch) {
message.guild.channels.create(ch.name, {
type: ch.type,
- permissionOverwrites: ch.permissionOverwrites,
- });
- });
+ permissionOverwrites: ch.permissionOverwrites
+ })
+ })
await backups[message.author.id][code].channels
- .filter((c) => c.type !== "category")
+ .filter((c) => c.type !== 'category')
.forEach(async function (ch) {
message.guild.channels
.create(ch.name, {
type: ch.type,
- permissionOverwrites: ch.permissionOverwrites,
+ permissionOverwrites: ch.permissionOverwrites
})
.then((c) => {
const parent = message.guild.channels.cache
- .filter((c) => c.type === "category")
- .find((c) => c.name === ch.parent);
- ch.parent ? c.setParent(parent) : "";
- });
- });
- message.guild.setName(backups[message.author.id][code].name);
- message.guild.setIcon(backups[message.author.id][code].icon);
+ .filter((c) => c.type === 'category')
+ .find((c) => c.name === ch.parent)
+ ch.parent ? c.setParent(parent) : ''
+ })
+ })
+ message.guild.setName(backups[message.author.id][code].name)
+ message.guild.setIcon(backups[message.author.id][code].icon)
}
- if (args[0] === "info" || args[0] === "i") {
- let id = args[1];
- let MissingbackupinfoEmbed = new MessageEmbed()
+ if (args[0] === 'info' || args[0] === 'i') {
+ const id = args[1]
+ const MissingbackupinfoEmbed = new MessageEmbed()
.setTitle(`${error} Error`)
.setDescription(
`You forgot to define the argument **backup_id**. Use \`help backup info\` for more information
[Support](https://discord.club/discord)`
)
- .setColor("#a11616");
- if (!id) return message.channel.send(MissingbackupinfoEmbed);
+ .setColor('#a11616')
+ if (!id) return message.channel.send(MissingbackupinfoEmbed)
- let cantfindEmbed = new MessageEmbed()
+ const cantfindEmbed = new MessageEmbed()
.setTitle(`${error} Error`)
.setDescription(
`You have **no backup** with the id \`${id}\`.
"[Support](https://discord.club/discord)`
)
- .setColor("#a11616");
- if (!backups[message.author.id][id])
- return message.channel.send(cantfindEmbed);
+ .setColor('#a11616')
+ if (!backups[message.author.id][id]) { return message.channel.send(cantfindEmbed) }
try {
- let infoEmbed = new MessageEmbed()
+ const infoEmbed = new MessageEmbed()
.setTitle(backups[message.author.id][id].name)
.setThumbnail(backups[message.author.id][id].icon)
.addField(
- "Creator",
+ 'Creator',
`<@${backups[message.author.id][id].owner}>`,
true
)
- .addField("Members", backups[message.author.id][id].members, true)
- .addField("Created At", backups[message.author.id][id].createdAt)
+ .addField('Members', backups[message.author.id][id].members, true)
+ .addField('Created At', backups[message.author.id][id].createdAt)
.addField(
- "Channels",
+ 'Channels',
`\`\`\`${backups[message.author.id][id].channels
.map((channel) => channel.name)
- .join("\n")}\`\`\``,
+ .join('\n')}\`\`\``,
true
)
.addField(
- "Roles",
+ 'Roles',
`\`\`\`${backups[message.author.id][id].roles
.map((role) => role.name)
- .join("\n")}\`\`\``,
+ .join('\n')}\`\`\``,
true
- );
- message.channel.send(infoEmbed);
+ )
+ message.channel.send(infoEmbed)
} catch (e) {
hastebins(
backups[message.author.id][id].channels
.map((channel) => channel.name)
- .join("\n"),
- "txt"
+ .join('\n'),
+ 'txt'
).then((ch) => {
hastebins(
backups[message.author.id][id].roles
.map((role) => role.name)
- .join("\n"),
- "txt"
+ .join('\n'),
+ 'txt'
).then((ro) => {
- let infoEmbed = new MessageEmbed()
+ const infoEmbed = new MessageEmbed()
.setTitle(backups[message.author.id][id].name)
.setThumbnail(backups[message.author.id][id].icon)
.addField(
- "Creator",
+ 'Creator',
`<@${backups[message.author.id][id].owner}>`,
true
)
.addField(
- "Members",
+ 'Members',
backups[message.author.id][id].members,
true
)
.addField(
- "Created At",
+ 'Created At',
backups[message.author.id][id].createdAt
)
- .addField("Channels", ch, true)
- .addField("Roles", ro, true);
- message.channel.send(infoEmbed);
- });
- });
+ .addField('Channels', ch, true)
+ .addField('Roles', ro, true)
+ message.channel.send(infoEmbed)
+ })
+ })
}
}
- if (args[0] === "purge") {
- let errorEmbed = new MessageEmbed()
+ if (args[0] === 'purge') {
+ const errorEmbed = new MessageEmbed()
.setTitle(`${error} Error`)
.setDescription(
`You did'nt backup any server yet
[Support](https://discord.club/discord)`
)
- .setColor("#a11616");
- if (!backups[message.author.id])
- return message.channel.send(errorEmbed);
+ .setColor('#a11616')
+ if (!backups[message.author.id]) { return message.channel.send(errorEmbed) }
- let warningEmbed = new MessageEmbed().setTitle(`${warning} Warning`)
+ const warningEmbed = new MessageEmbed().setTitle(`${warning} Warning`)
.setDescription(`Are you sure that you want to delete all your backups?
-__This cannot be undone!__`);
+__This cannot be undone!__`)
message.channel.sendEmbed(warningEmbed).then((msg) => {
- msg.react("✅").then(() => msg.react("❌"));
+ msg.react('✅').then(() => msg.react('❌'))
- let yesFilter = (reaction, user) =>
- reaction.emoji.name === "✅" && user.id === message.author.id;
- let noFilter = (reaction, user) =>
- reaction.emoji.name === "❌" && user.id === message.author.id;
+ const yesFilter = (reaction, user) =>
+ reaction.emoji.name === '✅' && user.id === message.author.id
+ const noFilter = (reaction, user) =>
+ reaction.emoji.name === '❌' && user.id === message.author.id
- let yes = msg.createReactionCollector(yesFilter, { time: 0 });
- let no = msg.createReactionCollector(noFilter, { time: 0 });
+ const yes = msg.createReactionCollector(yesFilter, { time: 0 })
+ const no = msg.createReactionCollector(noFilter, { time: 0 })
- yes.on("collect", (r) => {
- delete backups[message.author.id];
+ yes.on('collect', (r) => {
+ delete backups[message.author.id]
- let deletedsuc = new MessageEmbed()
+ const deletedsuc = new MessageEmbed()
.setTitle(`${green} Voila!`)
- .setDescription(`Deleted all your backups.`)
- .setColor("#59C57B");
- message.channel.send(deletedsuc);
- msg.delete();
- });
+ .setDescription('Deleted all your backups.')
+ .setColor('#59C57B')
+ message.channel.send(deletedsuc)
+ msg.delete()
+ })
- no.on("collect", (r) => {
- msg.delete();
- });
- });
+ no.on('collect', (r) => {
+ msg.delete()
+ })
+ })
}
if (!args[0]) {
@@ -365,37 +360,37 @@ __**Commands**__
backup load Load a backup
backup purge Delete all your backups`
)
- .addField("\u200b", "\u200b")
+ .addField('\u200b', '\u200b')
.setFooter(
`Use \` help [command]\` for more info on a command.
You can also use \` help [category]\` for more info on a category.`
)
- .setColor("#5DBCD2");
- message.channel.send(embed);
- return;
+ .setColor('#5DBCD2')
+ message.channel.send(embed)
+ return
}
- function makeid(length) {
- var result = "";
+ function makeid (length) {
+ var result = ''
var characters =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- var charactersLength = characters.length;
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
+ var charactersLength = characters.length
for (var i = 0; i < length; i++) {
result += characters.charAt(
Math.floor(Math.random() * charactersLength)
- );
+ )
}
- return result;
+ return result
}
- function save() {
- fs.writeFile("./Data/backups.json", JSON.stringify(backups), (err) => {
- if (err) console.error(err);
- });
+ function save () {
+ fs.writeFile('./Data/backups.json', JSON.stringify(backups), (err) => {
+ if (err) console.error(err)
+ })
}
} catch (e) {
- console.log(e);
- sendError(message, e);
+ console.log(e)
+ sendError(message, e)
}
- },
-};
+ }
+}
diff --git a/commands/moderation/ban.js b/commands/moderation/ban.js
index 889437e..bd53b0d 100644
--- a/commands/moderation/ban.js
+++ b/commands/moderation/ban.js
@@ -1,34 +1,34 @@
module.exports = {
config: {
- name: "ban",
- usage: "ban [user] [time] [reason]",
- description: "ban a specific person",
+ name: 'ban',
+ usage: 'ban [user] [time] [reason]',
+ description: 'ban a specific person',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let user = await message.mentions.members.first();
+ async run (client, message, args) {
+ const user = await message.mentions.members.first()
if (!user) {
message.channel.send({
embed: {
- title: "__***PICK A USER FOOL***__",
+ title: '__***PICK A USER FOOL***__',
color: 15158332
}
- });
+ })
}
- let reason = args[2] ? args[2] : "Not specified";
- let time = parseInt(args[1]);
- user.ban({ days: 7 ? !time : time, reason: reason });
- let bannedUser = await client.users.fetch(user.id);
+ const reason = args[2] ? args[2] : 'Not specified'
+ const time = parseInt(args[1])
+ user.ban({ days: 7 ? !time : time, reason: reason })
+ const bannedUser = await client.users.fetch(user.id)
message.channel.send({
embed: {
color: 15158332,
- title: message.author.tag + " has banned a member from this guild",
+ title: message.author.tag + ' has banned a member from this guild',
fields: [
- { name: "User", value: bannedUser.username },
- { name: "Reason", value: reason }
+ { name: 'User', value: bannedUser.username },
+ { name: 'Reason', value: reason }
]
}
- });
+ })
}
-};
+}
diff --git a/commands/moderation/clear.js b/commands/moderation/clear.js
index b4a1fe8..752d781 100644
--- a/commands/moderation/clear.js
+++ b/commands/moderation/clear.js
@@ -1,31 +1,31 @@
module.exports = {
config: {
- name: "clear",
- usage: "clear [number of messages]",
- description: "Delete specific amount of messages",
+ name: 'clear',
+ usage: 'clear [number of messages]',
+ description: 'Delete specific amount of messages',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (isNaN(args[0])) {
message.channel.send({
embed: {
color: 15158332,
title: "__***YOU THINK I'M A FOOL ?***__",
- description: "Specify the amount !!!",
+ description: 'Specify the amount !!!',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
}
if (!isNaN(args[0])) {
- message.channel.bulkDelete(args[0]);
+ message.channel.bulkDelete(args[0])
}
}
-};
+}
diff --git a/commands/moderation/ignoreChannels.js b/commands/moderation/ignoreChannels.js
index 91a2535..55d3828 100644
--- a/commands/moderation/ignoreChannels.js
+++ b/commands/moderation/ignoreChannels.js
@@ -1,36 +1,36 @@
-const guildSettings = require("../../model/guildSettingsModel");
+const guildSettings = require('../../model/guildSettingsModel')
module.exports = {
config: {
- name: "ignoreChannels",
- usage: "ignoreChannels [channelID]",
+ name: 'ignoreChannels',
+ usage: 'ignoreChannels [channelID]',
description:
- "Set a text channel as an ignored channel, i will not notice any messages from this channel",
+ 'Set a text channel as an ignored channel, i will not notice any messages from this channel',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (message.member.guild.channels.cache.find(x => x.id === args[0])) {
- let data = {
+ const data = {
guildID: message.member.guild.id,
ignoredChannel: args[0]
- };
- guildSettings.updateIgnoredChannels(data);
- client.guildSettings.set(data.guildID, data);
+ }
+ guildSettings.updateIgnoredChannels(data)
+ client.guildSettings.set(data.guildID, data)
message.channel.send({
embed: {
color: 3447003,
title:
message.member.guild.channels.cache.find(x => x.id === args[0])
- .name + " will be ignored"
+ .name + ' will be ignored'
}
- });
+ })
} else {
message.channel.send({
embed: {
color: 15158332,
- title: "No such channel found."
+ title: 'No such channel found.'
}
- });
+ })
}
}
-};
+}
diff --git a/commands/moderation/kick.js b/commands/moderation/kick.js
index cf8c23a..439bfe1 100644
--- a/commands/moderation/kick.js
+++ b/commands/moderation/kick.js
@@ -1,42 +1,41 @@
-let { verify } = require("../../utils/utility");
+const { verify } = require('../../utils/utility')
module.exports = {
config: {
- name: "kick",
- usage: "kick [user] [reason]",
- description: "Kick a specific person",
+ name: 'kick',
+ usage: 'kick [user] [reason]',
+ description: 'Kick a specific person',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- if (!message.member.hasPermission("KICK_MEMBERS"))
- return message.reply("fuck you blyat");
+ async run (client, message, args) {
+ if (!message.member.hasPermission('KICK_MEMBERS')) { return message.reply('fuck you blyat') }
try {
- let user = await message.mentions.members.first();
+ const user = await message.mentions.members.first()
if (!user) {
message.channel.send({
embed: {
- title: "__***PICK A USER FOOL***__",
- color: 15158332,
- },
- });
+ title: '__***PICK A USER FOOL***__',
+ color: 15158332
+ }
+ })
}
- let reason = args[1] ? args[1] : "Not specified";
- const verification = await verify(message.channel, message.author);
- if (!verification) return message.reply("aborted");
- user.kick(reason);
- let kickedUser = await client.users.fetch(user.id);
+ const reason = args[1] ? args[1] : 'Not specified'
+ const verification = await verify(message.channel, message.author)
+ if (!verification) return message.reply('aborted')
+ user.kick(reason)
+ const kickedUser = await client.users.fetch(user.id)
message.channel.send({
embed: {
color: 15158332,
- title: message.author.tag + " has removed a member from this guild",
+ title: message.author.tag + ' has removed a member from this guild',
fields: [
- { name: "User", value: kickedUser.username },
- { name: "Reason", value: reason },
- ],
- },
- });
+ { name: 'User', value: kickedUser.username },
+ { name: 'Reason', value: reason }
+ ]
+ }
+ })
} catch (e) {
- message.author.send(e);
+ message.author.send(e)
}
- },
-};
+ }
+}
diff --git a/commands/moderation/lockdown.js b/commands/moderation/lockdown.js
index 6e36d65..9c23c51 100644
--- a/commands/moderation/lockdown.js
+++ b/commands/moderation/lockdown.js
@@ -1,25 +1,25 @@
module.exports = {
config: {
- name: "lockdown",
- usage: "lockdown [--remove]",
- description: "Turn textChannel into lockdown status",
+ name: 'lockdown',
+ usage: 'lockdown [--remove]',
+ description: 'Turn textChannel into lockdown status',
ownerOnly: false,
enabled: false
},
- async run(client, message, args) {
- if (message.content.includes("--remove")) {
+ async run (client, message, args) {
+ if (message.content.includes('--remove')) {
await message.guild.channels.cache
.find(x => x.id === message.channel.id)
.overwritePermissions(
[
{
id: message.guild.id,
- deny: ["SEND_MESSAGES", "ADD_REACTION"]
+ deny: ['SEND_MESSAGES', 'ADD_REACTION']
}
],
- "Fuck you all"
- );
- message.channel.send("channel is no longer in lockdown");
+ 'Fuck you all'
+ )
+ message.channel.send('channel is no longer in lockdown')
} else {
await message.guild.channels.cache
.find(x => x.id === message.channel.id)
@@ -27,12 +27,12 @@ module.exports = {
[
{
id: message.guild.id,
- allow: ["SEND_MESSAGES", "ADD_REACTION"]
+ allow: ['SEND_MESSAGES', 'ADD_REACTION']
}
],
- "Fuck you all"
- );
- message.channel.send("channel is on lockdown");
+ 'Fuck you all'
+ )
+ message.channel.send('channel is on lockdown')
}
}
-};
+}
diff --git a/commands/moderation/moveMember.js b/commands/moderation/moveMember.js
index 855215c..8a3e2f8 100644
--- a/commands/moderation/moveMember.js
+++ b/commands/moderation/moveMember.js
@@ -1,39 +1,39 @@
-let { verify } = require("../../utils/utility");
+const { verify } = require('../../utils/utility')
module.exports = {
config: {
- name: "moveMembers",
- usage: "moveMembers [source] [destination]",
- description: "Move all members from one channel to another",
+ name: 'moveMembers',
+ usage: 'moveMembers [source] [destination]',
+ description: 'Move all members from one channel to another',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
// let role = message.guild.roles.find(x => x.name === "")
- if (!message.member.hasPermission("MOVE_MEMBERS")) return;
+ if (!message.member.hasPermission('MOVE_MEMBERS')) return
try {
- await message.reply("SURE BLYAT ?");
- const verification = await verify(message.channel, message.author);
- if (!verification) return message.reply("FUCK OFF");
- let voiceChannelOriginal = message.member.guild.channels.cache.find(
+ await message.reply('SURE BLYAT ?')
+ const verification = await verify(message.channel, message.author)
+ if (!verification) return message.reply('FUCK OFF')
+ const voiceChannelOriginal = message.member.guild.channels.cache.find(
(x) => x.id === args[0]
- );
- let destination = message.member.guild.channels.cache.find(
+ )
+ const destination = message.member.guild.channels.cache.find(
(x) => x.id === args[1]
- );
+ )
if (voiceChannelOriginal && destination) {
voiceChannelOriginal.members.forEach(function (member, id) {
- member.voice.setChannel(args[1]);
- });
- return message.reply("Your flight has completed");
+ member.voice.setChannel(args[1])
+ })
+ return message.reply('Your flight has completed')
}
} catch (e) {
message.channel.send({
embed: {
color: 15158332,
title: e.name,
- description: e.message,
- },
- });
+ description: e.message
+ }
+ })
}
- },
-};
+ }
+}
diff --git a/commands/moderation/mute.js b/commands/moderation/mute.js
index 7dde267..ac4251f 100644
--- a/commands/moderation/mute.js
+++ b/commands/moderation/mute.js
@@ -1,118 +1,117 @@
module.exports = {
config: {
- name: "mute",
- usage: "mute [user] [time] [reason]",
- description: "Mute a specific person",
+ name: 'mute',
+ usage: 'mute [user] [time] [reason]',
+ description: 'Mute a specific person',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- //variables
- const muteRole = message.guild.roles.cache.find(x => x.name === "Muted");
- let id = message.mentions.users.first();
- let user = await message.guild.members.cache.get(id.id);
- let knownRoles = [];
- //return if member has no permission
- if (!message.member.hasPermission("MANAGE_GUILD"))
- return message.channel.send("Đừng cố tạo phản nữa.");
- //check variables
- if (!id) return message.channel.send("Specific a user !");
- if (!parseInt(args[1])) return message.channel.send("Invalid time input.");
- //processing
+ async run (client, message, args) {
+ // variables
+ const muteRole = message.guild.roles.cache.find(x => x.name === 'Muted')
+ const id = message.mentions.users.first()
+ const user = await message.guild.members.cache.get(id.id)
+ let knownRoles = []
+ // return if member has no permission
+ if (!message.member.hasPermission('MANAGE_GUILD')) { return message.channel.send('Đừng cố tạo phản nữa.') }
+ // check variables
+ if (!id) return message.channel.send('Specific a user !')
+ if (!parseInt(args[1])) return message.channel.send('Invalid time input.')
+ // processing
if (!muteRole) {
- let tempRole = await message.guild.roles.create({
+ const tempRole = await message.guild.roles.create({
data: {
- name: "Muted",
- color: "#000000",
+ name: 'Muted',
+ color: '#000000',
permissions: []
},
- reason: "Mute role"
- });
- addMute(tempRole);
+ reason: 'Mute role'
+ })
+ addMute(tempRole)
}
if (muteRole) {
- addMute(muteRole);
+ addMute(muteRole)
}
- async function addMute(role) {
- //console.log(user);
+ async function addMute (role) {
+ // console.log(user);
if (user.roles) {
user.roles.cache.forEach(role => {
- knownRoles.push(role.id);
- });
- await user.roles.remove(knownRoles);
+ knownRoles.push(role.id)
+ })
+ await user.roles.remove(knownRoles)
}
- await user.roles.add(role);
+ await user.roles.add(role)
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.updateOverwrite(role, {
SEND_MESSAGES: false,
ADD_REACTION: false,
SPEAK: false
- });
- });
+ })
+ })
if (user.voice.channel) {
- disconnectUser();
+ disconnectUser()
}
message.channel.send({
embed: {
color: 15158332,
- title: "User muted",
- description: message.author.tag + " muted a user",
+ title: 'User muted',
+ description: message.author.tag + ' muted a user',
fields: [
{
- name: "Muted user",
+ name: 'Muted user',
value: id.tag
},
{
- name: "Duration",
+ name: 'Duration',
value: secondsCoverter(args[1])
}
]
}
- });
- setTimeout(async function() {
- await user.roles.remove(role.id);
- await user.roles.add(knownRoles);
- knownRoles = [];
+ })
+ setTimeout(async function () {
+ await user.roles.remove(role.id)
+ await user.roles.add(knownRoles)
+ knownRoles = []
message.channel.send({
embed: {
color: 3066993,
- title: "Unmuted",
- description: "User unmuted",
+ title: 'Unmuted',
+ description: 'User unmuted',
fields: [
{
- name: "Username",
+ name: 'Username',
value: id.tag
},
{
- name: "Mute duration",
+ name: 'Mute duration',
value: secondsCoverter(args[1])
}
]
}
- });
- }, args[1] * 1000);
+ })
+ }, args[1] * 1000)
}
- async function roleChanger(mutedRole) {
+ async function roleChanger (mutedRole) {
user.roles.cache.forEach(role => {
- knownRoles.push(role.id);
- });
- await user.roles.remove(knownRoles);
- await user.roles.add(mutedRole.id);
+ knownRoles.push(role.id)
+ })
+ await user.roles.remove(knownRoles)
+ await user.roles.add(mutedRole.id)
}
- async function disconnectUser() {
- let findVoice = await message.guild.channels.cache.find(
- x => x.name === "temp"
- );
+ async function disconnectUser () {
+ const findVoice = await message.guild.channels.cache.find(
+ x => x.name === 'temp'
+ )
if (findVoice) {
- await user.voice.setChannel(findVoice.id);
- findVoice.delete();
+ await user.voice.setChannel(findVoice.id)
+ findVoice.delete()
} else {
try {
- let tempVoice = await message.guild.channels.create("temp", {
- type: "voice"
- });
- await user.voice.setChannel(tempVoice.id);
- tempVoice.delete();
+ const tempVoice = await message.guild.channels.create('temp', {
+ type: 'voice'
+ })
+ await user.voice.setChannel(tempVoice.id)
+ tempVoice.delete()
} catch (error) {
// console.log(error);
message.channel.send({
@@ -120,16 +119,16 @@ module.exports = {
color: 15158332,
title: error.message
}
- });
+ })
}
}
}
- function secondsCoverter(second) {
- second = Number(second);
- var m = Math.floor((second % 3600) / 60);
- var s = Math.floor((second % 3600) % 60);
+ function secondsCoverter (second) {
+ second = Number(second)
+ var m = Math.floor((second % 3600) / 60)
+ var s = Math.floor((second % 3600) % 60)
- return m + ":" + s;
+ return m + ':' + s
}
}
-};
+}
diff --git a/commands/moderation/prefix.js b/commands/moderation/prefix.js
index 8398bad..da1cf30 100644
--- a/commands/moderation/prefix.js
+++ b/commands/moderation/prefix.js
@@ -1,38 +1,38 @@
-let guildModel = require("../../model/guildSettingsModel");
+const guildModel = require('../../model/guildSettingsModel')
module.exports = {
config: {
- name: "prefix",
- usage: "prefix [new prefix]",
+ name: 'prefix',
+ usage: 'prefix [new prefix]',
aliases: [],
description:
- "Set new prefix for current server. User must have [ADMINISTRATOR] role enabled to use the command.",
+ 'Set new prefix for current server. User must have [ADMINISTRATOR] role enabled to use the command.',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- if (!message.member.hasPermission("ADMINISTRATOR")) {
+ async run (client, message, args) {
+ if (!message.member.hasPermission('ADMINISTRATOR')) {
return message.channel.send({
embed: {
color: 15158332,
- title: "Your role does not match the required permission"
+ title: 'Your role does not match the required permission'
}
- });
+ })
} else {
try {
- await guildModel.updatePrefix(args[0], message.guild.id);
- client.guildSettings.get(message.guild.id).prefix === args[0];
+ await guildModel.updatePrefix(args[0], message.guild.id)
+ client.guildSettings.get(message.guild.id).prefix === args[0]
message.channel.send({
embed: {
color: 3447003,
- title: "Prefix changed to " + args[0]
+ title: 'Prefix changed to ' + args[0]
}
- });
- client.guildSettings.delete(message.guild.id);
- let data = await guildModel.queryGuildSettings(message.guild.id);
- client.guildSettings.set(message.guild.id, data);
+ })
+ client.guildSettings.delete(message.guild.id)
+ const data = await guildModel.queryGuildSettings(message.guild.id)
+ client.guildSettings.set(message.guild.id, data)
} catch (error) {
- console.log(error);
+ console.log(error)
}
}
}
-};
+}
diff --git a/commands/moderation/removeAllNickname.js b/commands/moderation/removeAllNickname.js
index ac4f29e..2625e13 100644
--- a/commands/moderation/removeAllNickname.js
+++ b/commands/moderation/removeAllNickname.js
@@ -1,38 +1,38 @@
-const { verify } = require("../../utils/utility");
+const { verify } = require('../../utils/utility')
module.exports = {
config: {
- name: "removeAllNickname",
- usage: "removeAllNickname",
+ name: 'removeAllNickname',
+ usage: 'removeAllNickname',
aliases: [],
- description: "Remove nickname of every single member of the server",
+ description: 'Remove nickname of every single member of the server',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- if (!message.member.hasPermission("ADMINISTRATOR")) return;
+ async run (client, message, args) {
+ if (!message.member.hasPermission('ADMINISTRATOR')) return
try {
await message.reply(
- `Are you sure you want to remove all nickname ?`
- );
- const verification = await verify(message.channel, message.author);
- if (!verification) return message.say("Aborted.");
- await message.reply("Fetching members...");
- await message.guild.members.fetch();
- await message.reply("Fetched members! Renaming...");
- let i = 0;
+ 'Are you sure you want to remove all nickname ?'
+ )
+ const verification = await verify(message.channel, message.author)
+ if (!verification) return message.say('Aborted.')
+ await message.reply('Fetching members...')
+ await message.guild.members.fetch()
+ await message.reply('Fetched members! Renaming...')
+ let i = 0
for (const member of message.guild.members.cache.values()) {
try {
- await member.setNickname(" ");
+ await member.setNickname(' ')
} catch {
- i++;
- continue;
+ i++
+ continue
}
}
return message.reply(
`Successfully renamed all but ${i} member`
- );
+ )
} catch (err) {
- return message.reply(`Failed to rename everyone: \`${err.message}\``);
+ return message.reply(`Failed to rename everyone: \`${err.message}\``)
}
}
-};
+}
diff --git a/commands/music/disconnect.js b/commands/music/disconnect.js
index b2babce..8f31926 100644
--- a/commands/music/disconnect.js
+++ b/commands/music/disconnect.js
@@ -1,63 +1,63 @@
-let { stop } = require("../../utils/radio");
+const { stop } = require('../../utils/radio')
module.exports = {
config: {
- name: "disconnect",
- usage: "disconnect",
- description: "Disconnect me from the voiceChannel",
+ name: 'disconnect',
+ usage: 'disconnect',
+ description: 'Disconnect me from the voiceChannel',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let serverQueue = client.queue.get(message.guild.id);
- let normaldj = message.guild.roles.cache.find((x) => x.name === "dj");
- let bigdj = message.guild.roles.cache.find((x) => x.name === "DJ");
- let roleID = bigdj ? bigdj : normaldj;
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
+ const normaldj = message.guild.roles.cache.find((x) => x.name === 'dj')
+ const bigdj = message.guild.roles.cache.find((x) => x.name === 'DJ')
+ const roleID = bigdj || normaldj
if (!roleID) {
return message.channel.send({
embed: {
color: 15158332,
title:
- "Your guild does not have the DJ role, please contact your guild owner/administrator/moderator to create and add the role.",
- },
- });
+ 'Your guild does not have the DJ role, please contact your guild owner/administrator/moderator to create and add the role.'
+ }
+ })
}
if (!serverQueue.voiceChannel) {
return message.channel.send({
embed: {
color: 15158332,
- title: "__***YOU IDIOT***__",
- description: "I AM NOT EVEN IN A VOICE CHANNEL",
+ title: '__***YOU IDIOT***__',
+ description: 'I AM NOT EVEN IN A VOICE CHANNEL',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
+ size: 1024
+ })
+ }
+ }
+ })
}
if (serverQueue.voiceChannel) {
if (message.member.roles.cache.has(roleID.id)) {
if (!serverQueue.radio) {
- serverQueue.queue = [];
- serverQueue.connection.dispatcher.end();
+ serverQueue.queue = []
+ serverQueue.connection.dispatcher.end()
message.channel.send({
embed: {
- title: "Disconnected from voiceChannel",
+ title: 'Disconnected from voiceChannel',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
- } else stop(client, message);
- } else return message.channel.send("Mày định đảo chính hả ???");
+ size: 1024
+ })
+ }
+ }
+ })
+ } else stop(client, message)
+ } else return message.channel.send('Mày định đảo chính hả ???')
}
- },
-};
+ }
+}
diff --git a/commands/music/lyrics.js b/commands/music/lyrics.js
index e3358fb..30965d5 100644
--- a/commands/music/lyrics.js
+++ b/commands/music/lyrics.js
@@ -1,45 +1,45 @@
-let request = require("request");
-let cheerio = require("cheerio");
+const request = require('request')
+const cheerio = require('cheerio')
module.exports = {
config: {
- name: "lyrics",
- usage: "lyrics [song name]",
- description: "Show lyrics for requested song.",
+ name: 'lyrics',
+ usage: 'lyrics [song name]',
+ description: 'Show lyrics for requested song.',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- const query = encodeURIComponent(args.join(" "));
- let msg = await message.channel.send(`Searching. . .`);
- request(`https://some-random-api.ml/lyrics?title=${query}`, async function(
+ async run (client, message, args) {
+ const query = encodeURIComponent(args.join(' '))
+ const msg = await message.channel.send('Searching. . .')
+ request(`https://some-random-api.ml/lyrics?title=${query}`, async function (
error,
response,
body
) {
- if (error) throw error;
+ if (error) throw error
- let data = JSON.parse(body);
+ const data = JSON.parse(body)
if (data.error) {
message.channel.send({
embed: {
color: 15158332,
title: "I can't find that song. Using another engine"
}
- });
- await geniusLyrics();
- return;
+ })
+ await geniusLyrics()
+ return
}
- var output = data.lyrics.split("\n");
- var myfields = [];
- var tmp = 0;
- var sttmp = "";
+ var output = data.lyrics.split('\n')
+ var myfields = []
+ var tmp = 0
+ var sttmp = ''
for (var i = 0; i <= output.length; i++) {
- sttmp += output[i] + " \n ";
- tmp++;
+ sttmp += output[i] + ' \n '
+ tmp++
if (tmp == 15) {
- myfields.push({ name: "\u200B", value: sttmp });
- tmp = 0;
- sttmp = "";
+ myfields.push({ name: '\u200B', value: sttmp })
+ tmp = 0
+ sttmp = ''
}
}
// if (data.lyrics.length >= 2048) {
@@ -50,33 +50,33 @@ module.exports = {
message.channel.send({
embed: {
color: 3447003,
- title: "Lyrics for requested song",
+ title: 'Lyrics for requested song',
url: data.links.genius,
- //description: data.lyrics,
+ // description: data.lyrics,
fields: myfields,
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
- //timestamp: new Date(), useless shit
+ // timestamp: new Date(), useless shit
}
- });
+ })
message.channel.send({
embed: {
color: 3447003,
- title: "Information of requested song",
+ title: 'Information of requested song',
url: data.links.genius,
fields: [
{
- name: "Song name",
+ name: 'Song name',
value: data.title
},
{
- name: "Author",
+ name: 'Author',
value: data.author
}
],
@@ -84,64 +84,65 @@ module.exports = {
url: data.thumbnail.genius
},
footer: {
- text: "Powered by Genius\t\t\t\tCreated by wrose",
+ text: 'Powered by Genius\t\t\t\tCreated by wrose',
icon_url:
- "https://images.genius.com/8ed669cadd956443e29c70361ec4f372.1000x1000x1.png"
+ 'https://images.genius.com/8ed669cadd956443e29c70361ec4f372.1000x1000x1.png'
},
thumbnail: {
url: client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
- });
+ })
+ })
- function geniusLyrics() {
- var replacedString = JSON.stringify(args);
- replacedString = replacedString.replace(/ /g, "%20");
+ function geniusLyrics () {
+ var replacedString = JSON.stringify(args)
+ replacedString = replacedString.replace(/ /g, '%20')
const options = {
- method: "GET",
- url: "https://api.genius.com/search",
+ method: 'GET',
+ url: 'https://api.genius.com/search',
qs: {
q: replacedString,
access_token:
- "ZilEYmeGT3qw_4Sfz3qOCnejUa1Jsbvogq55JoCqNw233YpyAUj779BFdgmGv6Wv"
+ 'ZilEYmeGT3qw_4Sfz3qOCnejUa1Jsbvogq55JoCqNw233YpyAUj779BFdgmGv6Wv'
}
- };
- request(options, function(error, response, body) {
- if (error)
+ }
+ request(options, function (error, response, body) {
+ if (error) {
return message.channel.send({
embed: {
color: 15158332,
- title: "__***Shit***__",
- description: "Something gone wrong"
+ title: '__***Shit***__',
+ description: 'Something gone wrong'
}
- });
- const hits = JSON.parse(body).response.hits;
- request(url, function(error, reponse, body) {
- let $ = cheerio.load(body);
- let lyrics = $("p")
+ })
+ }
+ const hits = JSON.parse(body).response.hits
+ request(url, function (error, reponse, body) {
+ const $ = cheerio.load(body)
+ const lyrics = $('p')
.first()
.eq(0)
.text()
.trim()
- .split("\n");
- var myfields = [];
- var tmp = 0;
- var sttmp = "";
+ .split('\n')
+ var myfields = []
+ var tmp = 0
+ var sttmp = ''
for (var i = 0; i <= lyrics.length; i++) {
- sttmp += lyrics[i] + " \n ";
- tmp++;
+ sttmp += lyrics[i] + ' \n '
+ tmp++
if (tmp == 15) {
myfields.push({
- name: "------------------------------------------------",
+ name: '------------------------------------------------',
value: sttmp
- });
- tmp = 0;
- sttmp = "";
+ })
+ tmp = 0
+ sttmp = ''
}
}
message.channel.send({
@@ -149,9 +150,9 @@ module.exports = {
color: 3447003,
fields: myfields
}
- });
- });
- });
+ })
+ })
+ })
}
}
-};
+}
diff --git a/commands/music/musicMasterRole.js b/commands/music/musicMasterRole.js
index 697b29a..5c52b19 100644
--- a/commands/music/musicMasterRole.js
+++ b/commands/music/musicMasterRole.js
@@ -1,69 +1,69 @@
-const low = require("lowdb");
-const FileSync = require("lowdb/adapters/FileSync");
-const adapter = new FileSync("./data/guildSettings.json");
-const db = low(adapter);
+const low = require('lowdb')
+const FileSync = require('lowdb/adapters/FileSync')
+const adapter = new FileSync('./data/guildSettings.json')
+const db = low(adapter)
module.exports = {
config: {
- name: "musicMasterRole",
- usage: "musicMasterRole [role id]",
- description: "Set the DJ role",
+ name: 'musicMasterRole',
+ usage: 'musicMasterRole [role id]',
+ description: 'Set the DJ role',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let guild = db
- .get("guild")
+ async run (client, message, args) {
+ const guild = db
+ .get('guild')
.find({
id: message.member.guild.id
})
- .value();
+ .value()
if (!guild) {
- db.get("guild")
+ db.get('guild')
.push({
id: message.member.guild.id
})
- .write();
+ .write()
}
if (guild && message.member.guild.roles.cache.find(x => x.id === args[0])) {
- db.get("guild")
+ db.get('guild')
.find({
id: message.member.guild.id
})
.push({
musicMasterRole: args[0]
})
- .write();
+ .write()
message.channel.send({
embed: {
color: 3447003,
title:
message.member.guild.roles.cache.find(x => x.id === args[0]).name +
- " has been choosen as musicMasterRole",
+ ' has been choosen as musicMasterRole',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
} else {
message.channel.send({
embed: {
color: 15158332,
- title: "Cannot find the specific role",
+ title: 'Cannot find the specific role',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
}
}
-};
+}
diff --git a/commands/music/nowPlaying.js b/commands/music/nowPlaying.js
index c38ce37..c976cfc 100644
--- a/commands/music/nowPlaying.js
+++ b/commands/music/nowPlaying.js
@@ -1,84 +1,84 @@
-let Bar = require("../../utils/progressBar");
+const Bar = require('../../utils/progressBar')
module.exports = {
config: {
- name: "nowPlaying",
- usage: "nowPlaying",
- aliases: ["np"],
- description: "Send information of playing song",
+ name: 'nowPlaying',
+ usage: 'nowPlaying',
+ aliases: ['np'],
+ description: 'Send information of playing song',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const serverQueue = client.queue.get(message.guild.id);
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
if (!serverQueue) {
return message.channel.send({
embed: {
color: 15158332,
- title: "I'm not playing anything right now",
- },
- });
+ title: "I'm not playing anything right now"
+ }
+ })
} else {
try {
- let bar = new Bar(
+ const bar = new Bar(
Math.floor((parseInt(serverQueue.dispatcher.streamTime) / 1000)),
serverQueue.queue[0].seconds,
20
- );
- let progress = bar.createBar();
+ )
+ const progress = bar.createBar()
message.channel.send({
embed: {
color: 3447003,
- title: "Now playing",
+ title: 'Now playing',
url: serverQueue.queue[0].url,
fields: [
{
- name: "Song name",
- value: serverQueue.queue[0].title,
+ name: 'Song name',
+ value: serverQueue.queue[0].title
},
{
- name: "Duration",
- value: serverQueue.queue[0].duration,
+ name: 'Duration',
+ value: serverQueue.queue[0].duration
},
{
- name: "Requested by",
- value: serverQueue.queue[0].requester,
+ name: 'Requested by',
+ value: serverQueue.queue[0].requester
},
{
- name: "Current seek",
- value: msToTime() + "\n" + progress,
- },
+ name: 'Current seek',
+ value: msToTime() + '\n' + progress
+ }
],
thumbnail: {
url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
+ size: 1024
+ })
},
image: {
- url: serverQueue.queue[0].thumbnail,
+ url: serverQueue.queue[0].thumbnail
},
footer: {
- text: "Created by wrose",
- },
- },
- });
+ text: 'Created by wrose'
+ }
+ }
+ })
} catch (error) {
- message.channel.send(error.message);
+ message.channel.send(error.message)
}
}
- function msToTime() {
- let duration = serverQueue.dispatcher.streamTime;
- var milliseconds = parseInt((duration % 1000) / 100),
- seconds = Math.floor((duration / 1000) % 60),
- minutes = Math.floor((duration / (1000 * 60)) % 60),
- hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
+ function msToTime () {
+ const duration = serverQueue.dispatcher.streamTime
+ var milliseconds = parseInt((duration % 1000) / 100)
+ var seconds = Math.floor((duration / 1000) % 60)
+ var minutes = Math.floor((duration / (1000 * 60)) % 60)
+ var hours = Math.floor((duration / (1000 * 60 * 60)) % 24)
- hours = hours < 10 ? "0" + hours : hours;
- minutes = minutes < 10 ? "0" + minutes : minutes;
- seconds = seconds < 10 ? "0" + seconds : seconds;
+ hours = hours < 10 ? '0' + hours : hours
+ minutes = minutes < 10 ? '0' + minutes : minutes
+ seconds = seconds < 10 ? '0' + seconds : seconds
- return minutes + ":" + seconds;
+ return minutes + ':' + seconds
}
- },
-};
+ }
+}
diff --git a/commands/music/play.js b/commands/music/play.js
index 5d31427..9b0b8ce 100644
--- a/commands/music/play.js
+++ b/commands/music/play.js
@@ -1,38 +1,37 @@
-const ytcore = require("ytdl-core");
-const dude = require("yt-dude");
-const getVideoId = require("get-video-id");
-let musicDB = require("../../model/musicData");
-let { initQueue, addPlaylistToQueue } = require("../../utils/queue");
-let { sendSongQueue, sendPlaying, emptyQueue } = require("../../utils/message");
-let {
+const ytcore = require('ytdl-core')
+const dude = require('yt-dude')
+const getVideoId = require('get-video-id')
+const musicDB = require('../../model/musicData')
+const { initQueue, addPlaylistToQueue } = require('../../utils/queue')
+const { sendSongQueue, sendPlaying, emptyQueue } = require('../../utils/message')
+const {
sendErrorMail,
updatePresence,
ytValidate,
getSongInfo,
- getvideourl,
-} = require("../../utils/utility");
+ getvideourl
+} = require('../../utils/utility')
-const send = require("gmail-send")({
- user: "minzycrackteam@gmail.com",
- pass: "kjbarjuidzcevgcn",
- to: "sktt1lka@gmail.com",
- subject: "Error on DiscordBot",
- text: "Error happened",
-});
+const send = require('gmail-send')({
+ user: 'minzycrackteam@gmail.com',
+ pass: 'kjbarjuidzcevgcn',
+ to: 'sktt1lka@gmail.com',
+ subject: 'Error on DiscordBot',
+ text: 'Error happened'
+})
module.exports = {
config: {
- name: "play",
- usage: "play [song name]",
- aliases: ["p"],
- description: "Play a song from youtube",
+ name: 'play',
+ usage: 'play [song name]',
+ aliases: ['p'],
+ description: 'Play a song from youtube',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const serverQueue = client.queue.get(message.guild.id);
- const voiceChannel = message.member.voice.channel;
- if (serverQueue && serverQueue.radio === true)
- return message.reply("Occupied somewhere else");
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
+ const voiceChannel = message.member.voice.channel
+ if (serverQueue && serverQueue.radio === true) { return message.reply('Occupied somewhere else') }
if (serverQueue) {
if (
message.member.voice.channel &&
@@ -42,154 +41,154 @@ module.exports = {
embed: {
color: 15158332,
title:
- "I'm now playing in another voiceChannel, please wait or join that voiceChannel",
- //description:
- //"If you are desperate to listen to music, use --wait in your order and i will join you immediately after i finished playing for someone else"
- },
- });
+ "I'm now playing in another voiceChannel, please wait or join that voiceChannel"
+ // description:
+ // "If you are desperate to listen to music, use --wait in your order and i will join you immediately after i finished playing for someone else"
+ }
+ })
}
}
if (!message.member.voice.channel) {
return message.channel.send({
embed: {
color: 15158332,
- description: "You have to be in a voiceChannel to use the command.",
- },
- });
+ description: 'You have to be in a voiceChannel to use the command.'
+ }
+ })
}
try {
- let user = message.mentions.users.first()
+ const user = message.mentions.users.first()
? message.mentions.users.first().id
- : message.author.id;
- if (args[0] !== "--playlist") {
+ : message.author.id
+ if (args[0] !== '--playlist') {
if (ytcore.validateURL(args[0])) {
- addQueue(args[0]);
+ addQueue(args[0])
}
if (!ytcore.validateURL(args[0])) {
- let params = args.join(" ");
- let videoUrl = await getvideourl(params);
- if (videoUrl !== null) addQueue(videoUrl);
- else return message.reply("Please retry after 5 seconds");
+ const params = args.join(' ')
+ const videoUrl = await getvideourl(params)
+ if (videoUrl !== null) addQueue(videoUrl)
+ else return message.reply('Please retry after 5 seconds')
}
}
- if (args[0] === "--playlist" && !serverQueue) {
- let tempQueue = await initQueue(message);
- tempQueue = await addPlaylistToQueue(message, tempQueue, user);
- client.queue.set(message.guild.id, tempQueue);
- play(message.guild.id);
+ if (args[0] === '--playlist' && !serverQueue) {
+ let tempQueue = await initQueue(message)
+ tempQueue = await addPlaylistToQueue(message, tempQueue, user)
+ client.queue.set(message.guild.id, tempQueue)
+ play(message.guild.id)
}
- if (args[0] === "--playlist" && serverQueue) {
- await addPlaylistToQueue(message, serverQueue, user);
+ if (args[0] === '--playlist' && serverQueue) {
+ await addPlaylistToQueue(message, serverQueue, user)
}
- //functions
- async function addQueue(url) {
- let songInfo = await getSongInfo(url);
- let song = {
+ // functions
+ async function addQueue (url) {
+ const songInfo = await getSongInfo(url)
+ const song = {
title: songInfo.title,
url: songInfo.video_url,
thumbnail: getThumbnail(url),
duration: secondsCoverter(songInfo.length_seconds),
seconds: songInfo.length_seconds,
- requester: message.author.tag,
- };
+ requester: message.author.tag
+ }
if (!serverQueue) {
- let tempQueue = await initQueue(message);
- tempQueue.queue.push(song);
- client.queue.set(message.guild.id, tempQueue);
- play(message.guild.id);
+ const tempQueue = await initQueue(message)
+ tempQueue.queue.push(song)
+ client.queue.set(message.guild.id, tempQueue)
+ play(message.guild.id)
} else {
- serverQueue.queue.push(song);
- sendSongQueue(message, client);
+ serverQueue.queue.push(song)
+ sendSongQueue(message, client)
}
}
- async function play(guild) {
- const serverQueue = client.queue.get(guild);
+ async function play (guild) {
+ const serverQueue = client.queue.get(guild)
if (!serverQueue.queue[0]) {
- serverQueue.isPlaying = false;
- updatePresence(message, serverQueue);
- serverQueue.voiceChannel.leave();
- emptyQueue(message, client);
- client.queue.delete(guild);
+ serverQueue.isPlaying = false
+ updatePresence(message, serverQueue)
+ serverQueue.voiceChannel.leave()
+ emptyQueue(message, client)
+ client.queue.delete(guild)
} else {
- sendPlaying(message, client);
+ sendPlaying(message, client)
serverQueue.dispatcher = serverQueue.connection
.play(
ytcore(serverQueue.queue[0].url, {
- filter: "audioonly",
- quality: "highestaudio",
+ filter: 'audioonly',
+ quality: 'highestaudio',
highWaterMark: 1 << 25,
encoderArgs: [
- "-af",
- `equalizer=f=40:width_type=h:width=50:g=50`,
- ],
+ '-af',
+ 'equalizer=f=40:width_type=h:width=50:g=50'
+ ]
})
)
- .on("start", () => {
- serverQueue.isPlaying = true;
- updatePresence(message, serverQueue);
- addTopSong(serverQueue.queue[0].title, message.guild.id);
+ .on('start', () => {
+ serverQueue.isPlaying = true
+ updatePresence(message, serverQueue)
+ addTopSong(serverQueue.queue[0].title, message.guild.id)
})
- .on("finish", () => {
- serverQueue.queue.shift();
- play(message.guild.id);
+ .on('finish', () => {
+ serverQueue.queue.shift()
+ play(message.guild.id)
})
- .on("volumeChange", (oldVolume, newVolume) => {
+ .on('volumeChange', (oldVolume, newVolume) => {
message.channel.send({
embed: {
title: `Volume changed from ${oldVolume} to ${newVolume}.`,
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
+ size: 1024
+ })
+ }
+ }
+ })
})
- .on("end", () => {
- serverQueue.queue.shift();
+ .on('end', () => {
+ serverQueue.queue.shift()
+ })
+ .on('error', (error) => {
+ console.log(error)
+ sendErrorMail(error)
})
- .on("error", (error) => {
- console.log(error);
- sendErrorMail(error);
- });
}
}
- function getThumbnail(url) {
- let ids = getVideoId(url);
- return `http://img.youtube.com/vi/${ids.id}/maxresdefault.jpg`;
+ function getThumbnail (url) {
+ const ids = getVideoId(url)
+ return `http://img.youtube.com/vi/${ids.id}/maxresdefault.jpg`
}
- function addTopSong(title) {
- musicDB.updateCount(title, message.guild.id);
+ function addTopSong (title) {
+ musicDB.updateCount(title, message.guild.id)
}
- function secondsCoverter(second) {
- var timestamp = second;
+ function secondsCoverter (second) {
+ var timestamp = second
// 2
- var hours = Math.floor(timestamp / 60 / 60);
+ var hours = Math.floor(timestamp / 60 / 60)
// 37
- var minutes = Math.floor(timestamp / 60) - hours * 60;
+ var minutes = Math.floor(timestamp / 60) - hours * 60
// 42
- var seconds = timestamp % 60;
+ var seconds = timestamp % 60
if (hours > 0) {
- return hours + ":" + minutes + ":" + seconds;
- } else return minutes + ":" + seconds;
+ return hours + ':' + minutes + ':' + seconds
+ } else return minutes + ':' + seconds
}
} catch (error) {
- console.log(error);
+ console.log(error)
message.channel.send({
embed: {
color: 15158332,
title: error.name,
- description: error.message,
- },
- });
- sendErrorMail(error);
+ description: error.message
+ }
+ })
+ sendErrorMail(error)
}
- },
-};
+ }
+}
diff --git a/commands/music/playlist.js b/commands/music/playlist.js
index a557de4..d6f5aa3 100644
--- a/commands/music/playlist.js
+++ b/commands/music/playlist.js
@@ -1,43 +1,42 @@
-let ytdl = require("ytdl-core");
-let dude = require("yt-dude");
-const plModel = require("../../model/playlist.model");
-let {
+const ytdl = require('ytdl-core')
+const dude = require('yt-dude')
+const plModel = require('../../model/playlist.model')
+const {
getSongInfo,
getThumbnail,
- secondsCoverter,
-} = require("../../utils/utility");
-const Pagination = require("discord-paginationembed");
-const { redMessage } = require("../../utils/message");
+ secondsCoverter
+} = require('../../utils/utility')
+const Pagination = require('discord-paginationembed')
+const { redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "playlist",
- description: "Add a song to a specific playlist",
- usage: "playlist [playlist] [url]",
+ name: 'playlist',
+ description: 'Add a song to a specific playlist',
+ usage: 'playlist [playlist] [url]',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let messageFlags = args[0];
- if (messageFlags === "--add") {
+ async run (client, message, args) {
+ const messageFlags = args[0]
+ if (messageFlags === '--add') {
if (ytdl.validateURL(args[1])) {
- addPlaylist(args[1]);
+ addPlaylist(args[1])
} else if (!ytdl.validateURL(args[1])) {
- args.splice(args.indexOf("--add"), 1);
- let query = await dude.search(args.join(" "));
- let videoUrl = "https://www.youtube.com/watch?v=" + query[0].videoId;
- addPlaylist(videoUrl);
+ args.splice(args.indexOf('--add'), 1)
+ const query = await dude.search(args.join(' '))
+ const videoUrl = 'https://www.youtube.com/watch?v=' + query[0].videoId
+ addPlaylist(videoUrl)
}
}
- if (messageFlags === "--show") {
- let user = message.mentions.users.first()
+ if (messageFlags === '--show') {
+ const user = message.mentions.users.first()
? message.mentions.users.first().id
- : message.author.id;
- let embeds = [];
- let songArr = await plModel.getPlaylist(user);
- if (songArr.length === 0)
- return redMessage(message, "You don't have any song on your playlist");
+ : message.author.id
+ const embeds = []
+ const songArr = await plModel.getPlaylist(user)
+ if (songArr.length === 0) { return redMessage(message, "You don't have any song on your playlist") }
for (const song of songArr) {
- await embeds.push(song.songName);
+ await embeds.push(song.songName)
}
try {
const playlist = new Pagination.FieldsEmbed()
@@ -45,83 +44,83 @@ module.exports = {
.setAuthorizedUsers([])
.setChannel(message.channel)
.setPageIndicator(true)
- .formatField("Name", (i) => i + "\n")
+ .formatField('Name', (i) => i + '\n')
.setDeleteOnTimeout(true)
.setElementsPerPage(10)
- .setEmojisFunctionAfterNavigation(true);
+ .setEmojisFunctionAfterNavigation(true)
playlist.embed
.setThumbnail(
- client.user.avatarURL({ format: "png", dynamic: true, size: 1024 })
+ client.user.avatarURL({ format: 'png', dynamic: true, size: 1024 })
)
- .setColor("#0390fc")
- .setFooter("Created by wrose");
- await playlist.build();
+ .setColor('#0390fc')
+ .setFooter('Created by wrose')
+ await playlist.build()
} catch (error) {
- message.channel.send(error.message);
+ message.channel.send(error.message)
}
}
- if (messageFlags === "--delete") {
- args.splice(args.indexOf(messageFlags), 1);
- let deletingSong = args.join(" ");
+ if (messageFlags === '--delete') {
+ args.splice(args.indexOf(messageFlags), 1)
+ const deletingSong = args.join(' ')
try {
- let a = await plModel.deleteSong(deletingSong, message.author.id);
+ const a = await plModel.deleteSong(deletingSong, message.author.id)
message.channel.send({
embed: {
color: 15158332,
- title: "Delete one song from " + message.author.tag + " playlist",
+ title: 'Delete one song from ' + message.author.tag + ' playlist',
fields: [
{
- name: "Song name",
- value: a.songName,
+ name: 'Song name',
+ value: a.songName
},
{
- name: "Song URL",
- value: a.link,
- },
- ],
- },
- });
+ name: 'Song URL',
+ value: a.link
+ }
+ ]
+ }
+ })
} catch (error) {
- console.log("error", error);
+ console.log('error', error)
}
}
- if (messageFlags === "--destroy") {
- let id = message.author.id;
+ if (messageFlags === '--destroy') {
+ const id = message.author.id
try {
- let query = await plModel.destroyPlaylist(id);
- console.log(query);
- message.channel.send("Deleted playlist for " + message.author.tag);
+ const query = await plModel.destroyPlaylist(id)
+ console.log(query)
+ message.channel.send('Deleted playlist for ' + message.author.tag)
} catch (error) {
- redMessage(message, error.title, error.message);
+ redMessage(message, error.title, error.message)
}
}
- async function addPlaylist(url) {
+ async function addPlaylist (url) {
try {
- let a = await plModel.addPlaylist(url, message.author.id);
- let songInfo = await getSongInfo(url);
+ const a = await plModel.addPlaylist(url, message.author.id)
+ const songInfo = await getSongInfo(url)
message.channel.send({
embed: {
color: 3447003,
- title: "Added one song playlist",
+ title: 'Added one song playlist',
fields: [
{
- name: "Song name",
- value: songInfo.title,
+ name: 'Song name',
+ value: songInfo.title
},
{
- name: "Song URL",
- value: songInfo.video_url,
+ name: 'Song URL',
+ value: songInfo.video_url
},
{
- name: "Playlist author",
- value: message.author.tag,
- },
- ],
- },
- });
+ name: 'Playlist author',
+ value: message.author.tag
+ }
+ ]
+ }
+ })
} catch (error) {
- console.log(error);
+ console.log(error)
}
}
- },
-};
+ }
+}
diff --git a/commands/music/queue.js b/commands/music/queue.js
index 66d01ac..7f4b730 100644
--- a/commands/music/queue.js
+++ b/commands/music/queue.js
@@ -1,35 +1,35 @@
-let Discord = require("discord.js");
+const Discord = require('discord.js')
module.exports = {
config: {
- name: "queue",
- usage: "queue",
- aliases: ["q"],
- description: "Show current queue songs.",
+ name: 'queue',
+ usage: 'queue',
+ aliases: ['q'],
+ description: 'Show current queue songs.',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- const serverQueue = client.queue.get(message.guild.id);
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
if (!serverQueue) {
message.channel.send({
embed: {
color: 15158332,
- title: "No songs in queue"
+ title: 'No songs in queue'
}
- });
+ })
} else {
- let songs = serverQueue.queue;
- let embed = new Discord.MessageEmbed()
- .setColor("#0390fc")
- .setTitle("Songs in queue")
+ const songs = serverQueue.queue
+ const embed = new Discord.MessageEmbed()
+ .setColor('#0390fc')
+ .setTitle('Songs in queue')
.setThumbnail(
- client.user.avatarURL({ format: "png", dynamic: true, size: 1024 })
- );
+ client.user.avatarURL({ format: 'png', dynamic: true, size: 1024 })
+ )
songs.forEach(entry => {
- let requestedBy = "Requested " + entry.requester;
- embed.addField(entry.title, requestedBy);
- });
- message.channel.send(embed);
+ const requestedBy = 'Requested ' + entry.requester
+ embed.addField(entry.title, requestedBy)
+ })
+ message.channel.send(embed)
}
}
-};
+}
diff --git a/commands/music/radio.js b/commands/music/radio.js
index 9938c80..2ec1436 100644
--- a/commands/music/radio.js
+++ b/commands/music/radio.js
@@ -1,43 +1,42 @@
-const stations = require("../../data/stations.json");
-const { play, stop, showStations } = require("../../utils/radio");
-const { initQueue } = require("../../utils/queue");
-const { sendErrorMail } = require("../../utils/utility");
+const stations = require('../../data/stations.json')
+const { play, stop, showStations } = require('../../utils/radio')
+const { initQueue } = require('../../utils/queue')
+const { sendErrorMail } = require('../../utils/utility')
module.exports = {
config: {
- name: "radio",
- usage: "[--play] [--stations] [--stop]",
+ name: 'radio',
+ usage: '[--play] [--stations] [--stop]',
aliases: [],
- description: "Start listening to a radio station",
+ description: 'Start listening to a radio station',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const serverQueue = client.queue.get(message.guild.id);
- if (serverQueue && !serverQueue.radio)
- return message.reply("Occupied somewhere else.");
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
+ if (serverQueue && !serverQueue.radio) { return message.reply('Occupied somewhere else.') }
try {
- if (args[0] === "--play") {
- let tempQueue = await initQueue(message);
- tempQueue.radio = true;
- args.splice(args.indexOf("--play"), 1);
- let name = args.join(" ");
- const station = stations[name];
+ if (args[0] === '--play') {
+ const tempQueue = await initQueue(message)
+ tempQueue.radio = true
+ args.splice(args.indexOf('--play'), 1)
+ const name = args.join(' ')
+ const station = stations[name]
if (!station) {
- await tempQueue.voiceChannel.leave();
- client.queue.delete(message.guild.id);
- return message.reply("No such station found");
+ await tempQueue.voiceChannel.leave()
+ client.queue.delete(message.guild.id)
+ return message.reply('No such station found')
} else {
- tempQueue.queue.push(station);
- client.queue.set(message.guild.id, tempQueue);
- play(client, message, station);
+ tempQueue.queue.push(station)
+ client.queue.set(message.guild.id, tempQueue)
+ play(client, message, station)
}
- } else if (args[0] === "--stations") {
- showStations(client, message);
- } else if (args[0] === "--stop") {
- stop(client, message);
+ } else if (args[0] === '--stations') {
+ showStations(client, message)
+ } else if (args[0] === '--stop') {
+ stop(client, message)
}
} catch (error) {
- sendErrorMail(error);
+ sendErrorMail(error)
}
- },
-};
+ }
+}
diff --git a/commands/music/repeat.js b/commands/music/repeat.js
index 8d7733b..8f953f5 100644
--- a/commands/music/repeat.js
+++ b/commands/music/repeat.js
@@ -1,28 +1,28 @@
module.exports = {
config: {
- name: "repeat",
- usage: "repeat",
- description: "Set a playing song on repeat",
+ name: 'repeat',
+ usage: 'repeat',
+ description: 'Set a playing song on repeat',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let serverQueue = client.queue.get(message.guild.id);
- serverQueue.queue.unshift(serverQueue.queue[0]);
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
+ serverQueue.queue.unshift(serverQueue.queue[0])
message.channel.send({
embed: {
color: 3066993,
- title: "Repeating one song",
- description: "Song name " + serverQueue.queue[0].title,
+ title: 'Repeating one song',
+ description: 'Song name ' + serverQueue.queue[0].title,
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
}
-};
+}
diff --git a/commands/music/saveQueue.js b/commands/music/saveQueue.js
index 13d6da5..bf90631 100644
--- a/commands/music/saveQueue.js
+++ b/commands/music/saveQueue.js
@@ -1,48 +1,48 @@
-const { addPlaylist } = require("../../model/playlist.model");
-let { getSongInfo } = require("../../utils/utility");
+const { addPlaylist } = require('../../model/playlist.model')
+const { getSongInfo } = require('../../utils/utility')
module.exports = {
config: {
- name: "saveQueue",
- usage: "saveQueue [--arguements]",
+ name: 'saveQueue',
+ usage: 'saveQueue [--arguements]',
aliases: [],
description:
- "Create playlist from running queue. To modify the playlist use playlist command",
+ 'Create playlist from running queue. To modify the playlist use playlist command',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const serverQueue = await client.queue.get(message.guild.id);
- if (!serverQueue) return message.reply("There is no running queue.");
+ async run (client, message, args) {
+ const serverQueue = await client.queue.get(message.guild.id)
+ if (!serverQueue) return message.reply('There is no running queue.')
for (let i = 0; i < serverQueue.queue.length; i++) {
- await add(serverQueue.queue[i].url, message.author.id);
+ await add(serverQueue.queue[i].url, message.author.id)
}
- async function add(url) {
+ async function add (url) {
try {
- let a = await addPlaylist(url, message.author.id);
- let songInfo = await getSongInfo(url);
+ const a = await addPlaylist(url, message.author.id)
+ const songInfo = await getSongInfo(url)
message.channel.send({
embed: {
color: 3447003,
- title: "Added one song to your playlist",
+ title: 'Added one song to your playlist',
fields: [
{
- name: "Song name",
- value: songInfo.title,
+ name: 'Song name',
+ value: songInfo.title
},
{
- name: "Song URL",
- value: songInfo.video_url,
+ name: 'Song URL',
+ value: songInfo.video_url
},
{
- name: "Playlist author",
- value: message.author.tag,
- },
- ],
- },
- });
+ name: 'Playlist author',
+ value: message.author.tag
+ }
+ ]
+ }
+ })
} catch (error) {
- console.log(error);
+ console.log(error)
}
}
- },
-};
+ }
+}
diff --git a/commands/music/search.js b/commands/music/search.js
index e923ef9..e3f2080 100644
--- a/commands/music/search.js
+++ b/commands/music/search.js
@@ -1,14 +1,14 @@
-let guildSettings = require("../../model/guildSettingsModel");
+const guildSettings = require('../../model/guildSettingsModel')
module.exports = {
config: {
- name: "search",
- usage: "search [args]",
- description: "Honestly this is my dev test command",
+ name: 'search',
+ usage: 'search [args]',
+ description: 'Honestly this is my dev test command',
ownerOnly: true,
enabled: true
},
- async run(client, message, args) {
- let data = await guildSettings.queryGuildSettings(message.member.guild.id);
- console.log(typeof data.ignoredChannels);
+ async run (client, message, args) {
+ const data = await guildSettings.queryGuildSettings(message.member.guild.id)
+ console.log(typeof data.ignoredChannels)
}
-};
+}
diff --git a/commands/music/seek.js b/commands/music/seek.js
index c779294..d0c21f7 100644
--- a/commands/music/seek.js
+++ b/commands/music/seek.js
@@ -1,24 +1,23 @@
module.exports = {
config: {
- name: "seek",
- usage: "seek [time]",
- description: "Resume song at specific time",
+ name: 'seek',
+ usage: 'seek [time]',
+ description: 'Resume song at specific time',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- const serverQueue = client.queue.get(message.guild.id);
- console.log(message.member.voice.channel.id, serverQueue.voiceChannel.id);
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
+ console.log(message.member.voice.channel.id, serverQueue.voiceChannel.id)
- if (!message.member.voice.channel)
- return message.channel.send("Join voice channel first");
- if (!serverQueue) return message.channel.send("No songs to seek");
+ if (!message.member.voice.channel) { return message.channel.send('Join voice channel first') }
+ if (!serverQueue) return message.channel.send('No songs to seek')
if (serverQueue.voiceChannel.id !== message.member.voice.channel.id) {
message.chanel.send(
`You must in **${serverQueue.voiceChannel.name}** to seek the song`
- );
+ )
} else {
- serverQueue.dispatcher.end(`seek 02:38`);
+ serverQueue.dispatcher.end('seek 02:38')
}
}
-};
+}
diff --git a/commands/music/setMusicChannel.js b/commands/music/setMusicChannel.js
index 97d0a8f..d0114ee 100644
--- a/commands/music/setMusicChannel.js
+++ b/commands/music/setMusicChannel.js
@@ -1,66 +1,66 @@
-let guildSettings = require("../../model/guildSettingsModel");
+const guildSettings = require('../../model/guildSettingsModel')
module.exports = {
config: {
- name: "setMusicChannel",
- usage: "setMusicChannel [textChannelID]",
- description: "Set a textChannel as a music command receiver",
+ name: 'setMusicChannel',
+ usage: 'setMusicChannel [textChannelID]',
+ description: 'Set a textChannel as a music command receiver',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (!message.member.voice.channel) {
message.channel.send({
embed: {
color: 15158332,
- title: "You have to be in a voiceChannel to setup the musicChannel"
+ title: 'You have to be in a voiceChannel to setup the musicChannel'
}
- });
- return;
+ })
+ return
}
if (message.member.guild.channels.cache.find(x => x.id === args[0])) {
- let data = {
+ const data = {
guildID: message.member.guild.id,
musicTextChannel: args[0],
musicVoiceChannel: message.member.voice.channelID
- };
- guildSettings.updateMusicChannel(data);
- client.guildSettings.set(data.guildID, data);
+ }
+ guildSettings.updateMusicChannel(data)
+ client.guildSettings.set(data.guildID, data)
message.channel.send({
embed: {
color: 15158332,
title:
message.member.guild.channels.cache.find(x => x.id === args[0])
.name +
- " and " +
+ ' and ' +
message.member.guild.channels.cache.find(
x => x.id === message.member.voice.channelID
).name +
- " are now the text and voice channel for music",
+ ' are now the text and voice channel for music',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
} else {
message.channel.send({
embed: {
color: 15158332,
- title: "Cannot find the specific channel",
+ title: 'Cannot find the specific channel',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
}
}
-};
+}
diff --git a/commands/music/shift.js b/commands/music/shift.js
index e977ee2..cd34e9b 100644
--- a/commands/music/shift.js
+++ b/commands/music/shift.js
@@ -1,26 +1,24 @@
-const { redMessage } = require("../../utils/message");
+const { redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "shift",
- usage: "shift",
- aliases: ["remove"],
- description: "",
+ name: 'shift',
+ usage: 'shift',
+ aliases: ['remove'],
+ description: '',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const serverQueue = client.queue.get(message.guild.id);
- if (!serverQueue)
- return redMessage(message, "I'm not playing anothing right now");
- let choice = args[0];
- if (!choice) return redMessage(message, "Please give me index of the song");
- if (choice == "1")
- return redMessage(message, "Can\t remove first song of the queue");
- let songArr = serverQueue.queue;
- await songArr.splice(choice - 1, 1);
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
+ if (!serverQueue) { return redMessage(message, "I'm not playing anothing right now") }
+ const choice = args[0]
+ if (!choice) return redMessage(message, 'Please give me index of the song')
+ if (choice == '1') { return redMessage(message, 'Can\t remove first song of the queue') }
+ const songArr = serverQueue.queue
+ await songArr.splice(choice - 1, 1)
try {
} catch (error) {
- redMessage(message, error.title, error.message);
+ redMessage(message, error.title, error.message)
}
- },
-};
+ }
+}
diff --git a/commands/music/shuffle.js b/commands/music/shuffle.js
index f0dbde7..b25e402 100644
--- a/commands/music/shuffle.js
+++ b/commands/music/shuffle.js
@@ -1,22 +1,22 @@
-let { emptyQueue } = require("../../utils/message");
-let { shuffleArray } = require("../../utils/utility");
+const { emptyQueue } = require('../../utils/message')
+const { shuffleArray } = require('../../utils/utility')
module.exports = {
config: {
- name: "shuffle",
- usage: "shuffle",
+ name: 'shuffle',
+ usage: 'shuffle',
aliases: [],
- description: "Shuffle current music queue",
+ description: 'Shuffle current music queue',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let normaldj = message.guild.roles.cache.find((x) => x.name === "dj");
- let bigdj = message.guild.roles.cache.find((x) => x.name === "DJ");
- let roleID = bigdj ? bigdj : normaldj;
- const serverQueue = client.queue.get(message.guild.id);
+ async run (client, message, args) {
+ const normaldj = message.guild.roles.cache.find((x) => x.name === 'dj')
+ const bigdj = message.guild.roles.cache.find((x) => x.name === 'DJ')
+ const roleID = bigdj || normaldj
+ const serverQueue = client.queue.get(message.guild.id)
if (!serverQueue) {
- console.log(serverQueue);
- return emptyQueue(message);
+ console.log(serverQueue)
+ return emptyQueue(message)
}
if (message.member.roles.cache.has(roleID.id)) {
if (message.member.voice.channel != serverQueue.voiceChannel) {
@@ -24,31 +24,32 @@ module.exports = {
return message.channel.send({
embed: {
title:
- "You have to be in the same channel with the me to use the command",
+ 'You have to be in the same channel with the me to use the command',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
+ size: 1024
+ })
+ }
+ }
+ })
} else {
- let queue = serverQueue.queue;
- let temp = queue[0];
- queue.shift();
- queue = shuffleArray(queue);
- queue.unshift(temp);
- message.channel.send("Queue shuffled");
+ let queue = serverQueue.queue
+ const temp = queue[0]
+ queue.shift()
+ queue = shuffleArray(queue)
+ queue.unshift(temp)
+ message.channel.send('Queue shuffled')
}
- } else
+ } else {
return message.channel.send({
embed: {
color: 15158332,
- title: "You do not have the DJ role.",
- },
- });
- },
-};
+ title: 'You do not have the DJ role.'
+ }
+ })
+ }
+ }
+}
diff --git a/commands/music/skip.js b/commands/music/skip.js
index 38de258..3c15674 100644
--- a/commands/music/skip.js
+++ b/commands/music/skip.js
@@ -1,53 +1,54 @@
-let { emptyQueue } = require("../../utils/message");
+const { emptyQueue } = require('../../utils/message')
module.exports = {
config: {
- name: "skip",
- usage: "skip",
- description: "Skip a playing song.",
+ name: 'skip',
+ usage: 'skip',
+ description: 'Skip a playing song.',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let serverQueue = client.queue.get(message.guild.id);
- let normaldj = message.guild.roles.cache.find((x) => x.name === "dj");
- let bigdj = message.guild.roles.cache.find((x) => x.name === "DJ");
- let roleID = bigdj ? bigdj : normaldj;
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
+ const normaldj = message.guild.roles.cache.find((x) => x.name === 'dj')
+ const bigdj = message.guild.roles.cache.find((x) => x.name === 'DJ')
+ const roleID = bigdj || normaldj
if (!roleID) {
return message.channel.send({
embed: {
color: 15158332,
title:
- "Your guild does not have the DJ role, please contact your guild owner/administrator/moderator to create and add the role.",
- },
- });
+ 'Your guild does not have the DJ role, please contact your guild owner/administrator/moderator to create and add the role.'
+ }
+ })
}
- if (!serverQueue) return emptyQueue(message);
- if(serverQueue.radio) return message.reply("Playing radio stream")
+ if (!serverQueue) return emptyQueue(message)
+ if (serverQueue.radio) return message.reply('Playing radio stream')
if (message.member.roles.cache.has(roleID.id)) {
if (message.member.voice.channel != serverQueue.voiceChannel) {
// undefined
return message.channel.send({
embed: {
title:
- "You have to be in the same channel with the me to use the command",
+ 'You have to be in the same channel with the me to use the command',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
- } else serverQueue.connection.dispatcher.end();
- } else
+ size: 1024
+ })
+ }
+ }
+ })
+ } else serverQueue.connection.dispatcher.end()
+ } else {
return message.channel.send({
embed: {
color: 15158332,
- title: "You do not have the DJ role.",
- },
- });
- },
-};
+ title: 'You do not have the DJ role.'
+ }
+ })
+ }
+ }
+}
diff --git a/commands/music/summon.js b/commands/music/summon.js
index 57f3734..6c151a3 100644
--- a/commands/music/summon.js
+++ b/commands/music/summon.js
@@ -1,28 +1,28 @@
module.exports = {
config: {
- name: "summon",
- usage: "summon",
+ name: 'summon',
+ usage: 'summon',
description: "It's like ShaZam but summon",
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- const serverQueue = client.queue.get(message.guild.id);
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
if (!message.member.voice.channel) {
return message.channel.send({
embed: {
color: 15158332,
- title: "__***N I G G E R***__ join a voice channel first",
+ title: '__***N I G G E R***__ join a voice channel first',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
}
if (serverQueue.isPlaying === true) {
return message.channel.send({
@@ -33,17 +33,17 @@ module.exports = {
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
}
if (serverQueue.isPlaying === false && !serverQueue.voiceChannel) {
- serverQueue.voiceChannel = message.member.voice.channel;
- serverQueue.connection = await message.member.voice.channel.join();
+ serverQueue.voiceChannel = message.member.voice.channel
+ serverQueue.connection = await message.member.voice.channel.join()
}
}
-};
+}
diff --git a/commands/music/volume.js b/commands/music/volume.js
index 851f1ad..dcc45c5 100644
--- a/commands/music/volume.js
+++ b/commands/music/volume.js
@@ -1,31 +1,31 @@
module.exports = {
config: {
- name: "volume",
- usage: "volume [0-100]",
- description: "Adjust the song volume",
+ name: 'volume',
+ usage: 'volume [0-100]',
+ description: 'Adjust the song volume',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- const serverQueue = client.queue.get(message.guild.id);
+ async run (client, message, args) {
+ const serverQueue = client.queue.get(message.guild.id)
if (args[0] < 0 && args[0] > 100 && !Number.isInteger(args[0])) {
return message.channel.send({
embed: {
color: 15158332,
title:
- "Wrong usage, please read the command usage using __.help volume__",
+ 'Wrong usage, please read the command usage using __.help volume__',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
size: 1024
})
}
}
- });
+ })
}
- let volume = args[0] / 100;
- serverQueue.dispatcher.setVolume(volume);
+ const volume = args[0] / 100
+ serverQueue.dispatcher.setVolume(volume)
}
-};
+}
diff --git a/commands/nsfw/neko.js b/commands/nsfw/neko.js
index ea2d4ce..1a087f8 100644
--- a/commands/nsfw/neko.js
+++ b/commands/nsfw/neko.js
@@ -1,19 +1,19 @@
-let neko = require("nekos.life");
-let owo = new neko();
-const { blueMessage, redMessage } = require("../../utils/message");
+const neko = require('nekos.life')
+const owo = new neko()
+const { blueMessage, redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "neko",
- usage: "neko",
+ name: 'neko',
+ usage: 'neko',
aliases: [],
- description: "Show random nsfw neko image",
+ description: 'Show random nsfw neko image',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- if(!message.channel.nsfw) return redMessage(message, 'Error', 'This channel is not a nsfw channel.');
- let img = (await owo.nsfw.nekoGif());
- if (!img) return redMessage(message, "Something happened", ":sad:");
+ async run (client, message, args) {
+ if (!message.channel.nsfw) return redMessage(message, 'Error', 'This channel is not a nsfw channel.')
+ const img = (await owo.nsfw.nekoGif())
+ if (!img) return redMessage(message, 'Something happened', ':sad:')
message.channel.send(img.url)
- },
-};
+ }
+}
diff --git a/commands/owner/away.js b/commands/owner/away.js
index 431f021..eda94e5 100644
--- a/commands/owner/away.js
+++ b/commands/owner/away.js
@@ -1,18 +1,18 @@
-let Discord = require("discord.js");
+const Discord = require('discord.js')
module.exports = {
config: {
- name: "away",
- usage: "away",
+ name: 'away',
+ usage: 'away',
description:
- "Set away status and send message to anyone who mention my owner",
+ 'Set away status and send message to anyone who mention my owner',
ownerOnly: true,
enabled: true
},
- async run(client, message, args) {
- client.awayuser = new Discord.Collection();
- client.awayuser.set(message.member.user.username, message.member);
- if (args[0] === "-remove") {
- client.awayuser.delete(message.member.user.username);
+ async run (client, message, args) {
+ client.awayuser = new Discord.Collection()
+ client.awayuser.set(message.member.user.username, message.member)
+ if (args[0] === '-remove') {
+ client.awayuser.delete(message.member.user.username)
}
}
-};
+}
diff --git a/commands/owner/reloadDatabase.js b/commands/owner/reloadDatabase.js
index 597a06a..1222d46 100644
--- a/commands/owner/reloadDatabase.js
+++ b/commands/owner/reloadDatabase.js
@@ -1,23 +1,23 @@
-const guildSettings = require("../../model/guildSettingsModel");
+const guildSettings = require('../../model/guildSettingsModel')
module.exports = {
config: {
- name: "reloadDatabase",
- usage: "reloadDatabase",
+ name: 'reloadDatabase',
+ usage: 'reloadDatabase',
description:
- "Reload the whole database, this will overwrite the current database",
+ 'Reload the whole database, this will overwrite the current database',
ownerOnly: true,
enabled: true
},
- async run(client, message, args) {
- if (message.author.id !== "155622262660268033") return;
- const guilds = client.guilds.cache;
-
+ async run (client, message, args) {
+ if (message.author.id !== '155622262660268033') return
+ const guilds = client.guilds.cache
+
client.guilds.cache.map(async guild => {
- let data = {
+ const data = {
name: guild.name,
id: guild.id
- };
- await guildSettings.addNewGuild(data);
- });
+ }
+ await guildSettings.addNewGuild(data)
+ })
}
-};
+}
diff --git a/commands/owner/restart.js b/commands/owner/restart.js
index 239d2b2..a5f01f4 100644
--- a/commands/owner/restart.js
+++ b/commands/owner/restart.js
@@ -1,24 +1,24 @@
-let util = require("../../utils/utility");
+const util = require('../../utils/utility')
module.exports = {
config: {
- name: "restart",
- usage: "restart",
- aliases: ["rt"],
- description: "Restart the bot",
+ name: 'restart',
+ usage: 'restart',
+ aliases: ['rt'],
+ description: 'Restart the bot',
ownerOnly: true,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const { exec } = require("child_process");
+ async run (client, message, args) {
+ const { exec } = require('child_process')
try {
exec(`pm2 restart ${process.env.pm2Name}`, async (err, out, stderr) => {
if (err) {
- console.log(err);
+ console.log(err)
}
- });
- return message.channel.send("Restart success");
+ })
+ return message.channel.send('Restart success')
} catch (e) {
- return util.sendError(message, e);
+ return util.sendError(message, e)
}
- },
-};
+ }
+}
diff --git a/commands/owner/setAvatar.js b/commands/owner/setAvatar.js
index 49c7b8d..99bc8a8 100644
--- a/commands/owner/setAvatar.js
+++ b/commands/owner/setAvatar.js
@@ -1,27 +1,27 @@
-const { redMessage } = require("../../utils/message");
+const { redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "setAvatar",
- usage: "setAvatar",
+ name: 'setAvatar',
+ usage: 'setAvatar',
aliases: [],
- description: "Set bot avatar",
+ description: 'Set bot avatar',
ownerOnly: true,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (message.deletable) {
- message.delete();
+ message.delete()
}
if (!args || args.length < 1) {
return redMessage(
message,
- "Please provide me with a valid link to set my avatar."
- );
+ 'Please provide me with a valid link to set my avatar.'
+ )
}
- client.user.setAvatar(args.join(" "));
+ client.user.setAvatar(args.join(' '))
message.channel
- .send("Profile photo has been changed!")
- .then((m) => m.delete({ timeout: 5000 }));
- },
-};
+ .send('Profile photo has been changed!')
+ .then((m) => m.delete({ timeout: 5000 }))
+ }
+}
diff --git a/commands/owner/setStatus.js b/commands/owner/setStatus.js
index ec531b5..b8a3014 100644
--- a/commands/owner/setStatus.js
+++ b/commands/owner/setStatus.js
@@ -1,43 +1,43 @@
-const { redMessage } = require("../../utils/message");
+const { redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "setStatus",
- usage: "setStatus",
+ name: 'setStatus',
+ usage: 'setStatus',
aliases: [],
- description: "Set bot status",
+ description: 'Set bot status',
ownerOnly: true,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (message.deletable) {
- message.delete();
+ message.delete()
}
- const status = args[0];
+ const status = args[0]
if (!status) {
return redMessage(
message,
- "Please input one of the following: `online`, `idle`, `dnd` or `invisible` and try again."
- );
+ 'Please input one of the following: `online`, `idle`, `dnd` or `invisible` and try again.'
+ )
}
- const statusType = args[0].toLowerCase();
+ const statusType = args[0].toLowerCase()
if (
- statusType === "online" ||
- statusType === "idle" ||
- statusType === "dnd" ||
- statusType === "invisible"
+ statusType === 'online' ||
+ statusType === 'idle' ||
+ statusType === 'dnd' ||
+ statusType === 'invisible'
) {
- client.user.setStatus(status);
+ client.user.setStatus(status)
message.channel
.send(
`Status successfully changed to **${statusType}**.\nPlease note that initially changing status may take up to a minute or two.`
)
- .then((m) => m.delete({ timeout: 10000 }));
+ .then((m) => m.delete({ timeout: 10000 }))
} else {
- return redMessage(message, `"${statusType}" is not a valid status type.`);
+ return redMessage(message, `"${statusType}" is not a valid status type.`)
}
- },
-};
+ }
+}
diff --git a/commands/owner/setUsername.js b/commands/owner/setUsername.js
index 42a0527..2fa609d 100644
--- a/commands/owner/setUsername.js
+++ b/commands/owner/setUsername.js
@@ -1,23 +1,23 @@
-const { redMessage } = require("../../utils/message");
+const { redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "setUsername",
- usage: "setUsername",
+ name: 'setUsername',
+ usage: 'setUsername',
aliases: [],
- description: "Set bot username",
+ description: 'Set bot username',
ownerOnly: true,
enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (message.deletable) {
- message.delete();
+ message.delete()
}
- let nick = args.join(" ");
- if(!nick) {
- return redMessage(message, "Please input some text to set as the username!");
+ const nick = args.join(' ')
+ if (!nick) {
+ return redMessage(message, 'Please input some text to set as the username!')
}
- await(client.user.setUsername(nick));
- return message.channel.send(`Successfully change username to ${nick}`).then((m) => m.delete({ timeout: 5000 }));
+ await (client.user.setUsername(nick))
+ return message.channel.send(`Successfully change username to ${nick}`).then((m) => m.delete({ timeout: 5000 }))
}
-};
+}
diff --git a/commands/owner/update.js b/commands/owner/update.js
index e67b397..2ce02bd 100644
--- a/commands/owner/update.js
+++ b/commands/owner/update.js
@@ -1,20 +1,20 @@
-const { exec } = require("child_process");
+const { exec } = require('child_process')
module.exports = {
config: {
- name: "update",
- usage: "update",
+ name: 'update',
+ usage: 'update',
aliases: [],
- description: "Command for owner to update and restart the bot",
+ description: 'Command for owner to update and restart the bot',
ownerOnly: true,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
try {
- exec("git pull && pm2 restart all", (stdout, stderr) => {
- message.channel.send("update: ```" + stdout + "```");
- });
+ exec('git pull && pm2 restart all', (stdout, stderr) => {
+ message.channel.send('update: ```' + stdout + '```')
+ })
} catch (error) {
- message.author.send(error.message);
+ message.author.send(error.message)
}
- },
-};
+ }
+}
diff --git a/commands/search/animeSearch.js b/commands/search/animeSearch.js
index 9371606..07906e6 100644
--- a/commands/search/animeSearch.js
+++ b/commands/search/animeSearch.js
@@ -1,49 +1,49 @@
-const malScraper = require("mal-scraper");
-const { MessageEmbed } = require("discord.js");
+const malScraper = require('mal-scraper')
+const { MessageEmbed } = require('discord.js')
module.exports = {
config: {
- name: "animeSearch",
- usage: "animeSearch [anime name]",
+ name: 'animeSearch',
+ usage: 'animeSearch [anime name]',
aliases: [],
- description: "Search for anime film statistic",
+ description: 'Search for anime film statistic',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const search = args.join(" ");
- if (!search) return message.reply("error");
+ async run (client, message, args) {
+ const search = args.join(' ')
+ if (!search) return message.reply('error')
malScraper
.getInfoFromName(search)
.then((anime) => {
- //console.log(anime);
+ // console.log(anime);
const embed = new MessageEmbed()
.setThumbnail(anime.picture)
- .setColor("BLUE")
+ .setColor('BLUE')
.setTitle(anime.title)
.setDescription(anime.synopsis)
.addField(
- "Translated title",
+ 'Translated title',
anime.englishTitle ? anime.englishTitle : anime.japaneseTitle,
true
)
- .addField("Anime type", anime.type, true)
- .addField("Numbers of episodes", anime.episodes, true)
- .addField("Rating", anime.rating, true)
- .addField("Release date", anime.aired, true)
- .addField("Anime score", anime.score, true)
- .addField("Anime score stats", anime.scoreStats, true)
- .addField("Anime duration", anime.duration, true)
- .addField("Anime rank", anime.ranked, true)
- .addField("Anime popularity", anime.popularity, true)
- .addField("Anime genres", `${anime.genres.join(", ")}`, true);
+ .addField('Anime type', anime.type, true)
+ .addField('Numbers of episodes', anime.episodes, true)
+ .addField('Rating', anime.rating, true)
+ .addField('Release date', anime.aired, true)
+ .addField('Anime score', anime.score, true)
+ .addField('Anime score stats', anime.scoreStats, true)
+ .addField('Anime duration', anime.duration, true)
+ .addField('Anime rank', anime.ranked, true)
+ .addField('Anime popularity', anime.popularity, true)
+ .addField('Anime genres', `${anime.genres.join(', ')}`, true)
- message.channel.send(embed);
+ message.channel.send(embed)
})
.catch((err) => {
- console.log(err.stack);
- message.reply(err.message);
- });
- },
-};
+ console.log(err.stack)
+ message.reply(err.message)
+ })
+ }
+}
diff --git a/commands/search/djs.js b/commands/search/djs.js
index f2cd0e8..ffba636 100644
--- a/commands/search/djs.js
+++ b/commands/search/djs.js
@@ -1,27 +1,26 @@
-const axios = require("axios");
- module.exports = {
- config: {
- name: "djs",
- usage: "djs",
- aliases: [],
- description: "Search for something on discord.js documents",
- ownerOnly: false,
- enabled: true
- },
- async run(client, message, args) {
- const query = args.join(" ");
+const axios = require('axios')
+module.exports = {
+ config: {
+ name: 'djs',
+ usage: 'djs',
+ aliases: [],
+ description: 'Search for something on discord.js documents',
+ ownerOnly: false,
+ enabled: true
+ },
+ async run (client, message, args) {
+ const query = args.join(' ')
axios.get(`https://djsdocs.sorta.moe/v2/embed?src=stable&q=${encodeURIComponent(query)}`).then((res) => {
- const embed = res.data;
-
- if (embed && !embed.error) {
- message.channel.send({ embed });
- } else {
- message.reply(`I don't know mate, but "${query}" doesn't make any sense!`)
- }
+ const embed = res.data
+
+ if (embed && !embed.error) {
+ message.channel.send({ embed })
+ } else {
+ message.reply(`I don't know mate, but "${query}" doesn't make any sense!`)
+ }
}).catch(() => {
- message.reply("Darn it! I failed!");
- });
- }
- };
-
\ No newline at end of file
+ message.reply('Darn it! I failed!')
+ })
+ }
+}
diff --git a/commands/search/github.js b/commands/search/github.js
index 45bb852..1a16cdc 100644
--- a/commands/search/github.js
+++ b/commands/search/github.js
@@ -1,21 +1,21 @@
-const axios = require("axios");
-const moment = require("moment");
-const { MessageEmbed } = require("discord.js");
-const { Colors } = require("../../utils/canvas");
-const { redMessage } = require("../../utils/message");
+const axios = require('axios')
+const moment = require('moment')
+const { MessageEmbed } = require('discord.js')
+const { Colors } = require('../../utils/canvas')
+const { redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "github",
- usage: "github",
- aliases: ["git"],
- description: "Show Github user or repo information",
+ name: 'github',
+ usage: 'github',
+ aliases: ['git'],
+ description: 'Show Github user or repo information',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (!args[0]) {
- return redMessage(message, "Wrong usage");
+ return redMessage(message, 'Wrong usage')
}
if (args[0] && args[1]) {
@@ -23,131 +23,131 @@ module.exports = {
return redMessage(
message,
"Please provide the repository owner's username or organisation name."
- );
+ )
}
if (!args[1]) {
return redMessage(
message,
- "Please provide a repository name to search for."
- );
+ 'Please provide a repository name to search for.'
+ )
}
axios
.get(`https://api.github.com/repos/${args[0]}/${args[1]}`)
.then((res) => {
- const repos = res.data;
+ const repos = res.data
if (repos.message) {
return redMessage(
message,
- "404",
+ '404',
`I wasnt able to find \`${args[0]}/${args[1]}\` on the github website!`
- );
+ )
}
const reposEmbed = new MessageEmbed()
.setColor(Colors.GITHUB)
.setAuthor(
- "GitHub Search Engine",
- "https://i.imgur.com/e4HunUm.png",
- "https://github.com/"
+ 'GitHub Search Engine',
+ 'https://i.imgur.com/e4HunUm.png',
+ 'https://github.com/'
)
.setTitle(repos.full_name)
.setURL(repos.html_url)
.setThumbnail(repos.owner.avatar_url)
.setDescription(
- repos.description ? repos.description : "[No description set]"
+ repos.description ? repos.description : '[No description set]'
)
.addField(
- "Updated",
- moment(repos.updated_at, "YYYYMMDDHHmmss").fromNow(),
+ 'Updated',
+ moment(repos.updated_at, 'YYYYMMDDHHmmss').fromNow(),
true
)
.addField(
- "Pushed",
- moment(repos.pushed_at, "YYYYMMDDHHmmss").fromNow(),
+ 'Pushed',
+ moment(repos.pushed_at, 'YYYYMMDDHHmmss').fromNow(),
true
)
.addField(
- "Created",
+ 'Created',
`${moment(repos.created_at).format(
- "ddd, DD MMMM YYYY HH:mm [GMT]Z"
- )} (${moment(repos.created_at, "YYYYMMDDHHmmss").fromNow()})`,
+ 'ddd, DD MMMM YYYY HH:mm [GMT]Z'
+ )} (${moment(repos.created_at, 'YYYYMMDDHHmmss').fromNow()})`,
false
)
- .addField("Stars", repos.stargazers_count, true)
- .addField("Forks", repos.forks, true)
- .addField("Issues", repos.open_issues, true)
- .addField("Language", repos.language || "No language", true)
+ .addField('Stars', repos.stargazers_count, true)
+ .addField('Forks', repos.forks, true)
+ .addField('Issues', repos.open_issues, true)
+ .addField('Language', repos.language || 'No language', true)
.addField(
- "License",
- repos.license ? repos.license.spdx_id : "Unlicensed",
+ 'License',
+ repos.license ? repos.license.spdx_id : 'Unlicensed',
true
)
.addField(
- "Archived",
- repos.archived.toString() === "True" ? "Yes" : "No",
+ 'Archived',
+ repos.archived.toString() === 'True' ? 'Yes' : 'No',
true
)
- .setFooter("Powered by GitHub")
- .setTimestamp();
+ .setFooter('Powered by GitHub')
+ .setTimestamp()
- message.channel.send(reposEmbed);
- });
+ message.channel.send(reposEmbed)
+ })
} else if (args[0]) {
if (!args[0]) {
return redMessage(
message,
- "Please provide a valid github account to search."
- );
+ 'Please provide a valid github account to search.'
+ )
}
axios.get(`https://api.github.com/users/${args[0]}`).then((res) => {
- const users = res.data;
+ const users = res.data
if (users.message) {
return redMessage(
message,
- "404",
+ '404',
`I wasnt able to find \`${args[0]}\` on the github website!`
- );
+ )
}
const usersEmbed = new MessageEmbed()
.setColor(Colors.GITHUB)
.setAuthor(
- "GitHub Search Engine",
- "https://i.imgur.com/4EDz1aY.png",
- "https://github.com/"
+ 'GitHub Search Engine',
+ 'https://i.imgur.com/4EDz1aY.png',
+ 'https://github.com/'
)
.setTitle(users.login)
.setURL(users.html_url)
.setThumbnail(users.avatar_url)
- .setDescription(`${users.bio || "[No bio set]"}`)
- .addField("Name", `${users.name || "Not Public."}`, true)
- .addField("ID", `${users.id || "Unknown"}`, true)
+ .setDescription(`${users.bio || '[No bio set]'}`)
+ .addField('Name', `${users.name || 'Not Public.'}`, true)
+ .addField('ID', `${users.id || 'Unknown'}`, true)
.addField(
- "Updated",
- `${moment(users.updated_at, "YYYYMMDDHHmmss").fromNow()}`,
+ 'Updated',
+ `${moment(users.updated_at, 'YYYYMMDDHHmmss').fromNow()}`,
true
)
- .addField("Location", `${users.location || "Invisible."}`, false)
- .addField("Repositories", `${users.public_repos}`, true)
- .addField("Followers", `${users.followers}`, true)
- .addField("Following", `${users.following}`, true)
+ .addField('Location', `${users.location || 'Invisible.'}`, false)
+ .addField('Repositories', `${users.public_repos}`, true)
+ .addField('Followers', `${users.followers}`, true)
+ .addField('Following', `${users.following}`, true)
.addField(
- "Created",
+ 'Created',
`${moment(users.created_at).format(
- "ddd, DD MMMM YYYY HH:mm [GMT]Z"
- )} (${moment(users.created_at, "YYYYMMDDHHmmss").fromNow()})`,
+ 'ddd, DD MMMM YYYY HH:mm [GMT]Z'
+ )} (${moment(users.created_at, 'YYYYMMDDHHmmss').fromNow()})`,
false
)
- .setFooter("Powered by GitHub")
- .setTimestamp();
+ .setFooter('Powered by GitHub')
+ .setTimestamp()
- message.channel.send(usersEmbed);
- });
+ message.channel.send(usersEmbed)
+ })
}
- },
-};
+ }
+}
diff --git a/commands/search/imdb.js b/commands/search/imdb.js
index eba08d5..18ed0c1 100644
--- a/commands/search/imdb.js
+++ b/commands/search/imdb.js
@@ -1,86 +1,86 @@
-const { MessageEmbed } = require("discord.js");
-const moment = require("moment");
-const IMDB = require("imdb-api");
-const { Colors } = require("../../utils/canvas");
-const { redMessage } = require("../../utils/message");
+const { MessageEmbed } = require('discord.js')
+const moment = require('moment')
+const IMDB = require('imdb-api')
+const { Colors } = require('../../utils/canvas')
+const { redMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "imdb",
- usage: "imdb",
+ name: 'imdb',
+ usage: 'imdb',
aliases: [],
- description: "Search for a movie ỏ series stats on IMDB",
+ description: 'Search for a movie ỏ series stats on IMDB',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const query = args.join(" ");
- if (!query)
- return redMessage(message, "Please give the name of movie or series");
+ async run (client, message, args) {
+ const query = args.join(' ')
+ if (!query) { return redMessage(message, 'Please give the name of movie or series') }
IMDB.get({ name: query }, { apiKey: process.env.IMDB })
.then((res) => {
const movieEmbed = new MessageEmbed()
.setColor(Colors.IMDB)
.setAuthor(
- "IMDb Search Engine",
- "https://i.imgur.com/0BTAjjv.png",
- "https://www.imdb.com/"
+ 'IMDb Search Engine',
+ 'https://i.imgur.com/0BTAjjv.png',
+ 'https://www.imdb.com/'
)
.setTitle(res.title)
.setURL(res.imdburl)
.setThumbnail(res.poster)
.setDescription(res.plot)
- .addField("Rated", res.rated, true)
- .addField("Runtime", res.runtime, true)
+ .addField('Rated', res.rated, true)
+ .addField('Runtime', res.runtime, true)
.addField(
- "Released",
- `${moment(res.released).format("DD MMMM YYYY")}`,
+ 'Released',
+ `${moment(res.released).format('DD MMMM YYYY')}`,
true
)
.addField(
- "Ratings",
+ 'Ratings',
`${res.rating}/10 ⭐\nby ${res.votes} users`,
true
)
.addField(
- "Metascores",
+ 'Metascores',
`${res.metascore}/100\nFrom [metacritic](https://metacritic.com)`,
true
)
.addField(
- "Type",
+ 'Type',
`${res.type.slice(0, 1).toUpperCase()}${res.type.slice(1)}`,
true
)
- .addField("Genres", res.genres, false)
- .addField("Directors", res.director, true)
- .addField("Cast", res.actors, true)
- .addField("Writers", res.writer, false)
- .addField("Production", res.production || "Unknown", true)
- .addField("Country", res.country, true)
- .addField("Language", res.languages, true)
- .setFooter("Powered by IMDb")
- .setTimestamp();
+ .addField('Genres', res.genres, false)
+ .addField('Directors', res.director, true)
+ .addField('Cast', res.actors, true)
+ .addField('Writers', res.writer, false)
+ .addField('Production', res.production || 'Unknown', true)
+ .addField('Country', res.country, true)
+ .addField('Language', res.languages, true)
+ .setFooter('Powered by IMDb')
+ .setTimestamp()
- if (res.awards !== "N/A") {
- movieEmbed.addField("Awards", res.awards, false);
+ if (res.awards !== 'N/A') {
+ movieEmbed.addField('Awards', res.awards, false)
}
if (res.series === true) {
- movieEmbed.addField("Total Seasons", res.totalseasons, true);
- movieEmbed.addField("Released Year", res._year_data, true);
+ movieEmbed.addField('Total Seasons', res.totalseasons, true)
+ movieEmbed.addField('Released Year', res._year_data, true)
}
- message.channel.send(movieEmbed);
+ message.channel.send(movieEmbed)
})
.catch((err) => {
- if (err.message.startsWith("Movie not found!:"))
+ if (err.message.startsWith('Movie not found!:')) {
return redMessage(
message,
- "404",
- "Request not found, make sure you have written the title correctly"
- );
- });
- },
-};
+ '404',
+ 'Request not found, make sure you have written the title correctly'
+ )
+ }
+ })
+ }
+}
diff --git a/commands/search/instagram.js b/commands/search/instagram.js
index f1e2805..e1b5a8d 100644
--- a/commands/search/instagram.js
+++ b/commands/search/instagram.js
@@ -1,33 +1,33 @@
-const { Colors } = require("../../utils/canvas");
-const { redMessage } = require("../../utils/message");
-const request = require("request-promise-native");
-const { MessageEmbed } = require("discord.js");
-const { stripIndents } = require("common-tags");
-const { formatNumber } = require("../../utils/utility");
+const { Colors } = require('../../utils/canvas')
+const { redMessage } = require('../../utils/message')
+const request = require('request-promise-native')
+const { MessageEmbed } = require('discord.js')
+const { stripIndents } = require('common-tags')
+const { formatNumber } = require('../../utils/utility')
module.exports = {
config: {
- name: "instagram",
- usage: "instagram",
- aliases: ["ig"],
- description: "Search for an Instagram account",
+ name: 'instagram',
+ usage: 'instagram',
+ aliases: ['ig'],
+ description: 'Search for an Instagram account',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let name = args[0];
+ async run (client, message, args) {
+ const name = args[0]
request(`https://instagram.com/${name}/?__a=1`, async function (
error,
response,
body
) {
- let data = JSON.parse(body);
- let account = data.graphql.user;
+ const data = JSON.parse(body)
+ const account = data.graphql.user
const instagramEmbed = new MessageEmbed()
.setColor(Colors.INSTAGRAM)
.setAuthor(
- "Instagram Search Engine",
- "https://i.imgur.com/wgMjJvq.png",
- "https://instagram.com/"
+ 'Instagram Search Engine',
+ 'https://i.imgur.com/wgMjJvq.png',
+ 'https://instagram.com/'
)
.setTitle(account.full_name)
.setURL(`https://instagram.com/${name}`)
@@ -36,29 +36,29 @@ module.exports = {
stripIndents`
${
account.biography.length === 0
- ? "None"
+ ? 'None'
: account.biography
}
- ${account.external_url || " "}`
+ ${account.external_url || ' '}`
)
- .addField("Username", `@${account.username}`, true)
- .addField("Verified", account.is_verified ? "Yes" : "No", true)
- .addField("Private", account.is_private ? "Yes 🔐" : "No 🔓", true)
+ .addField('Username', `@${account.username}`, true)
+ .addField('Verified', account.is_verified ? 'Yes' : 'No', true)
+ .addField('Private', account.is_private ? 'Yes 🔐' : 'No 🔓', true)
.addField(
- "Posts",
+ 'Posts',
formatNumber(account.edge_owner_to_timeline_media.count),
true
)
.addField(
- "Followers",
+ 'Followers',
formatNumber(account.edge_followed_by.count),
true
)
- .addField("Following", formatNumber(account.edge_follow.count), true)
- .setFooter("Powered by Instagram")
- .setTimestamp();
+ .addField('Following', formatNumber(account.edge_follow.count), true)
+ .setFooter('Powered by Instagram')
+ .setTimestamp()
- message.channel.send(instagramEmbed);
- });
- },
-};
+ message.channel.send(instagramEmbed)
+ })
+ }
+}
diff --git a/commands/search/reddit.js b/commands/search/reddit.js
index 1f4c718..25c4187 100644
--- a/commands/search/reddit.js
+++ b/commands/search/reddit.js
@@ -1,84 +1,84 @@
-const { MessageEmbed } = require("discord.js");
-const fetch = require("node-fetch");
+const { MessageEmbed } = require('discord.js')
+const fetch = require('node-fetch')
module.exports = {
config: {
- name: "reddit",
- usage: "reddit [subreddit name]",
+ name: 'reddit',
+ usage: 'reddit [subreddit name]',
aliases: [],
- description: "Send top 10 daily posts of a subreddit",
+ description: 'Send top 10 daily posts of a subreddit',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let subreddit = args[0];
+ async run (client, message, args) {
+ let subreddit = args[0]
if (!args[0]) {
- await message.channel.send("Which subreddit ?");
- let collected = await message.channel.awaitMessages(
+ await message.channel.send('Which subreddit ?')
+ const collected = await message.channel.awaitMessages(
(m) => m.author.id === message.author.id,
{
max: 1,
- time: 30000,
+ time: 30000
}
- );
- subreddit = collected.first().content;
+ )
+ subreddit = collected.first().content
}
await message.channel.send(
- `Do you want to get the top posts from past hour/week/month/year or all?`
- );
+ 'Do you want to get the top posts from past hour/week/month/year or all?'
+ )
try {
var t = await message.channel.awaitMessages(
(msg) =>
- msg.content === "hour" ||
- msg.content === "week" ||
- msg.content === "month" ||
- msg.content === "year" ||
- msg.content === "all",
+ msg.content === 'hour' ||
+ msg.content === 'week' ||
+ msg.content === 'month' ||
+ msg.content === 'year' ||
+ msg.content === 'all',
{
max: 1,
maxProcessed: 1,
time: 60000,
- errors: ["time"],
+ errors: ['time']
}
- );
- var timeFilter = t.first().content;
+ )
+ var timeFilter = t.first().content
} catch (e) {
- console.error(e);
+ console.error(e)
return message.channel.send(
- "Please try again and enter a proper time filter"
- );
+ 'Please try again and enter a proper time filter'
+ )
}
fetch(
`https://www.reddit.com/r/${subreddit}/top/.json?limit=10&t=${
- timeFilter ? timeFilter : "day"
+ timeFilter || 'day'
}`
)
.then((res) => res.json())
.then((json) => {
- const dataArr = json.data.children;
+ const dataArr = json.data.children
for (let i = 0; i < dataArr.length; i++) {
- message.channel.send(embedPost(dataArr[i].data));
+ message.channel.send(embedPost(dataArr[i].data))
}
})
.catch((err) => {
- message.channel.send("The subreddit you asked for was not found");
- return console.error(err);
- });
+ message.channel.send('The subreddit you asked for was not found')
+ return console.error(err)
+ })
// returns an embed that is ready to be sent
- function embedPost(data) {
- let color = "#FE9004";
+ function embedPost (data) {
+ let color = '#FE9004'
if (data.title.length > 255) {
- data.title = data.title.substring(0, 252) + "..."; // discord.js does not allow embed title lengths greater than 256
+ data.title = data.title.substring(0, 252) + '...' // discord.js does not allow embed title lengths greater than 256
}
- if (data.over_18) color = "#cf000f";
+ if (data.over_18) color = '#cf000f'
return new MessageEmbed()
.setColor(color) // if post is nsfw, color is red
.setTitle(data.title)
.setURL(`https://www.reddit.com${data.permalink}`)
.setDescription(`Upvotes: ${data.score} :thumbsup: `)
.setAuthor(data.author)
- .setImage(data.url);
+ .setImage(data.url)
}
- },
-};
+ }
+}
diff --git a/commands/search/songSearch.js b/commands/search/songSearch.js
index 40a91e8..6c98f5e 100644
--- a/commands/search/songSearch.js
+++ b/commands/search/songSearch.js
@@ -1,52 +1,52 @@
-const { verify } = require("../../utils/utility");
-const request = require("request-promise-native");
-const cheerio = require("cheerio");
-const fetch = require("node-fetch");
-const yts = require("yt-search");
-const { removeAccents } = require("../../utils/utility");
+const { verify } = require('../../utils/utility')
+const request = require('request-promise-native')
+const cheerio = require('cheerio')
+const fetch = require('node-fetch')
+const yts = require('yt-search')
+const { removeAccents } = require('../../utils/utility')
module.exports = {
config: {
- name: "songSearch",
- usage: "songSearch [lyrics]",
+ name: 'songSearch',
+ usage: 'songSearch [lyrics]',
aliases: [],
- description: "Search for a song by lyrics. use --v for vietnamese",
+ description: 'Search for a song by lyrics. use --v for vietnamese',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- if (args.includes("--v")) return vietnamSongs();
- let params = encodeURIComponent(args.join(" "));
- let url = "https://songsear.ch/q/" + params;
+ async run (client, message, args) {
+ if (args.includes('--v')) return vietnamSongs()
+ const params = encodeURIComponent(args.join(' '))
+ const url = 'https://songsear.ch/q/' + params
fetch(url)
.then((res) => res.text())
.then(async (body) => {
- let $ = cheerio.load(body);
- var songName = $("div.head > h2 > a").first().text();
- var songArtist = $("div.head > h3 > b").first().text();
- let shortLyrics = $("div.fragments > p").first().text();
- shortLyrics.replace(args.join(" "), `**${args.join(" ")}**`);
- let r = await yts(songName);
- if (!r) return message.reply("I don't know");
+ const $ = cheerio.load(body)
+ var songName = $('div.head > h2 > a').first().text()
+ var songArtist = $('div.head > h3 > b').first().text()
+ const shortLyrics = $('div.fragments > p').first().text()
+ shortLyrics.replace(args.join(' '), `**${args.join(' ')}**`)
+ const r = await yts(songName)
+ if (!r) return message.reply("I don't know")
message.channel.send({
embed: {
color: 3447003,
- title: "My guess",
+ title: 'My guess',
fields: [
{
- name: "Song title",
- value: songName + " by " + songArtist,
+ name: 'Song title',
+ value: songName + ' by ' + songArtist
},
{
- name: "URL",
- value: r.videos[0].url,
- },
+ name: 'URL',
+ value: r.videos[0].url
+ }
],
thumbnail: {
- url: r.videos[0].thumbnail,
- },
- },
- });
- });
+ url: r.videos[0].thumbnail
+ }
+ }
+ })
+ })
// let searchlink = "https://api.audd.io/findLyrics/?q=" + args.join(" ");
// request(searchlink, async function (error, response, body) {
@@ -89,42 +89,42 @@ module.exports = {
// }
// });
- async function vietnamSongs() {
+ async function vietnamSongs () {
args = args.filter(function (value, index, arr) {
- return value !== "--v";
- });
- let params = args.join("+");
- params = removeAccents(params);
- let url = `https://www.nhaccuatui.com/tim-kiem?q=${params}&b=lyric&s=default&l=tat-ca`;
- console.log(url);
+ return value !== '--v'
+ })
+ let params = args.join('+')
+ params = removeAccents(params)
+ const url = `https://www.nhaccuatui.com/tim-kiem?q=${params}&b=lyric&s=default&l=tat-ca`
+ console.log(url)
fetch(url)
.then((res) => res.text())
.then(async (body) => {
- let $ = cheerio.load(body);
- let a = $("h3.title_song > a").first().prop("title");
- let b = $("h4.singer_song > a").first().text();
- let r = await yts(a);
- if (!r) return message.reply("I don't know");
+ const $ = cheerio.load(body)
+ const a = $('h3.title_song > a').first().prop('title')
+ const b = $('h4.singer_song > a').first().text()
+ const r = await yts(a)
+ if (!r) return message.reply("I don't know")
message.channel.send({
embed: {
color: 3447003,
- title: "My guess",
+ title: 'My guess',
fields: [
{
- name: "Song title",
- value: a + " by " + b,
+ name: 'Song title',
+ value: a + ' by ' + b
},
{
- name: "URL",
- value: r.videos[0].url,
- },
+ name: 'URL',
+ value: r.videos[0].url
+ }
],
thumbnail: {
- url: r.videos[0].thumbnail,
- },
- },
- });
- });
+ url: r.videos[0].thumbnail
+ }
+ }
+ })
+ })
}
- },
-};
+ }
+}
diff --git a/commands/search/steam.js b/commands/search/steam.js
index 5633816..b21acfa 100644
--- a/commands/search/steam.js
+++ b/commands/search/steam.js
@@ -1,77 +1,77 @@
-const { MessageEmbed } = require("discord.js");
-const moment = require("moment");
-const IMDB = require("imdb-api");
-const { Colors } = require("../../utils/canvas");
-const { redMessage } = require("../../utils/message");
-const { stripIndents } = require("common-tags");
-const axios = require("axios");
-const { formatNumber } = require("../../utils/utility");
+const { MessageEmbed } = require('discord.js')
+const moment = require('moment')
+const IMDB = require('imdb-api')
+const { Colors } = require('../../utils/canvas')
+const { redMessage } = require('../../utils/message')
+const { stripIndents } = require('common-tags')
+const axios = require('axios')
+const { formatNumber } = require('../../utils/utility')
module.exports = {
config: {
- name: "steam",
- usage: "steam",
+ name: 'steam',
+ usage: 'steam',
aliases: [],
- description: "Search for Steam games",
+ description: 'Search for Steam games',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- const query = args.join(" ");
+ async run (client, message, args) {
+ const query = args.join(' ')
if (!query) {
- return redMessage(message, "noQuery");
+ return redMessage(message, 'noQuery')
}
const headers = {
- "user-agent":
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36",
- };
+ 'user-agent':
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
+ }
const data = await axios
.get(
`https://store.steampowered.com/api/storesearch/?term=${query}&l=en&cc=us`,
{ headers }
)
- .then((res) => res.data);
+ .then((res) => res.data)
if (!data.items.length) {
- return redMessage(message, "invalidQuery");
+ return redMessage(message, 'invalidQuery')
}
- const ids = data.items[0].id;
+ const ids = data.items[0].id
const details = await axios
.get(`https://store.steampowered.com/api/appdetails?appids=${ids}`, {
- headers,
+ headers
})
- .then((res) => res.data[ids].data);
+ .then((res) => res.data[ids].data)
const price = details.price_overview
? details.price_overview.final_formatted
- : "$0";
- const platforms = [];
+ : '$0'
+ const platforms = []
if (details.platforms) {
- if (details.platforms.windows) platforms.push("Windows");
- if (details.platforms.mac) platforms.push("Mac");
- if (details.platforms.linux) platforms.push("Linux");
+ if (details.platforms.windows) platforms.push('Windows')
+ if (details.platforms.mac) platforms.push('Mac')
+ if (details.platforms.linux) platforms.push('Linux')
}
const steamEmbed = new MessageEmbed()
.setColor(Colors.STEAM)
.setAuthor(
- "Steam Store Search Engine",
- "https://i.imgur.com/xxr2UBZ.png",
- "http://store.steampowered.com/"
+ 'Steam Store Search Engine',
+ 'https://i.imgur.com/xxr2UBZ.png',
+ 'http://store.steampowered.com/'
)
.setTitle(details.name)
.setURL(`https://store.steampowered.com/app/${details.steam_appid}/`)
.setImage(details.header_image)
.setDescription(details.short_description)
.addField(
- "__**Details**__",
+ '__**Details**__',
stripIndents`
_Release Date:_ **${
- details.release_date ? details.release_date.date : "Coming Soon"
+ details.release_date ? details.release_date.date : 'Coming Soon'
}**
_Price:_ **${price}**
- _Genres:_ **${details.genres.map((g) => g.description).join(", ")}**
- _Platform:_ **${platforms.join(", ") || "None"}**
+ _Genres:_ **${details.genres.map((g) => g.description).join(', ')}**
+ _Platform:_ **${platforms.join(', ') || 'None'}**
_Achievements:_ **${
details.achievements
? formatNumber(details.achievements.total)
@@ -83,20 +83,20 @@ module.exports = {
_Recommendations:_ **${
details.recommendations
? formatNumber(details.recommendations.total)
- : "None"
+ : 'None'
}**
- _Publishers:_ **${details.publishers.join(", ")}**
- _Developers:_ **${details.developers.join(", ")}**
- _Website:_ **${details.website ? details.website : "None"}**
+ _Publishers:_ **${details.publishers.join(', ')}**
+ _Developers:_ **${details.developers.join(', ')}**
+ _Website:_ **${details.website ? details.website : 'None'}**
_Support:_ **${
details.support_info
? details.support_info.url
- : details.support_info.email || "None"
+ : details.support_info.email || 'None'
}**`
)
- .setFooter("Powered by Steam Store")
- .setTimestamp();
+ .setFooter('Powered by Steam Store')
+ .setTimestamp()
- message.channel.send(steamEmbed);
- },
-};
+ message.channel.send(steamEmbed)
+ }
+}
diff --git a/commands/search/weather.js b/commands/search/weather.js
index 78783ee..d0a900e 100644
--- a/commands/search/weather.js
+++ b/commands/search/weather.js
@@ -1,104 +1,104 @@
-const { MessageEmbed } = require("discord.js");
-const weather = require("openweather-apis");
-const moment = require("moment-timezone");
-const geotz = require("geo-tz");
+const { MessageEmbed } = require('discord.js')
+const weather = require('openweather-apis')
+const moment = require('moment-timezone')
+const geotz = require('geo-tz')
module.exports = {
config: {
- name: "weather",
- usage: "weather",
+ name: 'weather',
+ usage: 'weather',
aliases: [],
- description: "Show weather of specific location",
+ description: 'Show weather of specific location',
ownerOnly: false,
enabled: true
},
- async run(client, message, args) {
- let city = args.join(" ").toLowerCase().trim();
+ async run (client, message, args) {
+ const city = args.join(' ').toLowerCase().trim()
if (!city) {
- return Errors.wrongText(message, "Please provide me a city to search up!");
+ return Errors.wrongText(message, 'Please provide me a city to search up!')
}
-
- weather.setAPPID(process.env.OPENWEATHER);
- weather.setLang("en");
- weather.setUnits("metric");
- weather.setCity(city);
- weather.getAllWeather( function (err, res) {
- if (err) {
- return message.channel.send("An Error Has occured, Try again later.");
- }
- if (res.cod === "404" || !res.sys.country) {
- return Errors.resStatus("404", message, "Couldn't Find That Location!");
- } else if (res.cod === "401") {
- return Errors.resStatus("401", message, "Invalid API Key!");
- }
+ weather.setAPPID(process.env.OPENWEATHER)
+ weather.setLang('en')
+ weather.setUnits('metric')
+ weather.setCity(city)
+ weather.getAllWeather(function (err, res) {
+ if (err) {
+ return message.channel.send('An Error Has occured, Try again later.')
+ }
- var compass;
- if (res.wind.deg > 39.37 && res.wind.deg < 84.37 ) {
- compass = "Northeast";
- } else if (res.wind.deg > 84.37 && res.wind.deg < 129.37 ) {
- compass = "East";
- } else if (res.wind.deg > 129.37 && res.wind.deg < 174.37 ) {
- compass = "Southeast";
- } else if (res.wind.deg > 174.37 && res.wind.deg < 219.37 ) {
- compass = "South";
- } else if (res.wind.deg > 219.37 && res.wind.deg < 264.37 ) {
- compass = "Southwest";
- } else if (res.wind.deg > 264.37 && res.wind.deg < 309.37 ) {
- compass = "West";
- } else if (res.wind.deg > 309.37 && res.wind.deg < 354.37 ) {
- compass = "Northwest";
- } else {
- compass = "North";
- }
+ if (res.cod === '404' || !res.sys.country) {
+ return Errors.resStatus('404', message, "Couldn't Find That Location!")
+ } else if (res.cod === '401') {
+ return Errors.resStatus('401', message, 'Invalid API Key!')
+ }
- var tempColors;
- if (res.main.temp < 0) {
- tempColors = "#CCF3FF";
- } else if (res.main.temp < 5) {
- tempColors = "#BFF0FF";
- } else if (res.main.temp < 10) {
- tempColors = "#B4FF92";
- } else if (res.main.temp < 15) {
- tempColors = "#8CF974";
- } else if (res.main.temp < 20) {
- tempColors = "#ECFF7A";
- } else if (res.main.temp < 25) {
- tempColors = "#FFC97A";
- } else if (res.main.temp < 30) {
- tempColors = "#FF6E46";
- } else if (res.main.temp < 35) {
- tempColors = "#FF4B22";
- } else if (res.main.temp < 40) {
- tempColors = "#FF3C22";
- } else if (res.main.temp > 40) {
- tempColors = "#BD0000";
- } else {
- tempColors = "#74CDFF";
- }
+ var compass
+ if (res.wind.deg > 39.37 && res.wind.deg < 84.37) {
+ compass = 'Northeast'
+ } else if (res.wind.deg > 84.37 && res.wind.deg < 129.37) {
+ compass = 'East'
+ } else if (res.wind.deg > 129.37 && res.wind.deg < 174.37) {
+ compass = 'Southeast'
+ } else if (res.wind.deg > 174.37 && res.wind.deg < 219.37) {
+ compass = 'South'
+ } else if (res.wind.deg > 219.37 && res.wind.deg < 264.37) {
+ compass = 'Southwest'
+ } else if (res.wind.deg > 264.37 && res.wind.deg < 309.37) {
+ compass = 'West'
+ } else if (res.wind.deg > 309.37 && res.wind.deg < 354.37) {
+ compass = 'Northwest'
+ } else {
+ compass = 'North'
+ }
- let city_tz = geotz(res.coord.lat, res.coord.lon);
- const weatherEmbed = new MessageEmbed()
- .setColor(tempColors)
- .setAuthor("Forecast today", "https://cdn1.iconfinder.com/data/icons/weather-429/64/weather_icons_color-06-512.png")
- .setTitle(`:flag_${res.sys.country.toLowerCase()}: ${res.name} - ${res.weather[0].main}`)
- .setDescription(`${res.weather[0].description[0].toUpperCase()}${res.weather[0].description.slice(1)} (${res.clouds.all}% clouds)`)
- .setURL(`https://openweathermap.org/city/${res.id}`)
- .setThumbnail(`https://openweathermap.org/img/wn/${res.weather[0].icon}@2x.png`)
- .addField("🌡️ Temperature", `${res.main.temp}°C | ${(res.main.temp*1.8+32).toFixed(2)}°F`, true)
- .addField("🍧 Feels Like", `${res.main.feels_like}°C | ${(res.main.feels_like*1.8+32).toFixed(2)}°F`, true)
- .addField("💧 Humidity", `${res.main.humidity}%`, true)
- .addField("☀️ Minimum/Maximum Temperature", `${res.main.temp_min}°C | ${(res.main.temp_min*1.8+32).toFixed(2)}°F / ${res.main.temp_max}°C | ${(res.main.temp_max*1.8+32).toFixed(2)}°F`, false)
- .addField("☁️ Pressure", `${res.main.pressure} hPA`, true)
- .addField("📏 Latitude | Longitude", `${res.coord.lat} | ${res.coord.lon}`, true)
- .addField("🌬️ Wind Speed", `${(res.wind.speed*3.6).toFixed(2)} km/h | ${(res.wind.speed*2.2369).toFixed(2)} mph, ${compass} (${res.wind.deg}°) `, false)
- .addField("🌅 Sunrise", `${moment(res.sys.sunrise*1000).tz(`${city_tz}`).format("HH:mm [GMT]Z")}`, true)
- .addField("🌇 Sunset", `${moment(res.sys.sunset*1000).tz(`${city_tz}`).format("HH:mm [GMT]Z")}`, true)
- .addField("⌚ Current Time", `${moment().tz(`${city_tz}`).format("ddd, DD MMMM YYYY HH:mm [GMT]Z")}`, false)
- .setFooter("Powered by OpenWeatherMap")
- .setTimestamp();
+ var tempColors
+ if (res.main.temp < 0) {
+ tempColors = '#CCF3FF'
+ } else if (res.main.temp < 5) {
+ tempColors = '#BFF0FF'
+ } else if (res.main.temp < 10) {
+ tempColors = '#B4FF92'
+ } else if (res.main.temp < 15) {
+ tempColors = '#8CF974'
+ } else if (res.main.temp < 20) {
+ tempColors = '#ECFF7A'
+ } else if (res.main.temp < 25) {
+ tempColors = '#FFC97A'
+ } else if (res.main.temp < 30) {
+ tempColors = '#FF6E46'
+ } else if (res.main.temp < 35) {
+ tempColors = '#FF4B22'
+ } else if (res.main.temp < 40) {
+ tempColors = '#FF3C22'
+ } else if (res.main.temp > 40) {
+ tempColors = '#BD0000'
+ } else {
+ tempColors = '#74CDFF'
+ }
- message.channel.send(weatherEmbed);
- });
+ const city_tz = geotz(res.coord.lat, res.coord.lon)
+ const weatherEmbed = new MessageEmbed()
+ .setColor(tempColors)
+ .setAuthor('Forecast today', 'https://cdn1.iconfinder.com/data/icons/weather-429/64/weather_icons_color-06-512.png')
+ .setTitle(`:flag_${res.sys.country.toLowerCase()}: ${res.name} - ${res.weather[0].main}`)
+ .setDescription(`${res.weather[0].description[0].toUpperCase()}${res.weather[0].description.slice(1)} (${res.clouds.all}% clouds)`)
+ .setURL(`https://openweathermap.org/city/${res.id}`)
+ .setThumbnail(`https://openweathermap.org/img/wn/${res.weather[0].icon}@2x.png`)
+ .addField('🌡️ Temperature', `${res.main.temp}°C | ${(res.main.temp * 1.8 + 32).toFixed(2)}°F`, true)
+ .addField('🍧 Feels Like', `${res.main.feels_like}°C | ${(res.main.feels_like * 1.8 + 32).toFixed(2)}°F`, true)
+ .addField('💧 Humidity', `${res.main.humidity}%`, true)
+ .addField('☀️ Minimum/Maximum Temperature', `${res.main.temp_min}°C | ${(res.main.temp_min * 1.8 + 32).toFixed(2)}°F / ${res.main.temp_max}°C | ${(res.main.temp_max * 1.8 + 32).toFixed(2)}°F`, false)
+ .addField('☁️ Pressure', `${res.main.pressure} hPA`, true)
+ .addField('📏 Latitude | Longitude', `${res.coord.lat} | ${res.coord.lon}`, true)
+ .addField('🌬️ Wind Speed', `${(res.wind.speed * 3.6).toFixed(2)} km/h | ${(res.wind.speed * 2.2369).toFixed(2)} mph, ${compass} (${res.wind.deg}°) `, false)
+ .addField('🌅 Sunrise', `${moment(res.sys.sunrise * 1000).tz(`${city_tz}`).format('HH:mm [GMT]Z')}`, true)
+ .addField('🌇 Sunset', `${moment(res.sys.sunset * 1000).tz(`${city_tz}`).format('HH:mm [GMT]Z')}`, true)
+ .addField('⌚ Current Time', `${moment().tz(`${city_tz}`).format('ddd, DD MMMM YYYY HH:mm [GMT]Z')}`, false)
+ .setFooter('Powered by OpenWeatherMap')
+ .setTimestamp()
+
+ message.channel.send(weatherEmbed)
+ })
}
-};
+}
diff --git a/commands/search/wikihow.js b/commands/search/wikihow.js
index 09e607f..fe514af 100644
--- a/commands/search/wikihow.js
+++ b/commands/search/wikihow.js
@@ -1,45 +1,45 @@
-const { stripIndents } = require("common-tags");
-const fetch = require("node-fetch");
-const cheerio = require("cheerio");
+const { stripIndents } = require('common-tags')
+const fetch = require('node-fetch')
+const cheerio = require('cheerio')
module.exports = {
config: {
- name: "wikihow",
- usage: "wikihow",
+ name: 'wikihow',
+ usage: 'wikihow',
aliases: [],
- description: "Send a wikihow",
+ description: 'Send a wikihow',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let query = args.join("+");
- let url = "https://www.wikihow.com/wikiHowTo?search=" + query;
+ async run (client, message, args) {
+ const query = args.join('+')
+ const url = 'https://www.wikihow.com/wikiHowTo?search=' + query
fetch(url)
.then((res) => res.text())
.then(async (body) => {
- var $ = cheerio.load(body);
- let wikiurl = $("a.result_link").first().attr("href");
- let wikititle = $("div.result_title").first().text();
+ var $ = cheerio.load(body)
+ const wikiurl = $('a.result_link').first().attr('href')
+ const wikititle = $('div.result_title').first().text()
message.channel.send({
embed: {
color: 3447003,
title: wikititle,
fields: [
{
- name: "URL",
- value: wikiurl,
- },
+ name: 'URL',
+ value: wikiurl
+ }
],
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
- });
- },
-};
+ size: 1024
+ })
+ }
+ }
+ })
+ })
+ }
+}
diff --git a/commands/search/wikipedia.js b/commands/search/wikipedia.js
index 9861047..3bcc41a 100644
--- a/commands/search/wikipedia.js
+++ b/commands/search/wikipedia.js
@@ -1,22 +1,22 @@
-const { MessageEmbed } = require("discord.js");
-const { Colors } = require("../../utils/canvas");
-const axios = require("axios");
+const { MessageEmbed } = require('discord.js')
+const { Colors } = require('../../utils/canvas')
+const axios = require('axios')
module.exports = {
config: {
- name: "wikipedia",
- usage: "wikipedia",
- aliases: ["wiki"],
- description: "Search for something on Wikipedia",
+ name: 'wikipedia',
+ usage: 'wikipedia',
+ aliases: ['wiki'],
+ description: 'Search for something on Wikipedia',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let query = args.join(" ");
+ async run (client, message, args) {
+ const query = args.join(' ')
if (!query) {
return Errors.wrongText(
message,
- "Please provide query to search on Wikipedia"
- );
+ 'Please provide query to search on Wikipedia'
+ )
}
axios
@@ -26,22 +26,22 @@ module.exports = {
)}`
)
.then((res) => {
- const article = res.data;
+ const article = res.data
if (!article.content_urls) {
return Errors.resStatus(
- "404",
+ '404',
message,
"I couldn't find a wikipedia article with that title!"
- );
+ )
}
const articleEmbed = new MessageEmbed()
.setColor(Colors.WIKIPEDIA)
.setAuthor(
- "Wikipedia Search Engine",
- "https://i.imgur.com/C665mkB.png",
- "https://en.wikipedia.org/"
+ 'Wikipedia Search Engine',
+ 'https://i.imgur.com/C665mkB.png',
+ 'https://en.wikipedia.org/'
)
.setTitle(article.title)
.setURL(article.content_urls.desktop.page)
@@ -49,10 +49,10 @@ module.exports = {
article.originalimage ? article.originalimage.source : null
)
.setDescription(article.extract)
- .setFooter("Powered by Wikipedia")
- .setTimestamp();
+ .setFooter('Powered by Wikipedia')
+ .setTimestamp()
- message.channel.send(articleEmbed);
- });
- },
-};
+ message.channel.send(articleEmbed)
+ })
+ }
+}
diff --git a/commands/util/calculate.js b/commands/util/calculate.js
index 817c2fa..6655a0e 100644
--- a/commands/util/calculate.js
+++ b/commands/util/calculate.js
@@ -1,37 +1,37 @@
-const { MessageEmbed } = require("discord.js");
-const { Colors } = require("../../utils/canvas");
-const math = require("mathjs");
+const { MessageEmbed } = require('discord.js')
+const { Colors } = require('../../utils/canvas')
+const math = require('mathjs')
module.exports = {
config: {
- name: "calculate",
- usage: "calculate",
- aliases: ["calc", "solve"],
- description: "Calculate shits",
+ name: 'calculate',
+ usage: 'calculate',
+ aliases: ['calc', 'solve'],
+ description: 'Calculate shits',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
+ async run (client, message, args) {
if (!args[0]) {
return message.channel.send(
- "You have to specify what you would like to count on!"
- );
+ 'You have to specify what you would like to count on!'
+ )
}
- const mathEquation = args.join(" ");
+ const mathEquation = args.join(' ')
- let answer;
+ let answer
try {
- answer = math.evaluate(mathEquation);
+ answer = math.evaluate(mathEquation)
} catch (e) {
- return message.channel.send("Invalid mathematical calculation!");
+ return message.channel.send('Invalid mathematical calculation!')
}
- const roleColor = message.guild.me.roles.highest.hexColor;
+ const roleColor = message.guild.me.roles.highest.hexColor
const calcEmbed = new MessageEmbed()
- .setColor(roleColor === "#000000" ? Colors.CUSTOM : roleColor)
- .setTitle("Math Calculation")
+ .setColor(roleColor === '#000000' ? Colors.CUSTOM : roleColor)
+ .setTitle('Math Calculation')
.setDescription(
`**Calculation:**\n\`\`\`\n${mathEquation}\n\`\`\`**Result:**\n\`\`\`\n${answer}\n\`\`\``
)
@@ -39,8 +39,8 @@ module.exports = {
`Requested by ${message.author.tag}`,
message.author.avatarURL({ dynamic: true })
)
- .setTimestamp();
+ .setTimestamp()
- message.channel.send(calcEmbed);
- },
-};
+ message.channel.send(calcEmbed)
+ }
+}
diff --git a/commands/util/createInvite.js b/commands/util/createInvite.js
index 82bfd77..8d05f65 100644
--- a/commands/util/createInvite.js
+++ b/commands/util/createInvite.js
@@ -1,41 +1,41 @@
-const { MessageEmbed } = require("discord.js");
+const { MessageEmbed } = require('discord.js')
module.exports = {
config: {
- name: "createInvite",
- usage: "createInvite",
+ name: 'createInvite',
+ usage: 'createInvite',
aliases: [],
- description: "Create invite for current channel",
+ description: 'Create invite for current channel',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- let channel = message.guild.channels.cache.get(message.channel.id);
- let inviteOption = {
+ async run (client, message, args) {
+ const channel = message.guild.channels.cache.get(message.channel.id)
+ const inviteOption = {
temporary: false,
maxAge: 0,
maxUses: 1,
unique: false,
- reason: "Generated by wrose",
- };
- let invite = await channel.createInvite(inviteOption);
+ reason: 'Generated by wrose'
+ }
+ const invite = await channel.createInvite(inviteOption)
message.channel.send({
embed: {
color: 3447003,
fields: [
{
- name: "Invite generated",
- value: "https://discord.com/invite/" + invite.code,
- },
+ name: 'Invite generated',
+ value: 'https://discord.com/invite/' + invite.code
+ }
],
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
- },
-};
+ size: 1024
+ })
+ }
+ }
+ })
+ }
+}
diff --git a/commands/util/translate.js b/commands/util/translate.js
index aaee893..7191178 100644
--- a/commands/util/translate.js
+++ b/commands/util/translate.js
@@ -1,40 +1,40 @@
-const translate = require("translate-google");
-const { blueMessage } = require("../../utils/message");
+const translate = require('translate-google')
+const { blueMessage } = require('../../utils/message')
module.exports = {
config: {
- name: "translate",
- usage: "translate",
+ name: 'translate',
+ usage: 'translate',
aliases: [],
- description: "translate a word to another language",
+ description: 'translate a word to another language',
ownerOnly: false,
- enabled: true,
+ enabled: true
},
- async run(client, message, args) {
- await message.channel.send("Input a text you want to translate");
- let collected = await message.channel.awaitMessages(
+ async run (client, message, args) {
+ await message.channel.send('Input a text you want to translate')
+ const collected = await message.channel.awaitMessages(
(m) => m.author.id === message.author.id,
{
max: 1,
- time: 30000,
+ time: 30000
}
- );
- let text = collected.first().content;
- if (!text) return message.reply("Stop spamming");
+ )
+ const text = collected.first().content
+ if (!text) return message.reply('Stop spamming')
await blueMessage(
message,
- "Available language codes",
- "ar, az, be, bg, bn, bs, cs, da, de, dz, el, en, en-gb, en-us, es, et, fa, fi, fil, fr, he, hi, hr, hu, hy, id, is, it, ja, ka, kk, km, ko, lb, lo, lt, lv, mk, mn, ms, my, ne, no, pl, pt, ro, ru, sk, sl, sq, sr, sv, sw, th, tk, uk, vi, zh"
- );
- let collect = await message.channel.awaitMessages(
+ 'Available language codes',
+ 'ar, az, be, bg, bn, bs, cs, da, de, dz, el, en, en-gb, en-us, es, et, fa, fi, fil, fr, he, hi, hr, hu, hy, id, is, it, ja, ka, kk, km, ko, lb, lo, lt, lv, mk, mn, ms, my, ne, no, pl, pt, ro, ru, sk, sl, sq, sr, sv, sw, th, tk, uk, vi, zh'
+ )
+ const collect = await message.channel.awaitMessages(
(m) => m.author.id === message.author.id,
{
max: 1,
- time: 30000,
+ time: 30000
}
- );
- let code = collect.first().content;
- if (!code) return message.reply("Stop spamming");
- let translated = await translate(text, { to: code });
- blueMessage(message, "Translated to " + code, translated);
- },
-};
+ )
+ const code = collect.first().content
+ if (!code) return message.reply('Stop spamming')
+ const translated = await translate(text, { to: code })
+ blueMessage(message, 'Translated to ' + code, translated)
+ }
+}
diff --git a/events/guildCreate.js b/events/guildCreate.js
index 5fd9917..dc8fa9b 100644
--- a/events/guildCreate.js
+++ b/events/guildCreate.js
@@ -1,6 +1,6 @@
-let guildSettings = require("../model/guildSettingsModel");
+const guildSettings = require('../model/guildSettingsModel')
module.exports = client => {
- return function(guild) {
+ return function (guild) {
// console.log(guild.id);
// let guildId = guild.id;
// let guildSettings = {
@@ -10,6 +10,6 @@ module.exports = client => {
// ignoredChannels: []
// };
// guildSettingsModel.addNewGuild(guildId, guildSettings);
- guildSettings.addNewGuild(guild);
- };
-};
+ guildSettings.addNewGuild(guild)
+ }
+}
diff --git a/events/guildMemberAdd.js b/events/guildMemberAdd.js
index 0e20607..0dd5154 100644
--- a/events/guildMemberAdd.js
+++ b/events/guildMemberAdd.js
@@ -1,58 +1,58 @@
-const path = require("path");
-const Discord = require("discord.js");
-const Canvas = require("discord-canvas");
+const path = require('path')
+const Discord = require('discord.js')
+const Canvas = require('discord-canvas')
module.exports = (client) => {
return async function (member) {
const channel = member.guild.channels.cache.find(
- (ch) => ch.name === "new-member"
- );
- if (!channel) return;
+ (ch) => ch.name === 'new-member'
+ )
+ if (!channel) return
const image = await new Canvas.Welcome()
.setUsername(member.user.username)
.setDiscriminator(member.user.discriminator)
.setMemberCount(member.guild.members.cache.size)
.setGuildName(member.guild.name)
.setAvatar(
- member.user.avatarURL({ format: "png", dynamic: true, size: 1024 })
+ member.user.avatarURL({ format: 'png', dynamic: true, size: 1024 })
)
- .setColor("border", "#8015EA")
- .setColor("username-box", "#8015EA")
- .setColor("discriminator-box", "#8015EA")
- .setColor("message-box", "#8015EA")
- .setColor("title", "#8015EA")
- .setColor("avatar", "#8015EA")
+ .setColor('border', '#8015EA')
+ .setColor('username-box', '#8015EA')
+ .setColor('discriminator-box', '#8015EA')
+ .setColor('message-box', '#8015EA')
+ .setColor('title', '#8015EA')
+ .setColor('avatar', '#8015EA')
// .setBackground("")
- .toAttachment();
+ .toAttachment()
const attachment = new Discord.MessageAttachment(
image.toBuffer(),
- "goodbye-image.png"
- );
- channel.send(attachment);
- if (!process.env.capcha) return;
- if (process.env.capcha === "true") {
- let msg = await member.send("react to this");
- msg.react("✅").then(() => msg.react("👎"));
+ 'goodbye-image.png'
+ )
+ channel.send(attachment)
+ if (!process.env.capcha) return
+ if (process.env.capcha === 'true') {
+ const msg = await member.send('react to this')
+ msg.react('✅').then(() => msg.react('👎'))
const filter = (reaction, user) => {
- return ["✅"].includes(reaction.emoji.name) && user.id === member.id;
- };
+ return ['✅'].includes(reaction.emoji.name) && user.id === member.id
+ }
msg
- .awaitReactions(filter, { max: 1, time: 60000, errors: ["time"] })
+ .awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(async (collected) => {
- const reaction = collected.first();
+ const reaction = collected.first()
- if (reaction.emoji.name === "✅") {
- msg.reply("you reacted with a ✅.");
+ if (reaction.emoji.name === '✅') {
+ msg.reply('you reacted with a ✅.')
} else {
- msg.reply("you reacted with a thumbs down.");
- await member.kick();
+ msg.reply('you reacted with a thumbs down.')
+ await member.kick()
}
})
.catch((collected) => {
- msg.reply("you reacted with neither a thumbs up, nor a thumbs down.");
- });
+ msg.reply('you reacted with neither a thumbs up, nor a thumbs down.')
+ })
}
- };
-};
+ }
+}
diff --git a/events/guildMemberRemove.js b/events/guildMemberRemove.js
index 16eb8f2..5fe9739 100644
--- a/events/guildMemberRemove.js
+++ b/events/guildMemberRemove.js
@@ -1,32 +1,32 @@
-const Discord = require("discord.js");
-const Canvas = require("discord-canvas");
+const Discord = require('discord.js')
+const Canvas = require('discord-canvas')
module.exports = (client) => {
return async function (member) {
const channel = member.guild.channels.cache.find(
- (ch) => ch.name === "new-member"
- );
- if (!channel) return;
+ (ch) => ch.name === 'new-member'
+ )
+ if (!channel) return
const image = await new Canvas.Goodbye()
.setUsername(member.user.username)
.setDiscriminator(member.user.discriminator)
.setMemberCount(member.guild.members.cache.size)
.setGuildName(member.guild.name)
.setAvatar(
- member.user.avatarURL({ format: "png", dynamic: true, size: 1024 })
+ member.user.avatarURL({ format: 'png', dynamic: true, size: 1024 })
)
- .setColor("border", "#8015EA")
- .setColor("username-box", "#8015EA")
- .setColor("discriminator-box", "#8015EA")
- .setColor("message-box", "#8015EA")
- .setColor("title", "#8015EA")
- .setColor("avatar", "#8015EA")
+ .setColor('border', '#8015EA')
+ .setColor('username-box', '#8015EA')
+ .setColor('discriminator-box', '#8015EA')
+ .setColor('message-box', '#8015EA')
+ .setColor('title', '#8015EA')
+ .setColor('avatar', '#8015EA')
// .setBackground("")
- .toAttachment();
+ .toAttachment()
const attachment = new Discord.MessageAttachment(
image.toBuffer(),
- "goodbye-image.png"
- );
- channel.send(attachment);
- };
-};
+ 'goodbye-image.png'
+ )
+ channel.send(attachment)
+ }
+}
diff --git a/events/message.js b/events/message.js
index 7fce29c..8eb1227 100644
--- a/events/message.js
+++ b/events/message.js
@@ -1,82 +1,79 @@
-let util = require("../utils/utility");
-let config = require("../config/config.json");
+const util = require('../utils/utility')
+const config = require('../config/config.json')
module.exports = (client) => {
return async function (message) {
- //let message.guild.id = message.guild.id;
+ // let message.guild.id = message.guild.id;
if (message.guild) {
- let guildConfig = client.guildSettings.get(message.guild.id);
- let prefix = "";
+ const guildConfig = client.guildSettings.get(message.guild.id)
+ let prefix = ''
if (guildConfig) {
- prefix = guildConfig.prefix.toString();
+ prefix = guildConfig.prefix.toString()
} else {
- prefix = config.prefix;
+ prefix = config.prefix
}
- //args definition
- if (prefix.length === 0) return;
- const args = message.content.slice(prefix.length).trim().split(/ +/g);
- const cmd = args.shift().toLowerCase();
- //message filter
+ // args definition
+ if (prefix.length === 0) return
+ const args = message.content.slice(prefix.length).trim().split(/ +/g)
+ const cmd = args.shift().toLowerCase()
+ // message filter
- if (message.author.bot) return;
- //ignore message when it's in ignored channels
+ if (message.author.bot) return
+ // ignore message when it's in ignored channels
if (guildConfig && guildConfig.ignoredChannels) {
- for (let ignoredChannel of guildConfig.ignoredChannels) {
+ for (const ignoredChannel of guildConfig.ignoredChannels) {
if (message.channel.id === ignoredChannel) {
- return;
+ return
}
}
}
- //delete message when it's in delete channels
+ // delete message when it's in delete channels
if (
guildConfig &&
message.channel.id === guildConfig.musicTextChannel &&
!message.content.startsWith(prefix)
) {
- //console.log(message.channel.id === musicTextChannel[key]);
+ // console.log(message.channel.id === musicTextChannel[key]);
- await message.delete();
+ await message.delete()
}
- //command execution
- if (cmd.length === 0) return;
+ // command execution
+ if (cmd.length === 0) return
if (message.content.startsWith(prefix)) {
- let aliases = client.aliases;
- let commands = client.commands;
- let author = message.author;
- let ownerID = client.config.get("ownerID");
+ const aliases = client.aliases
+ const commands = client.commands
+ const author = message.author
+ const ownerID = client.config.get('ownerID')
if (commands.has(cmd)) {
- if (commands.get(cmd).config.enabled === false) return;
- if (commands.get(cmd).config.ownerOnly === true && author.id !== ownerID){
- return message.channel.send("You are not the owner");
- }
- else {
- commands.get(cmd).run(client, message, args);
+ if (commands.get(cmd).config.enabled === false) return
+ if (commands.get(cmd).config.ownerOnly === true && author.id !== ownerID) {
+ return message.channel.send('You are not the owner')
+ } else {
+ commands.get(cmd).run(client, message, args)
}
} else if (aliases.has(cmd)) {
- if (aliases.get(cmd).config === false) return;
- if (aliases.get(cmd).config.ownerOnly === true &&author.id !== ownerID)
- return;
- else {
- aliases.get(cmd).run(client, message, args);
- }
+ if (aliases.get(cmd).config === false) return
+ if (aliases.get(cmd).config.ownerOnly === true && author.id !== ownerID) { return } else {
+ aliases.get(cmd).run(client, message, args)
+ }
}
}
if (message.mentions.users.has(client.user.id)) {
- message.channel.send("My prefix is " + prefix);
+ message.channel.send('My prefix is ' + prefix)
}
- //misc utilities
+ // misc utilities
if (client.awayuser && message.mentions.users.first()) {
- let mentionedUser = message.mentions.users.first().username;
+ const mentionedUser = message.mentions.users.first().username
if (
message.mentions.users.has(client.awayuser.get(mentionedUser).user.id)
) {
- util.sendShit(message);
+ util.sendShit(message)
}
}
}
- };
-};
+ }
+}
diff --git a/events/ready.js b/events/ready.js
index 046729c..8c93167 100644
--- a/events/ready.js
+++ b/events/ready.js
@@ -1,39 +1,39 @@
-let Discord = require("discord.js");
-let guildSettings = require("../model/guildSettingsModel");
+const Discord = require('discord.js')
+const guildSettings = require('../model/guildSettingsModel')
module.exports = (client) => {
return async function () {
- client.guildSettings = new Discord.Collection();
- client.config = new Discord.Collection();
- let config = require("../config/config.json");
- for (let key in config) {
- client.config.set(key, config[key]);
+ client.guildSettings = new Discord.Collection()
+ client.config = new Discord.Collection()
+ const config = require('../config/config.json')
+ for (const key in config) {
+ client.config.set(key, config[key])
}
- console.log("done loading");
+ console.log('done loading')
setInterval(() => {
client.user.setPresence({
- activity: { name: "on " + client.ws.ping + " ms" },
- status: "dnd",
- });
- }, 10000);
- client.queue = new Discord.Collection();
- client.mute = new Discord.Collection();
- client.games = new Discord.Collection();
- client.warewolf = new Discord.Collection();
- //let data = await guildSettings.queryGuildSettings(null);
- //console.log(data);
- let guilds = client.guilds.cache;
+ activity: { name: 'on ' + client.ws.ping + ' ms' },
+ status: 'dnd'
+ })
+ }, 10000)
+ client.queue = new Discord.Collection()
+ client.mute = new Discord.Collection()
+ client.games = new Discord.Collection()
+ client.warewolf = new Discord.Collection()
+ // let data = await guildSettings.queryGuildSettings(null);
+ // console.log(data);
+ const guilds = client.guilds.cache
guilds.forEach(async (guild) => {
- let data = await guildSettings.queryGuildSettings(guild.id);
- if (!data) return;
+ const data = await guildSettings.queryGuildSettings(guild.id)
+ if (!data) return
if (data) {
data.gameConfig = {
category: 27,
- categoryName: "Animals",
- difficulty: "hard",
- numberQuestions: 5,
- };
- await client.guildSettings.set(data.guildID, data);
+ categoryName: 'Animals',
+ difficulty: 'hard',
+ numberQuestions: 5
+ }
+ await client.guildSettings.set(data.guildID, data)
}
- });
- };
-};
+ })
+ }
+}
diff --git a/events/voiceStateUpdate.js b/events/voiceStateUpdate.js
index 379d484..bcd85ae 100644
--- a/events/voiceStateUpdate.js
+++ b/events/voiceStateUpdate.js
@@ -2,6 +2,8 @@ const muteModel = require("../model/mute.model");
module.exports = (client) => {
return async function (oldState, newState) {
const serverQueue = client.queue.get(newState.guild.id);
+ if (newState.id === client.user.id && serverQueue)
+ return client.queue.delete(newState.guild.id);
if (serverQueue) {
if (serverQueue.voiceChannel.members.size < 2) {
setTimeout(() => {
@@ -18,7 +20,6 @@ module.exports = (client) => {
};
const user = await muteModel.exist(userData);
let i = 0;
- console.log(newState.id + `changed ${i++}`);
if (user.length !== 0) {
if (!newState.guild.me.hasPermission("MUTE_MEMBERS")) return;
if (newState.serverMute === false) newState.setMute(true);
diff --git a/handler/commandHandler.js b/handler/commandHandler.js
index 164e140..f82b6f2 100644
--- a/handler/commandHandler.js
+++ b/handler/commandHandler.js
@@ -1,34 +1,34 @@
-const fs = require("fs");
-const config = require("../config/config.json");
-const Discord = require("discord.js");
-const ascii = require("ascii-table");
-let table = new ascii("Commands");
-table.setHeading("Command", "Active status");
+const fs = require('fs')
+const config = require('../config/config.json')
+const Discord = require('discord.js')
+const ascii = require('ascii-table')
+const table = new ascii('Commands')
+table.setHeading('Command', 'Active status')
module.exports = async (client, message) => {
- client.commands = new Discord.Collection();
- client.aliases = new Discord.Collection();
- client.categories = fs.readdirSync("./commands/");
+ client.commands = new Discord.Collection()
+ client.aliases = new Discord.Collection()
+ client.categories = fs.readdirSync('./commands/')
- fs.readdirSync("./commands/").forEach(dir => {
+ fs.readdirSync('./commands/').forEach(dir => {
const command = fs.readdirSync(`./commands/${dir}/`).filter(async file => {
- file.endsWith(".js");
+ file.endsWith('.js')
var filename = file
- .split(".")
+ .split('.')
.slice(0, -1)
- .join(".");
- let cmdObj = require("../commands/" + dir + "/" + filename);
- client.commands.set(filename.toLowerCase(), cmdObj);
- if (cmdObj.config.aliases) {
- for (let i in cmdObj.config.aliases) {
- client.aliases.set(cmdObj.config.aliases[i], cmdObj);
+ .join('.')
+ const cmdObj = require('../commands/' + dir + '/' + filename)
+ client.commands.set(filename.toLowerCase(), cmdObj)
+ if (cmdObj.config.aliases) {
+ for (const i in cmdObj.config.aliases) {
+ client.aliases.set(cmdObj.config.aliases[i], cmdObj)
}
}
table.addRow(
client.commands.get(filename.toLowerCase()).config.name,
- client.commands.get(filename.toLowerCase()).config.enabled ? "✅" : "❌"
- );
- });
- });
- //commandModel.table = table.toString();
- console.log(table.toString());
-};
+ client.commands.get(filename.toLowerCase()).config.enabled ? '✅' : '❌'
+ )
+ })
+ })
+ // commandModel.table = table.toString();
+ console.log(table.toString())
+}
diff --git a/handler/eventHandler.js b/handler/eventHandler.js
index f5bf563..eb0faae 100644
--- a/handler/eventHandler.js
+++ b/handler/eventHandler.js
@@ -1,16 +1,16 @@
-const fs = require("fs");
-const path = require("path");
+const fs = require('fs')
+const path = require('path')
module.exports = client => {
- const eventPath = "./events/";
- let events = fs.readdirSync(eventPath).filter(file => file.endsWith(".js"));
+ const eventPath = './events/'
+ const events = fs.readdirSync(eventPath).filter(file => file.endsWith('.js'))
events.forEach(event => {
- event = event.replace(/\.js$/i, "");
+ event = event.replace(/\.js$/i, '')
// if (event === 'ready') {
// let eventObj=require(path.resolve(eventPath, event))(client);
// client.on(event, eventObj)
// }
// client.on(event, require(path.resolve(eventPath, event)));
- let eventObj = require(path.resolve(eventPath, event))(client);
- client.on(event, eventObj);
- });
-};
+ const eventObj = require(path.resolve(eventPath, event))(client)
+ client.on(event, eventObj)
+ })
+}
diff --git a/index.js b/index.js
index dae5e57..1b88949 100644
--- a/index.js
+++ b/index.js
@@ -1,25 +1,25 @@
-const Discord = require("discord.js");
+const Discord = require('discord.js')
const client = new Discord.Client({
disableEveryone: true,
- fetchAllMembers: true,
-});
-const config = require("./config/config.json");
-const mongoose = require("mongoose");
-const logs = require("discord-logs");
-logs(client);
-process.env.NODE_PATH = __dirname;
-require("dotenv").config();
-const eventHandler = require("./handler/eventHandler.js")(client);
-const commandHandler = require("./handler/commandHandler.js")(client);
-client.login(process.env.token);
+ fetchAllMembers: true
+})
+const config = require('./config/config.json')
+const mongoose = require('mongoose')
+const logs = require('discord-logs')
+logs(client)
+process.env.NODE_PATH = __dirname
+require('dotenv').config()
+const eventHandler = require('./handler/eventHandler.js')(client)
+const commandHandler = require('./handler/commandHandler.js')(client)
+client.login(process.env.token)
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
- useCreateIndex: true,
+ useCreateIndex: true
})
.then(() => {
- console.log("CONNECTED DIT CON ME MAY");
- });
+ console.log('CONNECTED DIT CON ME MAY')
+ })
diff --git a/model/gameModel.js b/model/gameModel.js
index 27c0cb9..96266d0 100644
--- a/model/gameModel.js
+++ b/model/gameModel.js
@@ -1,191 +1,193 @@
-const Discord = require("discord.js");
-const questionsModel = require("./questionsModel.js");
+const Discord = require('discord.js')
+const questionsModel = require('./questionsModel.js')
class Game {
- constructor(config) {
+ constructor (config) {
this.config = {
category: undefined,
- categoryName: "ALL",
- difficulty: "easy",
+ categoryName: 'ALL',
+ difficulty: 'easy',
numberQuestions: 15
- };
- Object.assign(this.config, config);
+ }
+ Object.assign(this.config, config)
}
- async init(players) {
- if (players.length == 0) return;
- this.state = "init";
- this.currentQuestion = 1;
- this.players = new Discord.Collection();
- for (let user of players) {
+ async init (players) {
+ if (players.length == 0) return
+ this.state = 'init'
+ this.currentQuestion = 1
+ this.players = new Discord.Collection()
+ for (const user of players) {
this.players.set(user.id, {
user,
alive: true,
currentQuestion: 1
- });
+ })
}
- this.questions = await questionsModel.getQuestions(this.config);
+ this.questions = await questionsModel.getQuestions(this.config)
}
- getTopPlayer() {
- this.players.sort((a, b) => b.currentQuestion - a.currentQuestion);
- return this.players;
+
+ getTopPlayer () {
+ this.players.sort((a, b) => b.currentQuestion - a.currentQuestion)
+ return this.players
}
- async _end() {
- this.state = "end";
- let embed = getEndEmbed(this.getTopPlayer());
- this.message.channel.send(embed);
+
+ async _end () {
+ this.state = 'end'
+ const embed = getEndEmbed(this.getTopPlayer())
+ this.message.channel.send(embed)
}
- async _play(index) {
- if (index > this.config.numberQuestions) return _end();
+
+ async _play (index) {
+ if (index > this.config.numberQuestions) return _end()
let editEmbed = new Discord.MessageEmbed().setTitle(
- `:computer: LOADING QUESTION....`
- );
- const msg = await this.message.channel.send(editEmbed);
- await msg.react("🇦");
- await msg.react("🇧");
- await msg.react("🇨");
- await msg.react("🇩");
+ ':computer: LOADING QUESTION....'
+ )
+ const msg = await this.message.channel.send(editEmbed)
+ await msg.react('🇦')
+ await msg.react('🇧')
+ await msg.react('🇨')
+ await msg.react('🇩')
- let question = this.questions[index];
- let answer = question.answer;
+ const question = this.questions[index]
+ const answer = question.answer
editEmbed = new Discord.MessageEmbed()
- .setColor("#53b512")
- .setTitle("Câu hỏi số " + index)
+ .setColor('#53b512')
+ .setTitle('Câu hỏi số ' + index)
.setTimestamp()
.setFooter(
- "Ai la trieu phu",
- "https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG"
+ 'Ai la trieu phu',
+ 'https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG'
)
.setDescription(question.question)
- .addField("Đáp án 🇦", question.A, true)
- .addField("Đáp án 🇧", question.B, true)
- .addField("\u200B", "\u200B")
- .addField("Đáp án 🇨", question.C, true)
- .addField("Đáp án 🇩", question.D, true);
+ .addField('Đáp án 🇦', question.A, true)
+ .addField('Đáp án 🇧', question.B, true)
+ .addField('\u200B', '\u200B')
+ .addField('Đáp án 🇨', question.C, true)
+ .addField('Đáp án 🇩', question.D, true)
- await msg.edit(editEmbed);
+ await msg.edit(editEmbed)
- let interval;
- let time = 30;
- let cdMsg = await this.message.channel.send(`Time left: ${time} seconds`);
- interval = setInterval(function() {
- cdMsg.edit(`Time left: ${time} seconds`);
- time--;
+ let interval
+ let time = 30
+ const cdMsg = await this.message.channel.send(`Time left: ${time} seconds`)
+ interval = setInterval(function () {
+ cdMsg.edit(`Time left: ${time} seconds`)
+ time--
if (time < 0) {
- cdMsg.delete();
- clearInterval(interval);
+ cdMsg.delete()
+ clearInterval(interval)
}
- }, 1000);
- //reset all voted
- this.players.forEach(function(player) {
- player.voted = null;
- });
+ }, 1000)
+ // reset all voted
+ this.players.forEach(function (player) {
+ player.voted = null
+ })
const filter = (reaction, user) => {
- let player = this.players.get(user.id);
- if (user.bot || (player && (player.voted || !player.alive)) || !player)
- return false;
- if (!["🇦", "🇧", "🇨", "🇩"].includes(reaction.emoji.name)) return false;
- player.voted = reaction.emoji.name;
- this.message.channel.send(`${user} voted ${reaction.emoji.name}`);
- return true;
- };
+ const player = this.players.get(user.id)
+ if (user.bot || (player && (player.voted || !player.alive)) || !player) { return false }
+ if (!['🇦', '🇧', '🇨', '🇩'].includes(reaction.emoji.name)) return false
+ player.voted = reaction.emoji.name
+ this.message.channel.send(`${user} voted ${reaction.emoji.name}`)
+ return true
+ }
- await msg.awaitReactions(filter, { time: time * 1000 });
+ await msg.awaitReactions(filter, { time: time * 1000 })
- this.players.forEach(function(player) {
- if (!player.alive) return;
- let userAnswer = player.voted;
- player.currentQuestion = index;
+ this.players.forEach(function (player) {
+ if (!player.alive) return
+ let userAnswer = player.voted
+ player.currentQuestion = index
switch (userAnswer) {
- case "🇦":
- userAnswer = "A";
- break;
- case "🇧":
- userAnswer = "B";
- break;
- case "🇨":
- userAnswer = "C";
- break;
- case "🇩":
- userAnswer = "D";
- break;
+ case '🇦':
+ userAnswer = 'A'
+ break
+ case '🇧':
+ userAnswer = 'B'
+ break
+ case '🇨':
+ userAnswer = 'C'
+ break
+ case '🇩':
+ userAnswer = 'D'
+ break
default:
- userAnswer = null;
+ userAnswer = null
}
- if (userAnswer != answer) player.alive = false;
- });
- let alivePlayers = this.players.filter(player => player.alive);
- let embed = getAnswerEmbed(answer);
- let answerMsg = await this.message.channel.send(embed);
- setTimeout(function() {
+ if (userAnswer != answer) player.alive = false
+ })
+ const alivePlayers = this.players.filter(player => player.alive)
+ const embed = getAnswerEmbed(answer)
+ const answerMsg = await this.message.channel.send(embed)
+ setTimeout(function () {
msg.edit(
new Discord.MessageEmbed()
.setTitle(`Question ${index} has been hidden :V`)
- .setColor("NAVY")
- );
- answerMsg.delete();
- }, 10000);
+ .setColor('NAVY')
+ )
+ answerMsg.delete()
+ }, 10000)
await this.message.channel.send(
new Discord.MessageEmbed()
- .setColor("#0099ff")
- .setTitle("Người chơi tiếp: " + alivePlayers.size)
+ .setColor('#0099ff')
+ .setTitle('Người chơi tiếp: ' + alivePlayers.size)
.setTimestamp()
.setFooter(
- "Ai la trieu phu",
- "https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG"
+ 'Ai la trieu phu',
+ 'https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG'
)
.addField(
- "Danh sách",
+ 'Danh sách',
alivePlayers.size > 0
- ? alivePlayers.map(e => e.user).join("\n")
+ ? alivePlayers.map(e => e.user).join('\n')
: "Đéo có ai :'("
)
- );
+ )
setTimeout(() => {
- if (alivePlayers.size == 0) this._end();
- else this._play(index + 1);
- }, 4000);
+ if (alivePlayers.size == 0) this._end()
+ else this._play(index + 1)
+ }, 4000)
}
- async play(message) {
- this.message = message;
- this.state = "playing";
- this._play(1);
+ async play (message) {
+ this.message = message
+ this.state = 'playing'
+ this._play(1)
}
}
-module.exports = Game;
+module.exports = Game
-function getAnswerEmbed(answer) {
- const imgFile = new Discord.MessageAttachment("./assets/" + answer + ".png");
+function getAnswerEmbed (answer) {
+ const imgFile = new Discord.MessageAttachment('./assets/' + answer + '.png')
return new Discord.MessageEmbed()
- .setColor("#a3ff99")
- .setTitle("Câu trả lời của chúng tôi là")
+ .setColor('#a3ff99')
+ .setTitle('Câu trả lời của chúng tôi là')
.setTimestamp()
.setFooter(
- "Ai la trieu phu",
- "https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG"
+ 'Ai la trieu phu',
+ 'https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG'
)
.attachFiles(imgFile)
- .setImage("attachment://" + answer + ".png");
+ .setImage('attachment://' + answer + '.png')
}
-function getEndEmbed(playerList) {
- playerList = [...playerList.values()];
- const emojis = [0, 0, 0];
- for (let i of playerList) emojis.push(":poop:");
- emojis[0] = ":first_place:";
- emojis[1] = ":second_place:";
- emojis[2] = ":third_place:";
+function getEndEmbed (playerList) {
+ playerList = [...playerList.values()]
+ const emojis = [0, 0, 0]
+ for (const i of playerList) emojis.push(':poop:')
+ emojis[0] = ':first_place:'
+ emojis[1] = ':second_place:'
+ emojis[2] = ':third_place:'
playerList = playerList.map(
(elem, index) => `${emojis[index]} ${elem.user} ${elem.currentQuestion} `
- );
+ )
return new Discord.MessageEmbed()
- .setColor("#dbdb2c")
- .setTitle("END GAME")
+ .setColor('#dbdb2c')
+ .setTitle('END GAME')
.setTimestamp()
.setFooter(
- "Ai la trieu phu",
- "https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG"
+ 'Ai la trieu phu',
+ 'https://upload.wikimedia.org/wikipedia/en/f/fe/Vietnam_millionaire.JPG'
)
- .addField("Rank: ", playerList.join(" \n "));
+ .addField('Rank: ', playerList.join(' \n '))
}
diff --git a/model/guildSettingsModel.js b/model/guildSettingsModel.js
index 7ee2b45..bd7b4ed 100644
--- a/model/guildSettingsModel.js
+++ b/model/guildSettingsModel.js
@@ -1,5 +1,5 @@
-let mongoose = require("mongoose");
-let guildSettingsSchema = mongoose.Schema({
+const mongoose = require('mongoose')
+const guildSettingsSchema = mongoose.Schema({
guildID: {
type: String,
unique: true
@@ -10,72 +10,72 @@ let guildSettingsSchema = mongoose.Schema({
prefix: {
type: String,
max: 1,
- default: "."
+ default: '.'
},
musicTextChannel: {
- type: String,
+ type: String
},
musicVoiceChannel: {
- type: String,
+ type: String
},
ignoredChannels: []
-});
-var guildSettings = mongoose.model("guildSettings", guildSettingsSchema);
-function updateMusicChannel(data) {
+})
+var guildSettings = mongoose.model('guildSettings', guildSettingsSchema)
+function updateMusicChannel (data) {
guildSettings.findOneAndUpdate(
{ guildID: data.guildID },
{
musicTextChannel: data.musicTextChannel,
musicVoiceChannel: data.musicVoiceChannel
},
- function(error, doc, res) {
- if (error) console.log(error);
- if (res) console.log("done");
+ function (error, doc, res) {
+ if (error) console.log(error)
+ if (res) console.log('done')
}
- );
+ )
}
-function updateIgnoredChannels(data) {
- guildSettings.findOne({ guildID: data.guildID }, function(error, result) {
- if (error) console.log(error);
+function updateIgnoredChannels (data) {
+ guildSettings.findOne({ guildID: data.guildID }, function (error, result) {
+ if (error) console.log(error)
if (result) {
- result.ignoredChannels.push(data.ignoredChannel);
+ result.ignoredChannels.push(data.ignoredChannel)
result.save().then(() => {
- console.log("saved ignore channel\n" + result);
- });
+ console.log('saved ignore channel\n' + result)
+ })
}
- });
+ })
}
-async function addNewGuild(guild) {
- guildSettings.findOne({ guildID: guild.id }, async function(error, result) {
- if (error) console.log(error);
- if (result) return;
+async function addNewGuild (guild) {
+ guildSettings.findOne({ guildID: guild.id }, async function (error, result) {
+ if (error) console.log(error)
+ if (result) return
if (!result) {
- let newGuild = new guildSettings({
+ const newGuild = new guildSettings({
guildID: guild.id,
guildName: guild.name,
musicVoiceChannel: null,
musicTextChannel: null
- });
- await newGuild.save().then(function(err) {
- if (err) console.log(err);
- console.log("saved new guild\n" + newGuild);
- });
+ })
+ await newGuild.save().then(function (err) {
+ if (err) console.log(err)
+ console.log('saved new guild\n' + newGuild)
+ })
}
- });
+ })
}
-async function queryGuildSettings(guildID) {
- let result = await guildSettings.findOne({ guildID: guildID }).exec();
- return result;
+async function queryGuildSettings (guildID) {
+ const result = await guildSettings.findOne({ guildID: guildID }).exec()
+ return result
}
-async function updatePrefix(prefix, guildID) {
- let a = await guildSettings.findOneAndUpdate(
+async function updatePrefix (prefix, guildID) {
+ const a = await guildSettings.findOneAndUpdate(
{ guildID: guildID },
{
prefix: prefix
}
- );
- return a;
+ )
+ return a
}
module.exports = {
updateIgnoredChannels,
@@ -83,4 +83,4 @@ module.exports = {
addNewGuild,
queryGuildSettings,
updatePrefix
-};
+}
diff --git a/model/musicData.js b/model/musicData.js
index 86e858c..05aecff 100644
--- a/model/musicData.js
+++ b/model/musicData.js
@@ -1,18 +1,18 @@
-let mongoose = require("mongoose");
-let musicSchema = mongoose.Schema({
+const mongoose = require('mongoose')
+const musicSchema = mongoose.Schema({
name: {
- type: String,
+ type: String
},
count: {
type: Number,
- default: 1,
+ default: 1
},
guildID: {
- type: String,
- },
-});
-var music = mongoose.model("music", musicSchema);
-async function updateCount(title, guildID) {
+ type: String
+ }
+})
+var music = mongoose.model('music', musicSchema)
+async function updateCount (title, guildID) {
music.findOne({ name: title, guildID: guildID }, async function (
error,
result
@@ -22,32 +22,32 @@ async function updateCount(title, guildID) {
{ name: title, guildID: guildID },
{ $inc: { count: 1 } },
async function (error, doc, res) {
- if (error) console.log(error);
+ if (error) console.log(error)
}
- );
+ )
}
if (!result) {
- let song = new music({
+ const song = new music({
name: title,
- guildID: guildID,
- });
+ guildID: guildID
+ })
await song.save().then(() => {
- console.log("saved");
- });
+ console.log('saved')
+ })
}
- if (error) console.log(error);
- });
+ if (error) console.log(error)
+ })
}
-async function getSongs() {
- let songs = await music.find({}).sort({ count: -1 }).limit(10).exec();
- return songs;
+async function getSongs () {
+ const songs = await music.find({}).sort({ count: -1 }).limit(10).exec()
+ return songs
}
const guildTop = async (guildID) => {
- let songs = await music
+ const songs = await music
.find({ guildID: guildID })
.sort({ count: -1 })
.limit(10)
- .exec();
- return songs;
-};
-module.exports = { updateCount, getSongs, guildTop };
+ .exec()
+ return songs
+}
+module.exports = { updateCount, getSongs, guildTop }
diff --git a/model/mute.model.js b/model/mute.model.js
index e5c5eb0..67d7dab 100644
--- a/model/mute.model.js
+++ b/model/mute.model.js
@@ -1,42 +1,42 @@
-let mongoose = require("mongoose");
-const { string } = require("mathjs");
-const { Message } = require("discord.js");
-let muteSchema = mongoose.Schema({
+const mongoose = require('mongoose')
+const { string } = require('mathjs')
+const { Message } = require('discord.js')
+const muteSchema = mongoose.Schema({
username: {
- type: String,
+ type: String
},
id: {
- type: String,
+ type: String
},
discriminator: {
- type: String,
+ type: String
},
guildID: {
- type: String,
- },
-});
-let mute = mongoose.model("mute", muteSchema);
+ type: String
+ }
+})
+const mute = mongoose.model('mute', muteSchema)
const add = async (user) => {
- let muted = new mute({
+ const muted = new mute({
username: user.username,
id: user.id,
discriminator: user.discriminator,
- guildID: user.guildID,
- });
- return muted.save();
-};
+ guildID: user.guildID
+ })
+ return muted.save()
+}
const exist = async (user) => {
- let query = await mute.find({ id: user.id, guildID: user.guildID });
- return query;
-};
+ const query = await mute.find({ id: user.id, guildID: user.guildID })
+ return query
+}
const remove = async (user) => {
- let query = await mute.deleteOne({ id: user.id, guildID: user.guildID });
- return query;
-};
+ const query = await mute.deleteOne({ id: user.id, guildID: user.guildID })
+ return query
+}
const list = async (guildID) => {
- let query = await mute.find({ guildID: guildID });
- return query;
-};
-module.exports = { add, exist, remove, list };
+ const query = await mute.find({ guildID: guildID })
+ return query
+}
+module.exports = { add, exist, remove, list }
diff --git a/model/playlist.model.js b/model/playlist.model.js
index 3908e5c..c126edb 100644
--- a/model/playlist.model.js
+++ b/model/playlist.model.js
@@ -1,38 +1,38 @@
-let mongoose = require("mongoose");
-let { getSongInfo } = require("../utils/utility");
-let playlistSchema = mongoose.Schema({
+const mongoose = require('mongoose')
+const { getSongInfo } = require('../utils/utility')
+const playlistSchema = mongoose.Schema({
songName: { type: String },
link: { type: String, required: true },
author: {
- type: String,
- },
-});
-let playlist = mongoose.model("playlist", playlistSchema);
+ type: String
+ }
+})
+const playlist = mongoose.model('playlist', playlistSchema)
const addPlaylist = async (url, authorID) => {
- let songInfo = await getSongInfo(url);
- let song = new playlist({
+ const songInfo = await getSongInfo(url)
+ const song = new playlist({
songName: songInfo.title,
link: songInfo.video_url,
- author: authorID,
- });
- return song.save();
-};
+ author: authorID
+ })
+ return song.save()
+}
const getPlaylist = async (authorID) => {
- let playlistArr = playlist.find({ author: authorID });
- return playlistArr;
-};
+ const playlistArr = playlist.find({ author: authorID })
+ return playlistArr
+}
const deleteSong = async (song, authorID) => {
- let a = playlist.findOneAndDelete({ songName: song, author: authorID });
- return a;
-};
+ const a = playlist.findOneAndDelete({ songName: song, author: authorID })
+ return a
+}
const destroyPlaylist = async (authorID) => {
- let a = playlist.deleteMany({ author: authorID });
- return a;
-};
+ const a = playlist.deleteMany({ author: authorID })
+ return a
+}
module.exports = {
addPlaylist,
getPlaylist,
deleteSong,
- destroyPlaylist,
-};
+ destroyPlaylist
+}
diff --git a/model/questionsModel.js b/model/questionsModel.js
index f7ad712..2ca52e4 100644
--- a/model/questionsModel.js
+++ b/model/questionsModel.js
@@ -1,4 +1,4 @@
-const axios = require("axios");
+const axios = require('axios')
/*
question schema:{
@@ -10,67 +10,67 @@ const axios = require("axios");
answer:string(A,B,C,D)
}
*/
-async function checkDb() {
- const url = `https://opentdb.com/api.php?amount=1&category=15`;
- let response = await axios.get(url);
- let response_code = response.data.response_code;
- return response_code == 0;
+async function checkDb () {
+ const url = 'https://opentdb.com/api.php?amount=1&category=15'
+ const response = await axios.get(url)
+ const response_code = response.data.response_code
+ return response_code == 0
}
-function shuffle(a) {
+function shuffle (a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
- [a[i], a[j]] = [a[j], a[i]];
+ [a[i], a[j]] = [a[j], a[i]]
}
- return a;
+ return a
}
-async function getQuestions({ amount = 15, category = "", difficulty = "" }) {
- const url = `https://opentdb.com/api.php?amount=${amount}&category=${category}&difficulty=${difficulty}&type=multiple&encode=url3986`;
- let response = await axios.get(url);
- response = response.data.results;
- let results = [];
- for (let q of response) {
- let x = [q.correct_answer, ...q.incorrect_answers];
- shuffle(x);
- let answer = String.fromCharCode(65 + x.indexOf(q.correct_answer));
- let newQ = {
+async function getQuestions ({ amount = 15, category = '', difficulty = '' }) {
+ const url = `https://opentdb.com/api.php?amount=${amount}&category=${category}&difficulty=${difficulty}&type=multiple&encode=url3986`
+ let response = await axios.get(url)
+ response = response.data.results
+ const results = []
+ for (const q of response) {
+ const x = [q.correct_answer, ...q.incorrect_answers]
+ shuffle(x)
+ const answer = String.fromCharCode(65 + x.indexOf(q.correct_answer))
+ const newQ = {
question: decodeURIComponent(q.question),
A: decodeURIComponent(x[0]),
B: decodeURIComponent(x[1]),
C: decodeURIComponent(x[2]),
D: decodeURIComponent(x[3]),
answer
- };
- results.push(newQ);
+ }
+ results.push(newQ)
}
- return results;
+ return results
}
-async function getCategoryDetail() {
- let category = await getCategory();
- let promises = [];
- for (let x of category)
+async function getCategoryDetail () {
+ const category = await getCategory()
+ const promises = []
+ for (const x of category) {
promises.push(
axios.get(`https://opentdb.com/api_count.php?category=${x.id}`)
- );
- let response = await Promise.all(promises);
- let datas = response.map(e => e.data);
- for (let i = 0; i < category.length; i++)
- category[i].category_question_count = datas[i].category_question_count;
- return category;
+ )
+ }
+ const response = await Promise.all(promises)
+ const datas = response.map(e => e.data)
+ for (let i = 0; i < category.length; i++) { category[i].category_question_count = datas[i].category_question_count }
+ return category
}
-async function getCategory() {
- let url = "https://opentdb.com/api_category.php";
- let response = await axios.get(url);
- response = response.data.trivia_categories;
- return response;
+async function getCategory () {
+ const url = 'https://opentdb.com/api_category.php'
+ let response = await axios.get(url)
+ response = response.data.trivia_categories
+ return response
}
-async function getCategoryName(id) {
- let c = await getCategory();
- let res = c.find(e => e.id == id);
- if (!res) return "ALL";
- return res.name;
+async function getCategoryName (id) {
+ const c = await getCategory()
+ const res = c.find(e => e.id == id)
+ if (!res) return 'ALL'
+ return res.name
}
module.exports = {
@@ -79,4 +79,4 @@ module.exports = {
checkDb,
getCategoryDetail,
getCategory
-};
+}
diff --git a/model/warewolf.js b/model/warewolf.js
index 88bbeac..b505a7e 100644
--- a/model/warewolf.js
+++ b/model/warewolf.js
@@ -1,39 +1,39 @@
-let rules = require("../config/rules.json");
+const rules = require('../config/rules.json')
let roles = [
- "Tiên tri",
- "Bảo vệ",
- "Thợ săn",
- "Phù thủy",
- "Sói",
- "Sói",
- "Sói lửa",
- "Nguyện nữ",
- "Thầy đồng"
-];
-const Discord = require("discord.js");
-const ascii = require("ascii-table");
+ 'Tiên tri',
+ 'Bảo vệ',
+ 'Thợ săn',
+ 'Phù thủy',
+ 'Sói',
+ 'Sói',
+ 'Sói lửa',
+ 'Nguyện nữ',
+ 'Thầy đồng'
+]
+const Discord = require('discord.js')
+const ascii = require('ascii-table')
-async function init(client, message, players) {
+async function init (client, message, players) {
roles = shuffle(roles)
- let gameCategory = message.guild.channels.cache.find(
- x => x.name === "warewolf"
- );
+ const gameCategory = message.guild.channels.cache.find(
+ x => x.name === 'warewolf'
+ )
let gameChannel = message.guild.channels.cache.find(
- x => x.name === "game-session"
- );
- let category;
+ x => x.name === 'game-session'
+ )
+ let category
if (!gameCategory) {
- category = await message.guild.channels.create("warewolf", {
- type: "category"
- });
- } else category = gameCategory;
+ category = await message.guild.channels.create('warewolf', {
+ type: 'category'
+ })
+ } else category = gameCategory
if (!gameChannel) {
- gameChannel = await message.guild.channels.create("game-session", {
- type: "text"
- });
- gameChannel.setParent(category.id);
+ gameChannel = await message.guild.channels.create('game-session', {
+ type: 'text'
+ })
+ gameChannel.setParent(category.id)
}
- let model = {
+ const model = {
players: [],
deadPlayers: [],
alivePlayers: [],
@@ -44,233 +44,221 @@ async function init(client, message, players) {
log: [],
wolvesVote: [],
lynchVote: []
- };
+ }
for (player of players) {
- player.isSlept = null;
- player.isKilled = null;
- player.isProtected = null;
- player.isSaved = null;
- model.players.push(player);
+ player.isSlept = null
+ player.isKilled = null
+ player.isProtected = null
+ player.isSaved = null
+ model.players.push(player)
}
- client.warewolf.set(message.guild.id, model);
- gameProcess(client, message);
+ client.warewolf.set(message.guild.id, model)
+ gameProcess(client, message)
}
-async function gameProcess(client, message) {
- const game = client.warewolf.get(message.guild.id);
- //console.log(serverGame.players);
+async function gameProcess (client, message) {
+ const game = client.warewolf.get(message.guild.id)
+ // console.log(serverGame.players);
for (player of game.players) {
// fixx here
- player.role = game.roles.pop();
- await game.alivePlayers.push(player);
+ player.role = game.roles.pop()
+ await game.alivePlayers.push(player)
}
- sendRole(client, message);
+ sendRole(client, message)
}
-async function sendRole(client, message) {
- const game = client.warewolf.get(message.guild.id);
- //console.log(serverGame.alivePlayers);
+async function sendRole (client, message) {
+ const game = client.warewolf.get(message.guild.id)
+ // console.log(serverGame.alivePlayers);
for (player of game.alivePlayers) {
- await player.send(player.role);
- if (player.role === "Sói" || "Sói lửa") {
- game.wolves.push(player);
+ await player.send(player.role)
+ if (player.role === 'Sói' || 'Sói lửa') {
+ game.wolves.push(player)
}
}
- gettingReady(client, message, game);
+ gettingReady(client, message, game)
}
-async function gettingReady(client, message, game) {
- let channel = message.guild.channels.cache.find(
- x => x.name === "game-session"
- );
- channel.send("Are you ready ? ");
- channel.send("```" + getAlivePlayers(game) + "```");
+async function gettingReady (client, message, game) {
+ const channel = message.guild.channels.cache.find(
+ x => x.name === 'game-session'
+ )
+ channel.send('Are you ready ? ')
+ channel.send('```' + getAlivePlayers(game) + '```')
setTimeout(() => {
- night(client, message, game);
- }, 10000);
+ night(client, message, game)
+ }, 10000)
}
-async function night(client, message, game) {
- game.time = "night";
- moonGirl(client, message, game);
+async function night (client, message, game) {
+ game.time = 'night'
+ moonGirl(client, message, game)
}
-async function day(client, message, game) {
- game.time = "day";
+async function day (client, message, game) {
+ game.time = 'day'
if (parseInt(getVote(wolvesVote)) >= game.wolves.length / 2) {
- game.alivePlayers[parseInt(getVote(wolvesVote))].isKilled = true;
+ game.alivePlayers[parseInt(getVote(wolvesVote))].isKilled = true
log(
- "Sói",
- "đã giết",
+ 'Sói',
+ 'đã giết',
game.alivePlayers[parseInt(getVote(wolvesVote))],
game
- );
- game.wolvesVote = [];
+ )
+ game.wolvesVote = []
}
for (player in game.alivePlayers) {
if (player.isKilled) {
- if (player.isProtected) return;
- if (player.isSaved) return;
- if (!player.isProtected || !player.isSaved)
- await game.deadPlayers.push(player);
+ if (player.isProtected) return
+ if (player.isSaved) return
+ if (!player.isProtected || !player.isSaved) { await game.deadPlayers.push(player) }
}
}
- night(client, message, game);
+ night(client, message, game)
}
-async function lynch() {}
-async function moonGirl(client, message, game) {
+async function lynch () {}
+async function moonGirl (client, message, game) {
for (player of game.alivePlayers) {
- if (player.role === "Nguyệt Nữ") {
- await player.send("```" + getAlivePlayers(game) + "```");
- await player.send("Đêm nay bạn muốn đi khách ở đâu?");
+ if (player.role === 'Nguyệt Nữ') {
+ await player.send('```' + getAlivePlayers(game) + '```')
+ await player.send('Đêm nay bạn muốn đi khách ở đâu?')
const collector = new Discord.MessageCollector(
player.dmChannel,
m => true,
{ time: 30000 },
{ limit: 1 }
- );
- collector.on("end", async collected => {
+ )
+ collector.on('end', async collected => {
if (!collected.length) {
player.send(
- "Bạn đã không chọn người chơi, hệ thống sẽ chọn ngẫu nhiên"
- );
- let alive = game.alivePlayers;
- let random = alive[Math.floor(Math.random() * alive.length)];
- random.isSlept = true;
- return;
+ 'Bạn đã không chọn người chơi, hệ thống sẽ chọn ngẫu nhiên'
+ )
+ const alive = game.alivePlayers
+ const random = alive[Math.floor(Math.random() * alive.length)]
+ random.isSlept = true
} else {
if (!parseInt(collected.first().content)) {
- player.send("Sai quy tắc, sẽ chọn ngẫu nhiên");
- let alive = game.alivePlayers;
- let random = alive[Math.floor(Math.random() * alive.length)];
- random.isSlept = true;
- return;
+ player.send('Sai quy tắc, sẽ chọn ngẫu nhiên')
+ const alive = game.alivePlayers
+ const random = alive[Math.floor(Math.random() * alive.length)]
+ random.isSlept = true
} else {
- let choice = parseInt(collected.first().content);
- game.alivePlayers[choice].isSlept = true;
- log(player.name, "đã ngủ với", game.alivePlayers[choice].name);
+ const choice = parseInt(collected.first().content)
+ game.alivePlayers[choice].isSlept = true
+ log(player.name, 'đã ngủ với', game.alivePlayers[choice].name)
}
}
- });
+ })
}
}
- protector(client, message, game);
+ protector(client, message, game)
}
-async function protector(client, message, game) {
+async function protector (client, message, game) {
for (player of game.alivePlayers) {
- if (player.role === "Người bảo vệ") {
- await player.send("```" + getAlivePlayers(game) + "```");
- await player.send("Bạn muốn bảo vệ ai ?");
+ if (player.role === 'Người bảo vệ') {
+ await player.send('```' + getAlivePlayers(game) + '```')
+ await player.send('Bạn muốn bảo vệ ai ?')
const collector = new Discord.MessageCollector(
player.dmChannel,
m => true,
{ time: 30000 },
{ limit: 1 }
- );
- collector.on("end", collected => {
+ )
+ collector.on('end', collected => {
if (!Number.isInteger(parseInt(collected[0].content))) {
player.send(
- "Bạn đã không chọn người chơi, hệ thống sẽ chọn ngẫu nhiên"
- );
- let alive = game.alivePlayers;
- let random = alive[Math.floor(Math.random() * alive.length)];
- random.isProtected = true;
- return;
+ 'Bạn đã không chọn người chơi, hệ thống sẽ chọn ngẫu nhiên'
+ )
+ const alive = game.alivePlayers
+ const random = alive[Math.floor(Math.random() * alive.length)]
+ random.isProtected = true
} else {
if (!parseInt(collected.first().content)) {
- player.send("Sai quy tắc, sẽ chọn ngẫu nhiên");
- let alive = game.alivePlayers;
- let random = alive[Math.floor(Math.random() * alive.length)];
- random.isProtected = true;
- log(player.name, "đã bảo vệ", random.name);
+ player.send('Sai quy tắc, sẽ chọn ngẫu nhiên')
+ const alive = game.alivePlayers
+ const random = alive[Math.floor(Math.random() * alive.length)]
+ random.isProtected = true
+ log(player.name, 'đã bảo vệ', random.name)
} else {
- let choice = parseInt(collected.first().content);
- game.alivePlayers[choice].isProtected = true;
- log(player.name, "đã bảo vệ", game.alivePlayers[choice].name);
+ const choice = parseInt(collected.first().content)
+ game.alivePlayers[choice].isProtected = true
+ log(player.name, 'đã bảo vệ', game.alivePlayers[choice].name)
}
}
- });
+ })
}
}
- prophet(client, message, game);
+ prophet(client, message, game)
}
-async function prophet(client, message, game) {
+async function prophet (client, message, game) {
for (player of game.alivePlayers) {
- if (player.role === "Tiên tri") {
- await player.send("Đêm nay bạn muốn soi ai?");
+ if (player.role === 'Tiên tri') {
+ await player.send('Đêm nay bạn muốn soi ai?')
await player
- .send("```" + getAlivePlayers(game) + "```")
- .catch(function(err) {
- str = "Unable to send you the list because you cannot receive DMs.";
- if (err != "DiscordAPIError: Cannot send messages to this user")
- console.log(err);
- });
+ .send('```' + getAlivePlayers(game) + '```')
+ .catch(function (err) {
+ str = 'Unable to send you the list because you cannot receive DMs.'
+ if (err != 'DiscordAPIError: Cannot send messages to this user') { console.log(err) }
+ })
const collector = new Discord.MessageCollector(
player.dmChannel,
- m => true, //m.channel.id === player.dmChannel.id && !player.bot,
+ m => true, // m.channel.id === player.dmChannel.id && !player.bot,
{ time: 30000, max: 1 }
- ).on("end", async collected => {
- console.log(Number.isInteger(parseInt(collected.first().content)));
- if (!Number.isInteger(parseInt(collected.first().content)))
- return player.send("Sai quy tắc, mất lượt");
- else {
- let choice = parseInt(collected.first().content);
- if (game.alivePlayers[choice].role === "Sói")
- await player.send("tiên tri đúng");
- else await player.send("Tiên tri sai");
+ ).on('end', async collected => {
+ console.log(Number.isInteger(parseInt(collected.first().content)))
+ if (!Number.isInteger(parseInt(collected.first().content))) { return player.send('Sai quy tắc, mất lượt') } else {
+ const choice = parseInt(collected.first().content)
+ if (game.alivePlayers[choice].role === 'Sói') { await player.send('tiên tri đúng') } else await player.send('Tiên tri sai')
}
- });
+ })
}
}
}
-async function wolves(client, message, game) {
+async function wolves (client, message, game) {
for (player of game.wolves) {
- await player.send("Đêm nay bạn muốn giết ai ?");
+ await player.send('Đêm nay bạn muốn giết ai ?')
await player
- .send("```" + getAlivePlayers(game) + "```")
- .catch(function(err) {
- str = "Unable to send you the list because you cannot receive DMs.";
- if (err != "DiscordAPIError: Cannot send messages to this user")
- console.log(err);
- });
+ .send('```' + getAlivePlayers(game) + '```')
+ .catch(function (err) {
+ str = 'Unable to send you the list because you cannot receive DMs.'
+ if (err != 'DiscordAPIError: Cannot send messages to this user') { console.log(err) }
+ })
const collector = new Discord.MessageCollector(
player.dmChannel,
m => true,
{ time: 30000, max: 1 }
- ).on("end", async collected => {
- console.log(Number.isInteger(parseInt(collected.first().content)));
- if (!Number.isInteger(parseInt(collected.first().content)))
- return player.send("Sai quy tắc, mất lượt");
- else {
- let choice = parseInt(collected.first().content);
- game.wolvesVote.push(choice);
+ ).on('end', async collected => {
+ console.log(Number.isInteger(parseInt(collected.first().content)))
+ if (!Number.isInteger(parseInt(collected.first().content))) { return player.send('Sai quy tắc, mất lượt') } else {
+ const choice = parseInt(collected.first().content)
+ game.wolvesVote.push(choice)
}
- });
+ })
}
}
-function getAlivePlayers(game) {
- let table = new ascii("Alive players");
- table.setHeading("Index", "Name");
- let tempDes = "";
- let alive = game.alivePlayers;
+function getAlivePlayers (game) {
+ const table = new ascii('Alive players')
+ table.setHeading('Index', 'Name')
+ const tempDes = ''
+ const alive = game.alivePlayers
for (player of alive) {
- table.addRow(alive.indexOf(player), player.username);
+ table.addRow(alive.indexOf(player), player.username)
}
- return table.toString();
+ return table.toString()
}
-function shuffle(array) {
- array.sort(() => Math.random() - 0.5);
- return array;
+function shuffle (array) {
+ array.sort(() => Math.random() - 0.5)
+ return array
}
-function createLog(who, reason, victim, game) {
- let logData = `${who} ${reason} ${victim} \n`;
- game.log.push(logData);
+function createLog (who, reason, victim, game) {
+ const logData = `${who} ${reason} ${victim} \n`
+ game.log.push(logData)
}
-function getVote(arr) {
+function getVote (arr) {
return arr
.sort(
(a, b) =>
arr.filter(v => v === a).length - arr.filter(v => v === b).length
)
- .pop();
+ .pop()
}
module.exports = {
init
-};
+}
diff --git a/utils/canvas.js b/utils/canvas.js
index 18c8ed8..2a830a3 100644
--- a/utils/canvas.js
+++ b/utils/canvas.js
@@ -1,70 +1,70 @@
-const { createCanvas } = require("canvas");
-function wrapText(ctx, text, maxWidth) {
+const { createCanvas } = require('canvas')
+function wrapText (ctx, text, maxWidth) {
return new Promise((resolve) => {
- if (ctx.measureText(text).width < maxWidth) return resolve([text]);
- if (ctx.measureText("W").width > maxWidth) return resolve(null);
- const words = text.split(" ");
- const lines = [];
- let line = "";
+ if (ctx.measureText(text).width < maxWidth) return resolve([text])
+ if (ctx.measureText('W').width > maxWidth) return resolve(null)
+ const words = text.split(' ')
+ const lines = []
+ let line = ''
while (words.length > 0) {
- let split = false;
+ let split = false
while (ctx.measureText(words[0]).width >= maxWidth) {
- const temp = words[0];
- words[0] = temp.slice(0, -1);
+ const temp = words[0]
+ words[0] = temp.slice(0, -1)
if (split) {
- words[1] = `${temp.slice(-1)}${words[1]}`;
+ words[1] = `${temp.slice(-1)}${words[1]}`
} else {
- split = true;
- words.splice(1, 0, temp.slice(-1));
+ split = true
+ words.splice(1, 0, temp.slice(-1))
}
}
if (ctx.measureText(`${line}${words[0]}`).width < maxWidth) {
- line += `${words.shift()} `;
+ line += `${words.shift()} `
} else {
- lines.push(line.trim());
- line = "";
+ lines.push(line.trim())
+ line = ''
}
- if (words.length === 0) lines.push(line.trim());
+ if (words.length === 0) lines.push(line.trim())
}
- return resolve(lines);
- });
+ return resolve(lines)
+ })
+}
+const Colors = {
+ DEFAULT: '0',
+ AQUA: '1abc9c',
+ GREEN: '2ecc71',
+ BLUE: '3498db',
+ PURPLE: '9b59b6',
+ GOLD: 'f1c40f',
+ ORANGE: 'e67e22',
+ RED: 'e74c3c',
+ GREY: '95a5a6',
+ DARKER_GREY: '7f8c8d',
+ NAVY: '34495e',
+ DARK_AQUA: '11806a',
+ DARK_GREEN: '1f8b4c',
+ DARK_BLUE: '206694',
+ DARK_PURPLE: '71368a',
+ DARK_GOLD: 'c27c0e',
+ DARK_ORANGE: 'a84300',
+ DARK_RED: '992d22',
+ DARK_GREY: '979c9f',
+ LIGHT_GREY: 'bcc0c0',
+ DARK_NAVY: '2c3e50',
+ LUMINOUS_VIVID_PINK: 'fd0061',
+ DARK_VIVID_PINK: 'bc0057',
+ CUSTOM: '2b2c36',
+ G_TRANSLATE: '4989f4',
+ GITHUB: '282828',
+ IMDB: 'f3ce13',
+ INSTAGRAM: 'e1306c',
+ MAL: '2e51a2',
+ NPM: 'cc3534',
+ STEAM: '2a475e',
+ YOUTUBE: 'c4302b',
+ WIKIPEDIA: '6b6b6b'
}
-let Colors = {
- DEFAULT: "0",
- AQUA: "1abc9c",
- GREEN: "2ecc71",
- BLUE: "3498db",
- PURPLE: "9b59b6",
- GOLD: "f1c40f",
- ORANGE: "e67e22",
- RED: "e74c3c",
- GREY: "95a5a6",
- DARKER_GREY: "7f8c8d",
- NAVY: "34495e",
- DARK_AQUA: "11806a",
- DARK_GREEN: "1f8b4c",
- DARK_BLUE: "206694",
- DARK_PURPLE: "71368a",
- DARK_GOLD: "c27c0e",
- DARK_ORANGE: "a84300",
- DARK_RED: "992d22",
- DARK_GREY: "979c9f",
- LIGHT_GREY: "bcc0c0",
- DARK_NAVY: "2c3e50",
- LUMINOUS_VIVID_PINK: "fd0061",
- DARK_VIVID_PINK: "bc0057",
- CUSTOM: "2b2c36",
- G_TRANSLATE: "4989f4",
- GITHUB: "282828",
- IMDB: "f3ce13",
- INSTAGRAM: "e1306c",
- MAL: "2e51a2",
- NPM: "cc3534",
- STEAM: "2a475e",
- YOUTUBE: "c4302b",
- WIKIPEDIA: "6b6b6b",
-};
module.exports = {
wrapText,
- Colors,
-};
+ Colors
+}
diff --git a/utils/message.js b/utils/message.js
index 5b14389..24a390d 100644
--- a/utils/message.js
+++ b/utils/message.js
@@ -1,55 +1,55 @@
const sendSongQueue = (message, client) => {
- const serverQueue = client.queue.get(message.guild.id);
+ const serverQueue = client.queue.get(message.guild.id)
message.channel.send({
embed: {
color: 3066993,
- title: "Queue added",
+ title: 'Queue added',
url: serverQueue.queue[serverQueue.queue.length - 1].url,
description: serverQueue.queue[serverQueue.queue.length - 1].title,
thumbnail: {
- url: serverQueue.queue[serverQueue.queue.length - 1].thumbnail,
+ url: serverQueue.queue[serverQueue.queue.length - 1].thumbnail
},
footer: {
text:
- `Duration ` +
- serverQueue.queue[serverQueue.queue.length - 1].duration,
- },
- },
- });
-};
+ 'Duration ' +
+ serverQueue.queue[serverQueue.queue.length - 1].duration
+ }
+ }
+ })
+}
const sendPlaying = (message, client) => {
- const serverQueue = client.queue.get(message.guild.id);
+ const serverQueue = client.queue.get(message.guild.id)
message.channel.send({
embed: {
color: 3447003,
- title: "Playing",
+ title: 'Playing',
url: serverQueue.queue[0].url,
description: serverQueue.queue[0].title,
thumbnail: {
- url: serverQueue.queue[0].thumbnail,
+ url: serverQueue.queue[0].thumbnail
},
footer: {
- text: `Duration ` + serverQueue.queue[0].duration,
- },
- },
- });
-};
+ text: 'Duration ' + serverQueue.queue[0].duration
+ }
+ }
+ })
+}
const emptyQueue = (message) => {
message.channel.send({
embed: {
color: 15158332,
- title: "No songs in the queue",
+ title: 'No songs in the queue',
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
-};
+ size: 1024
+ })
+ }
+ }
+ })
+}
const redMessage = (message, title, description = null) => {
message.channel.send({
embed: {
@@ -59,14 +59,14 @@ const redMessage = (message, title, description = null) => {
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
-};
+ size: 1024
+ })
+ }
+ }
+ })
+}
const blueMessage = (message, title, description = null) => {
message.channel.send({
embed: {
@@ -76,33 +76,33 @@ const blueMessage = (message, title, description = null) => {
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
-};
+ size: 1024
+ })
+ }
+ }
+ })
+}
const sendLyrics = async (message, lyrics) => {
- var output = lyrics.split("\n");
- var myfields = [];
- var tmp = 0;
- var sttmp = "";
+ var output = lyrics.split('\n')
+ var myfields = []
+ var tmp = 0
+ var sttmp = ''
for (var i = 0; i <= output.length; i++) {
- sttmp += output[i] + " \n ";
- tmp++;
+ sttmp += output[i] + ' \n '
+ tmp++
if (tmp == 15) {
- myfields.push({ name: "\u200B", value: sttmp });
- tmp = 0;
- sttmp = "";
+ myfields.push({ name: '\u200B', value: sttmp })
+ tmp = 0
+ sttmp = ''
}
}
-};
+}
module.exports = {
sendSongQueue,
sendPlaying,
emptyQueue,
blueMessage,
- redMessage,
-};
+ redMessage
+}
diff --git a/utils/player.js b/utils/player.js
index d6ce13c..307f6da 100644
--- a/utils/player.js
+++ b/utils/player.js
@@ -3,103 +3,103 @@ const {
isYT,
secondsCoverter,
updatePresence,
- sendError,
-} = require("./utility");
-const { initQueue } = require("./queue");
-const dude = require("yt-dude");
-const util = require("util");
-const youtubeDL = require("youtube-dl");
+ sendError
+} = require('./utility')
+const { initQueue } = require('./queue')
+const dude = require('yt-dude')
+const util = require('util')
+const youtubeDL = require('youtube-dl')
const ytdl = require('ytdl-core')
-const getInfo = util.promisify(youtubeDL.getInfo);
+const getInfo = util.promisify(youtubeDL.getInfo)
const {
sendSongQueue,
sendPlaying,
emptyQueue,
- redMessage,
-} = require("./message");
-const { updateCount } = require("../model/musicData");
-let youtubeDLOptions = [
- "--quiet",
- "--ignore-errors",
- "--simulate",
- "--no-warnings",
- "--format=bestaudio[protocol^=http]",
- "--user-agent=KaraDiscordBot (https://bastion.traction.one)",
- "--referer=https://bastion.traction.one",
- "--youtube-skip-dash-manifest",
-];
+ redMessage
+} = require('./message')
+const { updateCount } = require('../model/musicData')
+const youtubeDLOptions = [
+ '--quiet',
+ '--ignore-errors',
+ '--simulate',
+ '--no-warnings',
+ '--format=bestaudio[protocol^=http]',
+ '--user-agent=KaraDiscordBot (https://bastion.traction.one)',
+ '--referer=https://bastion.traction.one',
+ '--youtube-skip-dash-manifest'
+]
const validate = async (client, message, args) => {
if (isYT(args) || isSC(args)) {
- addQueue(client, message, args);
+ addQueue(client, message, args)
} else {
- let query = await dude.search(args);
- let videoUrl = "https://www.youtube.com/watch?v=" + query[0].videoId;
- addQueue(client, message, videoUrl);
+ const query = await dude.search(args)
+ const videoUrl = 'https://www.youtube.com/watch?v=' + query[0].videoId
+ addQueue(client, message, videoUrl)
}
-};
+}
const addQueue = async (client, message, url) => {
- const serverQueue = client.queue.get(message.guild.id);
- let songInfo = await getInfo(url, youtubeDLOptions);
- let song = {
+ const serverQueue = client.queue.get(message.guild.id)
+ const songInfo = await getInfo(url, youtubeDLOptions)
+ const song = {
title: songInfo.title,
url: songInfo.webpage_url,
duration: songInfo.duration,
seconds: songInfo._duration_raw,
requester: message.author.tag,
- thumbnail: songInfo.thumbnail,
- };
+ thumbnail: songInfo.thumbnail
+ }
if (!serverQueue) {
- let tempQueue = await initQueue(message);
- tempQueue.queue.push(song);
- client.queue.set(message.guild.id, tempQueue);
- player(client, message);
+ const tempQueue = await initQueue(message)
+ tempQueue.queue.push(song)
+ client.queue.set(message.guild.id, tempQueue)
+ player(client, message)
} else {
- serverQueue.queue.push(song);
- sendSongQueue(message, client);
+ serverQueue.queue.push(song)
+ sendSongQueue(message, client)
}
-};
+}
const player = async (client, message) => {
- const serverQueue = client.queue.get(message.guild.id);
+ const serverQueue = client.queue.get(message.guild.id)
try {
if (!serverQueue.queue[0]) {
- serverQueue.isPlaying = false;
- updatePresence(message, serverQueue);
- serverQueue.voiceChannel.leave();
- emptyQueue(message);
- client.queue.delete(message.guild.id);
+ serverQueue.isPlaying = false
+ updatePresence(message, serverQueue)
+ serverQueue.voiceChannel.leave()
+ emptyQueue(message)
+ client.queue.delete(message.guild.id)
} else {
- sendPlaying(message, client);
+ sendPlaying(message, client)
serverQueue.dispatcher = serverQueue.connection
.play(youtubeDL(serverQueue.queue[0].url))
- .on("start", () => {
- serverQueue.isPlaying = true;
- updatePresence(message, serverQueue);
- updateCount(serverQueue.queue[0].title);
+ .on('start', () => {
+ serverQueue.isPlaying = true
+ updatePresence(message, serverQueue)
+ updateCount(serverQueue.queue[0].title)
})
- .on("finish", () => {
- serverQueue.queue.shift();
- player(client, message);
+ .on('finish', () => {
+ serverQueue.queue.shift()
+ player(client, message)
})
- .on("volumeChange", (oldVolume, newVolume) => {
+ .on('volumeChange', (oldVolume, newVolume) => {
message.channel.send({
embed: {
title: `Volume changed from ${oldVolume} to ${newVolume}.`,
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
+ size: 1024
+ })
+ }
+ }
+ })
})
- .on("end", () => {
- serverQueue.queue.shift();
+ .on('end', () => {
+ serverQueue.queue.shift()
})
- .on("error", (error) => {
- redMessage(message, error.name, error.message);
+ .on('error', (error) => {
+ redMessage(message, error.name, error.message)
// const { exec } = require("child_process");
// try {
// exec(
@@ -114,16 +114,16 @@ const player = async (client, message) => {
// } catch (e) {
// return sendError(message, e);
// }
- });
+ })
}
} catch (error) {
- await serverQueue.voiceChannel.leave();
- client.queue.delete(message.guild.id);
+ await serverQueue.voiceChannel.leave()
+ client.queue.delete(message.guild.id)
}
-};
+}
module.exports = {
validate,
addQueue,
- player,
-};
+ player
+}
diff --git a/utils/progressBar.js b/utils/progressBar.js
index 85a764a..6bdbe1c 100644
--- a/utils/progressBar.js
+++ b/utils/progressBar.js
@@ -1,25 +1,25 @@
class ProgressBar {
- constructor(value, maxValue, barSize) {
- this.value = value;
- this.maxValue = maxValue;
- this.barSize = barSize;
+ constructor (value, maxValue, barSize) {
+ this.value = value
+ this.maxValue = maxValue
+ this.barSize = barSize
}
/**
* Create a text progress bar
* @returns {String} - The bar
*/
- createBar() {
- let percentage = this.value / this.maxValue; //Calculate the percentage of the bar
- let progress = Math.round(this.barSize * percentage); //Calculate the number of square caracters to fill the progress side.
- let emptyProgress = this.barSize - progress; //Calculate the number of dash caracters to fill the empty progress side.
+ createBar () {
+ const percentage = this.value / this.maxValue // Calculate the percentage of the bar
+ const progress = Math.round(this.barSize * percentage) // Calculate the number of square caracters to fill the progress side.
+ const emptyProgress = this.barSize - progress // Calculate the number of dash caracters to fill the empty progress side.
- let progressText = "▇".repeat(progress); //Repeat is creating a string with progress * caracters in it
- let emptyProgressText = "—".repeat(emptyProgress); //Repeat is creating a string with empty progress * caracters in it
- let percentageText = Math.round(percentage * 100) + "%"; //Displaying the percentage of the bar
+ const progressText = '▇'.repeat(progress) // Repeat is creating a string with progress * caracters in it
+ const emptyProgressText = '—'.repeat(emptyProgress) // Repeat is creating a string with empty progress * caracters in it
+ const percentageText = Math.round(percentage * 100) + '%' // Displaying the percentage of the bar
- let bar = "[" + progressText + emptyProgressText + "] " + percentageText; //Creating the bar
- return bar;
+ const bar = '[' + progressText + emptyProgressText + '] ' + percentageText // Creating the bar
+ return bar
}
}
// //The barSize is the number of caracters which define the bar (default: 20)
@@ -27,4 +27,4 @@ class ProgressBar {
// //Create the bar
// let bar = progressBar.createBar();
// console.log(bar);
-module.exports = ProgressBar;
+module.exports = ProgressBar
diff --git a/utils/queue.js b/utils/queue.js
index 00346ca..20d4a2c 100644
--- a/utils/queue.js
+++ b/utils/queue.js
@@ -1,14 +1,14 @@
-const plModel = require("../model/playlist.model");
-const { blueMessage } = require("./message");
-let {
+const plModel = require('../model/playlist.model')
+const { blueMessage } = require('./message')
+const {
secondsCoverter,
getThumbnail,
getSongInfo,
- shuffleArray,
-} = require("./utility");
+ shuffleArray
+} = require('./utility')
const initQueue = async (message) => {
- let voiceChannel = message.member.voice.channel;
- let tempQueue = {
+ const voiceChannel = message.member.voice.channel
+ const tempQueue = {
guildID: null,
queue: [],
isPlaying: false,
@@ -16,32 +16,32 @@ const initQueue = async (message) => {
voiceChannel: voiceChannel,
textChannel: message.channel,
connection: null,
- dispatcher: null,
- };
- tempQueue.connection = await tempQueue.voiceChannel.join();
- return tempQueue;
-};
+ dispatcher: null
+ }
+ tempQueue.connection = await tempQueue.voiceChannel.join()
+ return tempQueue
+}
const addPlaylistToQueue = async (message, queue, user) => {
- let songArr = await plModel.getPlaylist(user);
- songArr = shuffleArray(songArr);
- let i = 1;
+ let songArr = await plModel.getPlaylist(user)
+ songArr = shuffleArray(songArr)
+ let i = 1
for (const song of songArr) {
- let songInfo = await getSongInfo(song.link);
- let songData = {
+ const songInfo = await getSongInfo(song.link)
+ const songData = {
title: `${i}/` + songInfo.title,
url: songInfo.video_url,
thumbnail: getThumbnail(songInfo.video_url),
duration: secondsCoverter(songInfo.length_seconds),
seconds: songInfo.length_seconds,
- requester: message.author.tag,
- };
- queue.queue.push(songData);
- i++;
+ requester: message.author.tag
+ }
+ queue.queue.push(songData)
+ i++
}
- blueMessage(message, "Added " + songArr.length + " songs to queue");
- return queue;
-};
+ blueMessage(message, 'Added ' + songArr.length + ' songs to queue')
+ return queue
+}
module.exports = {
initQueue,
- addPlaylistToQueue,
-};
+ addPlaylistToQueue
+}
diff --git a/utils/radio.js b/utils/radio.js
index 03d78e5..f417b9e 100644
--- a/utils/radio.js
+++ b/utils/radio.js
@@ -1,100 +1,100 @@
-let { sendSongQueue, sendPlaying, emptyQueue } = require("./message");
-let { updatePresence, sendErrorMail } = require("./utility");
-const Pagination = require("discord-paginationembed");
-const ytcore = require("ytdl-core");
-const stations = require("../data/stations.json");
+const { sendSongQueue, sendPlaying, emptyQueue } = require('./message')
+const { updatePresence, sendErrorMail } = require('./utility')
+const Pagination = require('discord-paginationembed')
+const ytcore = require('ytdl-core')
+const stations = require('../data/stations.json')
const play = (client, message, station) => {
- const serverQueue = client.queue.get(message.guild.id);
- console.log(serverQueue);
+ const serverQueue = client.queue.get(message.guild.id)
+ console.log(serverQueue)
if (!serverQueue.queue[0]) {
- serverQueue.isPlaying = false;
- updatePresence(message, serverQueue);
- serverQueue.voiceChannel.leave();
- emptyQueue(message, client);
- client.queue.delete(guild);
+ serverQueue.isPlaying = false
+ updatePresence(message, serverQueue)
+ serverQueue.voiceChannel.leave()
+ emptyQueue(message, client)
+ client.queue.delete(guild)
} else {
- sendPlaying(message, client);
+ sendPlaying(message, client)
serverQueue.dispatcher = serverQueue.connection
.play(serverQueue.queue[0].url, {
- filter: "audioonly",
- quality: "highestaudio",
+ filter: 'audioonly',
+ quality: 'highestaudio',
highWaterMark: 1 << 25,
- encoderArgs: ["-af", `equalizer=f=40:width_type=h:width=50:g=50`],
+ encoderArgs: ['-af', 'equalizer=f=40:width_type=h:width=50:g=50']
})
// serverQueue.dispatcher = serverQueue.connection
// .play(await ytDiscord(serverQueue.queue[0].url), { type: "opus" })
- .on("start", () => {
- serverQueue.isPlaying = true;
- updatePresence(message, serverQueue);
+ .on('start', () => {
+ serverQueue.isPlaying = true
+ updatePresence(message, serverQueue)
})
- .on("finish", () => {
- console.log("stop playing");
- serverQueue.queue.shift();
- play(message.guild.id);
+ .on('finish', () => {
+ console.log('stop playing')
+ serverQueue.queue.shift()
+ play(message.guild.id)
})
- .on("volumeChange", (oldVolume, newVolume) => {
+ .on('volumeChange', (oldVolume, newVolume) => {
message.channel.send({
embed: {
title: `Volume changed from ${oldVolume} to ${newVolume}.`,
author: {
name: message.client.user.username,
icon_url: message.client.user.avatarURL({
- format: "png",
+ format: 'png',
dynamic: true,
- size: 1024,
- }),
- },
- },
- });
+ size: 1024
+ })
+ }
+ }
+ })
})
- .on("end", () => {
- serverQueue.queue.shift();
+ .on('end', () => {
+ serverQueue.queue.shift()
+ })
+ .on('error', (error) => {
+ console.log(error)
+ sendErrorMail(error)
})
- .on("error", (error) => {
- console.log(error);
- sendErrorMail(error);
- });
}
-};
+}
const stop = (client, message) => {
- const serverQueue = client.queue.get(message.guild.id);
- if (!serverQueue) return message.reply("Not playing radio stream");
- if (!serverQueue.radio) message.reply("Use skip command please");
+ const serverQueue = client.queue.get(message.guild.id)
+ if (!serverQueue) return message.reply('Not playing radio stream')
+ if (!serverQueue.radio) message.reply('Use skip command please')
try {
- serverQueue.dispatcher.destroy();
- serverQueue.voiceChannel.leave();
- client.queue.delete(message.guild.id);
+ serverQueue.dispatcher.destroy()
+ serverQueue.voiceChannel.leave()
+ client.queue.delete(message.guild.id)
} catch (error) {
- console.log(error);
+ console.log(error)
}
-};
+}
const showStations = async (client, message) => {
- let embeds = [];
- for (let station of Object.keys(stations)) {
- let data = {
- name: station,
- };
- embeds.push(data);
+ const embeds = []
+ for (const station of Object.keys(stations)) {
+ const data = {
+ name: station
+ }
+ embeds.push(data)
}
const infor = new Pagination.FieldsEmbed()
.setArray(embeds)
.setAuthorizedUsers([])
.setChannel(message.channel)
.setPageIndicator(true)
- .formatField("Name", (i) => i.name + "\n")
+ .formatField('Name', (i) => i.name + '\n')
.setDeleteOnTimeout(true)
.setElementsPerPage(10)
- .setEmojisFunctionAfterNavigation(true);
+ .setEmojisFunctionAfterNavigation(true)
infor.embed
.setThumbnail(
- client.user.avatarURL({ format: "png", dynamic: true, size: 1024 })
+ client.user.avatarURL({ format: 'png', dynamic: true, size: 1024 })
)
- .setColor("#0390fc")
- .setFooter("Created by wrose");
- await infor.build();
-};
+ .setColor('#0390fc')
+ .setFooter('Created by wrose')
+ await infor.build()
+}
module.exports = {
play,
stop,
- showStations,
-};
+ showStations
+}
diff --git a/utils/utility.js b/utils/utility.js
index 68d0f79..8a9c510 100644
--- a/utils/utility.js
+++ b/utils/utility.js
@@ -1,191 +1,190 @@
-let request = require("request");
-let cheerio = require("cheerio");
-let config = require("../config/config.json");
-const fs = require("fs");
-const convert = require("xml-js");
-const Discord = require("discord.js");
-const moment = require("moment");
-const jsdom = require("jsdom");
-const { createCanvas } = require("canvas");
-const { JSDOM } = jsdom;
-const getVideoId = require("get-video-id");
-const ytdl = require("ytdl-core");
-const startWords = require("../assets/json/word-list.json");
-const send = require("gmail-send")({
- user: "minzycrackteam@gmail.com",
- pass: "kjbarjuidzcevgcn",
- to: "sktt1lka@gmail.com",
- subject: "Error on DiscordBot",
- text: "Error happened",
-});
-const yts = require("yt-search");
-function sendResponse(message) {
- const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
- let query = encodeURIComponent(args.join(" "));
+const request = require('request')
+const cheerio = require('cheerio')
+const config = require('../config/config.json')
+const fs = require('fs')
+const convert = require('xml-js')
+const Discord = require('discord.js')
+const moment = require('moment')
+const jsdom = require('jsdom')
+const { createCanvas } = require('canvas')
+const { JSDOM } = jsdom
+const getVideoId = require('get-video-id')
+const ytdl = require('ytdl-core')
+const startWords = require('../assets/json/word-list.json')
+const send = require('gmail-send')({
+ user: 'minzycrackteam@gmail.com',
+ pass: 'kjbarjuidzcevgcn',
+ to: 'sktt1lka@gmail.com',
+ subject: 'Error on DiscordBot',
+ text: 'Error happened'
+})
+const yts = require('yt-search')
+function sendResponse (message) {
+ const args = message.content.slice(config.prefix.length).trim().split(/ +/g)
+ const query = encodeURIComponent(args.join(' '))
request(`https://some-random-api.ml/chatbot?message=${query}`, function (
error,
response,
body
) {
- if (error) console.log(error);
- let data = JSON.parse(body);
- if (!data) console.log("no data");
+ if (error) console.log(error)
+ const data = JSON.parse(body)
+ if (!data) console.log('no data')
if (data) {
- message.channel.send(data.response);
+ message.channel.send(data.response)
}
- });
+ })
}
-function validateUser(message) {
- for (let key in config.ownerID) {
- if (message.member.id === config.ownerID[key]) return true;
+function validateUser (message) {
+ for (const key in config.ownerID) {
+ if (message.member.id === config.ownerID[key]) return true
}
- return false;
+ return false
}
-function sendShit(message) {
- message.channel.send(`https://discord.gg/grd5J3K`);
+function sendShit (message) {
+ message.channel.send('https://discord.gg/grd5J3K')
}
String.prototype.capitalize = function () {
- return this.charAt(0).toUpperCase() + this.slice(1);
-};
+ return this.charAt(0).toUpperCase() + this.slice(1)
+}
-function sendNews(msg) {
- fs.readFile("./newsData.json", async function readFileCallback(err, data) {
- data = JSON.parse(data);
- var key1, sendData;
+function sendNews (msg) {
+ fs.readFile('./newsData.json', async function readFileCallback (err, data) {
+ data = JSON.parse(data)
+ var key1, sendData
for (const key of Object.keys(data)) {
if (data[key].Actived == false) {
- key1 = key;
+ key1 = key
}
}
if (key1) {
- data[key1].Actived = true;
- sendData = data[key1];
+ data[key1].Actived = true
+ sendData = data[key1]
}
if (sendData) {
- fs.writeFile("./newsData.json", JSON.stringify(data), "", (err) => {});
- var { link, desc } = convert_data(sendData.description._cdata);
- let title = sendData.title._text ? sendData.title._text : "Article";
+ fs.writeFile('./newsData.json', JSON.stringify(data), '', (err) => {})
+ var { link, desc } = convert_data(sendData.description._cdata)
+ const title = sendData.title._text ? sendData.title._text : 'Article'
const embed = new Discord.MessageEmbed()
.setTitle(title)
.setColor(getRandomColor())
.setDescription(desc)
.setURL(link)
.setTimestamp(sendData.pubDate._text)
- .setFooter("VNEXPRESS");
+ .setFooter('VNEXPRESS')
- await msg.channel.send(embed);
+ await msg.channel.send(embed)
}
- });
+ })
}
-function updateNews() {
- request("https://vnexpress.net/rss/tin-moi-nhat.rss", function (
+function updateNews () {
+ request('https://vnexpress.net/rss/tin-moi-nhat.rss', function (
err,
response,
body
) {
- if (err) console.log(err);
- var result1 = convert.xml2js(body, { compact: true, spaces: 4 });
- var dataTmp = result1.rss.channel.item;
+ if (err) console.log(err)
+ var result1 = convert.xml2js(body, { compact: true, spaces: 4 })
+ var dataTmp = result1.rss.channel.item
for (const key of Object.keys(dataTmp)) {
- dataTmp[key].Actived = false;
+ dataTmp[key].Actived = false
}
- if (!fs.existsSync("./newsData.json")) {
+ if (!fs.existsSync('./newsData.json')) {
// Nếu chưa tồn tại tạo file mới
- fs.writeFile("./newsData.json", JSON.stringify(dataTmp), "", (err) => {
- if (err) throw err;
- console.log("Tạo file newsData.json thành công!");
- });
- return;
+ fs.writeFile('./newsData.json', JSON.stringify(dataTmp), '', (err) => {
+ if (err) throw err
+ console.log('Tạo file newsData.json thành công!')
+ })
+ return
}
- fs.readFile("./newsData.json", function readFileCallback(err, data) {
+ fs.readFile('./newsData.json', function readFileCallback (err, data) {
if (err) {
- console.log("Đọc file newsData.json thất bại!");
- return;
+ console.log('Đọc file newsData.json thất bại!')
} else {
- var obj = JSON.parse(data);
- var ifNew = false;
- var del = 0,
- add = 0;
+ var obj = JSON.parse(data)
+ var ifNew = false
+ var del = 0
+ var add = 0
for (const key1 of Object.keys(dataTmp)) {
- var check = false;
+ var check = false
for (const key2 of Object.keys(obj)) {
- if (obj[key2].title._text == dataTmp[key1].title._text)
- check = true;
+ if (obj[key2].title._text == dataTmp[key1].title._text) { check = true }
}
if (!check) {
- obj.push(dataTmp[key1]);
- ifNew = true;
- add++;
+ obj.push(dataTmp[key1])
+ ifNew = true
+ add++
}
}
cleanData(obj, function (delData, ifNewData) {
- del += delData;
- ifNew = ifNew || ifNewData;
- });
+ del += delData
+ ifNew = ifNew || ifNewData
+ })
- if (ifNew)
- fs.writeFile("./newsData.json", JSON.stringify(obj), "", (err) => {
- if (err) throw err;
+ if (ifNew) {
+ fs.writeFile('./newsData.json', JSON.stringify(obj), '', (err) => {
+ if (err) throw err
console.log(
`Cập nhật newsData.json thành công!\n Thêm ${add} tin. Xóa ${del} tin. Tổng tin: ${obj.length}\n`
- );
- });
+ )
+ })
+ }
}
- });
- });
+ })
+ })
}
-function convert_data(data) {
- const $ = cheerio.load(data);
- var link = $("a").first().attr("href");
+function convert_data (data) {
+ const $ = cheerio.load(data)
+ var link = $('a').first().attr('href')
const dom = new JSDOM('
', {
- includeNodeLocations: true,
- });
- var thumnail = dom.window.document.querySelector("img").getAttribute("src");
- var desc = $.text();
- return { link, desc, thumnail };
+ includeNodeLocations: true
+ })
+ var thumnail = dom.window.document.querySelector('img').getAttribute('src')
+ var desc = $.text()
+ return { link, desc, thumnail }
}
-function cleanData(obj, callback) {
- var key = obj.length;
- var del = 0;
- ifNew = false;
+function cleanData (obj, callback) {
+ var key = obj.length
+ var del = 0
+ ifNew = false
while (key--) {
if (obj[key]) {
- var date = Date.parse(obj[key].pubDate._text);
+ var date = Date.parse(obj[key].pubDate._text)
if ((Date.now() - date) / (60 * 60 * 24 * 1000) >= 24 / 24) {
- obj.splice(key, 1);
- ifNew = true;
- del++;
+ obj.splice(key, 1)
+ ifNew = true
+ del++
}
}
}
- callback(del, ifNew);
+ callback(del, ifNew)
}
-function getChess(data, msg) {
+function getChess (data, msg) {
if (checkSteam(data)) {
request(config.getID64URL + data, function (err, response, body) {
- if (err) throw err;
- body = JSON.parse(body).response;
+ if (err) throw err
+ body = JSON.parse(body).response
if (body.success == 1) {
- var steamID64 = body.steamid;
- sendATC(steamID64, msg);
- } else msg.channel.send("```ERROR, CANT FIND USER\nPLEASE USE USERNAME OR STEAMID```");
- });
- } else sendATC(data, msg);
+ var steamID64 = body.steamid
+ sendATC(steamID64, msg)
+ } else msg.channel.send('```ERROR, CANT FIND USER\nPLEASE USE USERNAME OR STEAMID```')
+ })
+ } else sendATC(data, msg)
}
-function sendATC(steamID, msg) {
+function sendATC (steamID, msg) {
request(
- config.getDAC + steamID64toSteamID32(steamID) + "/overview",
+ config.getDAC + steamID64toSteamID32(steamID) + '/overview',
function (err, response, body) {
- if (err) throw err;
- var body = JSON.parse(body).data;
+ if (err) throw err
+ var body = JSON.parse(body).data
if (body) {
getUsername(steamID, function (username, avatarLink) {
const embed = new Discord.MessageEmbed()
@@ -193,353 +192,353 @@ function sendATC(steamID, msg) {
.setColor(getRandomColor())
.setThumbnail(avatarLink)
.addField(
- ":globe_with_meridians: Rank/Max Rank :",
- getRank(body.current_level) + "/" + getRank(body.highest_level),
+ ':globe_with_meridians: Rank/Max Rank :',
+ getRank(body.current_level) + '/' + getRank(body.highest_level),
true
)
.addField(
- ":100: Avg Rank In Match :",
+ ':100: Avg Rank In Match :',
Math.round(body.avg_rank * 100) / 100,
true
)
- .addField(":wheel_of_dharma: Total Games :", body.total_games, true)
- .addField(":crown: Top 1 :", body.win_games, true)
- .addField(":small_orange_diamond: Top 3 :", body.top3_games, true)
- .addField(":candy: Total candies :", body.total_candies, true)
- .setFooter("Autochess Stats - autochess.varena.com")
- .setTimestamp(Date.now());
- msg.channel.send(embed);
- });
- } else msg.channel.send("```SORRY,SOMETHING WENT WRONG```");
+ .addField(':wheel_of_dharma: Total Games :', body.total_games, true)
+ .addField(':crown: Top 1 :', body.win_games, true)
+ .addField(':small_orange_diamond: Top 3 :', body.top3_games, true)
+ .addField(':candy: Total candies :', body.total_candies, true)
+ .setFooter('Autochess Stats - autochess.varena.com')
+ .setTimestamp(Date.now())
+ msg.channel.send(embed)
+ })
+ } else msg.channel.send('```SORRY,SOMETHING WENT WRONG```')
}
- );
+ )
}
-function getUsername(steamID, callback) {
+function getUsername (steamID, callback) {
request(config.getUserInfo + steamID, function (err, response, body) {
- if (err) throw err;
+ if (err) throw err
if (body) {
- body = JSON.parse(body).response.players[0];
- callback(body.personaname, body.avatarfull);
+ body = JSON.parse(body).response.players[0]
+ callback(body.personaname, body.avatarfull)
}
- });
+ })
}
-function checkSteam(data) {
- return 1 && (data.length !== 17 || parseInt(data) == NaN);
+function checkSteam (data) {
+ return 1 && (data.length !== 17 || parseInt(data) == NaN)
}
-function steamID64toSteamID32(steamID64) {
- return Number(steamID64.substr(-16, 16)) - 6561197960265728;
+function steamID64toSteamID32 (steamID64) {
+ return Number(steamID64.substr(-16, 16)) - 6561197960265728
}
-function getRank(number) {
- var rank = ["Pawn", "Knight", "Bishop", "Rook", "King", "Queen"];
- var tier = Math.floor(number / 9);
- var num;
- if (tier >= 4) num = "";
- else num = " " + (number % 9 == 0 ? 9 : number % 9);
- return rank[tier] + num;
+function getRank (number) {
+ var rank = ['Pawn', 'Knight', 'Bishop', 'Rook', 'King', 'Queen']
+ var tier = Math.floor(number / 9)
+ var num
+ if (tier >= 4) num = ''
+ else num = ' ' + (number % 9 == 0 ? 9 : number % 9)
+ return rank[tier] + num
}
-function getRandomColor() {
- var letters = "0123456789ABCDEF";
- var color = "#";
+function getRandomColor () {
+ var letters = '0123456789ABCDEF'
+ var color = '#'
for (var i = 0; i < 6; i++) {
- color += letters[Math.floor(Math.random() * 16)];
+ color += letters[Math.floor(Math.random() * 16)]
}
- return color;
+ return color
}
-function getStats(username, msg) {
- var user = msg.member;
+function getStats (username, msg) {
+ var user = msg.member
const embed = new Discord.MessageEmbed()
.setTitle(user.displayName)
.addField(
- "Join date:",
- moment(user.joinedAt).calendar(null, { sameElse: "DD/MM/YYYY" }),
+ 'Join date:',
+ moment(user.joinedAt).calendar(null, { sameElse: 'DD/MM/YYYY' }),
true
)
- .addField("Status:", user.presence.status.capitalize(), true)
- .addField("IsBot:", user.user.bot ? "Yes" : "No", true)
- .addField("Total time spend on discord:", "Dunt know :<", true)
+ .addField('Status:', user.presence.status.capitalize(), true)
+ .addField('IsBot:', user.user.bot ? 'Yes' : 'No', true)
+ .addField('Total time spend on discord:', 'Dunt know :<', true)
.setThumbnail(user.user.avatarURL)
.setColor(user.displayHexColor)
- .setTimestamp(Date.now());
- msg.channel.send(embed);
+ .setTimestamp(Date.now())
+ msg.channel.send(embed)
}
-function updateCorona(message) {
- request("https://coronavirus-tracker-api.herokuapp.com/all", function (
+function updateCorona (message) {
+ request('https://coronavirus-tracker-api.herokuapp.com/all', function (
error,
response,
body
) {
- let data = JSON.parse(body);
+ const data = JSON.parse(body)
message.channel.send({
embed: {
color: 14177041,
- title: "Corona(COVID-19) updates",
+ title: 'Corona(COVID-19) updates',
fields: [
{
- name: "Infected",
- value: data.latest.confirmed,
+ name: 'Infected',
+ value: data.latest.confirmed
},
{
- name: "Deaths confirmed",
- value: data.latest.deaths,
+ name: 'Deaths confirmed',
+ value: data.latest.deaths
},
{
- name: "Recoverd",
- value: data.latest.recovered,
- },
- ],
- },
- });
- });
-}
-function progressBar(message, duration) {
- let progressCount = 30;
- let intervalTime = duration / progressCount;
- let count = 0;
- let bar = "";
+ name: 'Recoverd',
+ value: data.latest.recovered
+ }
+ ]
+ }
+ })
+ })
+}
+function progressBar (message, duration) {
+ const progressCount = 30
+ const intervalTime = duration / progressCount
+ let count = 0
+ let bar = ''
thisInterval = setInterval(async function () {
- msg.edit({ embed: {} });
- bar = bar + "=";
- count++;
- }, intervalTime);
+ msg.edit({ embed: {} })
+ bar = bar + '='
+ count++
+ }, intervalTime)
}
-function progressBarStop() {
- clearInterval(thisInterval);
+function progressBarStop () {
+ clearInterval(thisInterval)
}
-async function verify(channel, user, time = 30000) {
- const yes = ["yes", "y", "ye", "yeah", "yup", "yea", "ya"];
- const no = ["no", "n", "nah", "nope", "nop"];
+async function verify (channel, user, time = 30000) {
+ const yes = ['yes', 'y', 'ye', 'yeah', 'yup', 'yea', 'ya']
+ const no = ['no', 'n', 'nah', 'nope', 'nop']
const filter = (res) => {
- const value = res.content.toLowerCase();
+ const value = res.content.toLowerCase()
return (
(user ? res.author.id === user.id : true) &&
(yes.includes(value) || no.includes(value))
- );
- };
+ )
+ }
const verify = await channel.awaitMessages(filter, {
max: 1,
- time,
- });
- if (!verify.size) return 0;
- const choice = verify.first().content.toLowerCase();
- if (yes.includes(choice)) return true;
- if (no.includes(choice)) return false;
- return false;
-}
-async function verifyWord(word) {
- if (startWords.includes(word.toLowerCase())) return true;
+ time
+ })
+ if (!verify.size) return 0
+ const choice = verify.first().content.toLowerCase()
+ if (yes.includes(choice)) return true
+ if (no.includes(choice)) return false
+ return false
+}
+async function verifyWord (word) {
+ if (startWords.includes(word.toLowerCase())) return true
try {
const { body } = await request
.get(
`https://www.dictionaryapi.com/api/v3/references/collegiate/json/${word}`
)
- .query({ key: "d1bc37f2-10d5-4b0e-9171-54d13e7b7475" });
- if (!body.length) return false;
- return true;
+ .query({ key: 'd1bc37f2-10d5-4b0e-9171-54d13e7b7475' })
+ if (!body.length) return false
+ return true
} catch (err) {
- if (err.status === 404) return false;
- return null;
+ if (err.status === 404) return false
+ return null
}
}
-function delay(ms) {
- return new Promise((resolve) => setTimeout(resolve, ms));
+function delay (ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms))
}
-function shortenText(ctx, text, maxWidth) {
- let shorten = false;
+function shortenText (ctx, text, maxWidth) {
+ let shorten = false
while (ctx.measureText(text).width > maxWidth) {
- if (!shorten) shorten = true;
- text = text.substr(0, text.length - 1);
+ if (!shorten) shorten = true
+ text = text.substr(0, text.length - 1)
}
- return shorten ? `${text}...` : text;
+ return shorten ? `${text}...` : text
}
-function list(arr, conj = "and") {
- const len = arr.length;
- return `${arr.slice(0, -1).join(", ")}${
- len > 1 ? `${len > 2 ? "," : ""} ${conj} ` : ""
- }${arr.slice(-1)}`;
+function list (arr, conj = 'and') {
+ const len = arr.length
+ return `${arr.slice(0, -1).join(', ')}${
+ len > 1 ? `${len > 2 ? ',' : ''} ${conj} ` : ''
+ }${arr.slice(-1)}`
}
-function silhouette(ctx, x, y, width, height) {
- const data = ctx.getImageData(x, y, width, height);
+function silhouette (ctx, x, y, width, height) {
+ const data = ctx.getImageData(x, y, width, height)
for (let i = 0; i < data.data.length; i += 4) {
- data.data[i] = 0;
- data.data[i + 1] = 0;
- data.data[i + 2] = 0;
+ data.data[i] = 0
+ data.data[i + 1] = 0
+ data.data[i + 2] = 0
}
- ctx.putImageData(data, x, y);
- return ctx;
+ ctx.putImageData(data, x, y)
+ return ctx
}
-function invert(ctx, x, y, width, height) {
- const data = ctx.getImageData(x, y, width, height);
+function invert (ctx, x, y, width, height) {
+ const data = ctx.getImageData(x, y, width, height)
for (let i = 0; i < data.data.length; i += 4) {
- data.data[i] = 255 - data.data[i];
- data.data[i + 1] = 255 - data.data[i + 1];
- data.data[i + 2] = 255 - data.data[i + 2];
+ data.data[i] = 255 - data.data[i]
+ data.data[i + 1] = 255 - data.data[i + 1]
+ data.data[i + 2] = 255 - data.data[i + 2]
}
- ctx.putImageData(data, x, y);
- return ctx;
-}
-function centerImage(base, data) {
- const dataRatio = data.width / data.height;
- const baseRatio = base.width / base.height;
- let { width, height } = data;
- let x = 0;
- let y = 0;
+ ctx.putImageData(data, x, y)
+ return ctx
+}
+function centerImage (base, data) {
+ const dataRatio = data.width / data.height
+ const baseRatio = base.width / base.height
+ let { width, height } = data
+ let x = 0
+ let y = 0
if (baseRatio < dataRatio) {
- height = data.height;
- width = base.width * (height / base.height);
- x = (data.width - width) / 2;
- y = 0;
+ height = data.height
+ width = base.width * (height / base.height)
+ x = (data.width - width) / 2
+ y = 0
} else if (baseRatio > dataRatio) {
- width = data.width;
- height = base.height * (width / base.width);
- x = 0;
- y = (data.height - height) / 2;
+ width = data.width
+ height = base.height * (width / base.width)
+ x = 0
+ y = (data.height - height) / 2
}
- return { x, y, width, height };
+ return { x, y, width, height }
}
-function sepia(ctx, x, y, width, height) {
- const data = ctx.getImageData(x, y, width, height);
+function sepia (ctx, x, y, width, height) {
+ const data = ctx.getImageData(x, y, width, height)
for (let i = 0; i < data.data.length; i += 4) {
const brightness =
- 0.34 * data.data[i] + 0.5 * data.data[i + 1] + 0.16 * data.data[i + 2];
- data.data[i] = brightness + 100;
- data.data[i + 1] = brightness + 50;
- data.data[i + 2] = brightness;
+ 0.34 * data.data[i] + 0.5 * data.data[i + 1] + 0.16 * data.data[i + 2]
+ data.data[i] = brightness + 100
+ data.data[i + 1] = brightness + 50
+ data.data[i + 2] = brightness
}
- ctx.putImageData(data, x, y);
- return ctx;
+ ctx.putImageData(data, x, y)
+ return ctx
}
-function shorten(text, maxLen = 2000) {
- return text.length > maxLen ? `${text.substr(0, maxLen - 3)}...` : text;
+function shorten (text, maxLen = 2000) {
+ return text.length > maxLen ? `${text.substr(0, maxLen - 3)}...` : text
}
-function trimArray(arr, maxLen = 10) {
+function trimArray (arr, maxLen = 10) {
if (arr.length > maxLen) {
- const len = arr.length - maxLen;
- arr = arr.slice(0, maxLen);
- arr.push(`${len} more...`);
+ const len = arr.length - maxLen
+ arr = arr.slice(0, maxLen)
+ arr.push(`${len} more...`)
}
- return arr;
+ return arr
}
-function sendError(message, error) {
+function sendError (message, error) {
message.channel.send({
embed: {
color: 15158332,
title: error.name,
- description: error.message,
- },
- });
+ description: error.message
+ }
+ })
}
-async function getSongInfo(url) {
+async function getSongInfo (url) {
try {
- let data = await ytdl.getInfo(url);
- return data;
+ const data = await ytdl.getInfo(url)
+ return data
} catch (error) {
- console.log(error);
- sendErrorMail(error);
+ console.log(error)
+ sendErrorMail(error)
}
}
-function secondsCoverter(time) {
- console.log(time);
- let second = time.split(".");
- var timestamp = parseInt(second[0]);
- var hours = Math.floor(timestamp / 60 / 60);
- var minutes = Math.floor(timestamp / 60) - hours * 60;
- var seconds = timestamp % 60;
+function secondsCoverter (time) {
+ console.log(time)
+ const second = time.split('.')
+ var timestamp = parseInt(second[0])
+ var hours = Math.floor(timestamp / 60 / 60)
+ var minutes = Math.floor(timestamp / 60) - hours * 60
+ var seconds = timestamp % 60
if (hours > 0) {
- return hours + ":" + minutes + ":" + seconds;
- } else return minutes + ":" + seconds;
+ return hours + ':' + minutes + ':' + seconds
+ } else return minutes + ':' + seconds
}
-function getThumbnail(url) {
- let ids = getVideoId(url);
- return `http://img.youtube.com/vi/${ids.id}/maxresdefault.jpg`;
+function getThumbnail (url) {
+ const ids = getVideoId(url)
+ return `http://img.youtube.com/vi/${ids.id}/maxresdefault.jpg`
}
-function shuffleArray(array) {
- let m = array.length,
- t,
- i;
+function shuffleArray (array) {
+ let m = array.length
+ let t
+ let i
while (m) {
- i = Math.floor(Math.random() * m--);
- t = array[m];
- array[m] = array[i];
- array[i] = t;
+ i = Math.floor(Math.random() * m--)
+ t = array[m]
+ array[m] = array[i]
+ array[i] = t
}
- return array;
+ return array
}
-function sendErrorMail(error) {
+function sendErrorMail (error) {
// const filepath = "log.txt";
send(
{
- subject: "attached ",
- text: `${error.name} \n` + `${error.message}`,
+ subject: 'attached ',
+ text: `${error.name} \n` + `${error.message}`
},
function (err, res, full) {
- if (err) return console.log("send() callback returned: err:", err);
- console.log("send() callback returned: res:", res);
+ if (err) return console.log('send() callback returned: err:', err)
+ console.log('send() callback returned: res:', res)
}
- );
+ )
}
-function updatePresence(message, serverQueue) {
+function updatePresence (message, serverQueue) {
if (serverQueue.isPlaying === true) {
message.member.guild.channels.cache
.find((x) => x.id === serverQueue.textChannel.id)
- .setTopic("Playing " + serverQueue.queue[0].title);
+ .setTopic('Playing ' + serverQueue.queue[0].title)
}
if (serverQueue.isPlaying === false) {
message.member.guild.channels.cache
.find((x) => x.id === serverQueue.textChannel.id)
- .setTopic("Not playing");
+ .setTopic('Not playing')
}
}
-function isYT(url) {
- let y = /(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/g.test(
+function isYT (url) {
+ const y = /(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/g.test(
url
- );
- return true ? y : false;
+ )
+ return true ? y : false
}
-function isSC(url) {
- let s = /((https:\/\/)|(http:\/\/)|(www.)|(m\.)|(\s))+(soundcloud.com\/)+[a-zA-Z0-9\-\.]+(\/)+[a-zA-Z0-9\-\.]+/g.test(
+function isSC (url) {
+ const s = /((https:\/\/)|(http:\/\/)|(www.)|(m\.)|(\s))+(soundcloud.com\/)+[a-zA-Z0-9\-\.]+(\/)+[a-zA-Z0-9\-\.]+/g.test(
url
- );
- return true ? s : false;
+ )
+ return true ? s : false
}
-function formatNumber(number) {
- return number.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
+function formatNumber (number) {
+ return number.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
-async function getvideourl(args) {
- const r = await yts(args);
- if (r) return r.videos[0].url;
- else return null;
+async function getvideourl (args) {
+ const r = await yts(args)
+ if (r) return r.videos[0].url
+ else return null
}
-function removeAccents(str) {
+function removeAccents (str) {
var AccentsMap = [
- "aàảãáạăằẳẵắặâầẩẫấậ",
- "AÀẢÃÁẠĂẰẲẴẮẶÂẦẨẪẤẬ",
- "dđ",
- "DĐ",
- "eèẻẽéẹêềểễếệ",
- "EÈẺẼÉẸÊỀỂỄẾỆ",
- "iìỉĩíị",
- "IÌỈĨÍỊ",
- "oòỏõóọôồổỗốộơờởỡớợ",
- "OÒỎÕÓỌÔỒỔỖỐỘƠỜỞỠỚỢ",
- "uùủũúụưừửữứự",
- "UÙỦŨÚỤƯỪỬỮỨỰ",
- "yỳỷỹýỵ",
- "YỲỶỸÝỴ",
- ];
+ 'aàảãáạăằẳẵắặâầẩẫấậ',
+ 'AÀẢÃÁẠĂẰẲẴẮẶÂẦẨẪẤẬ',
+ 'dđ',
+ 'DĐ',
+ 'eèẻẽéẹêềểễếệ',
+ 'EÈẺẼÉẸÊỀỂỄẾỆ',
+ 'iìỉĩíị',
+ 'IÌỈĨÍỊ',
+ 'oòỏõóọôồổỗốộơờởỡớợ',
+ 'OÒỎÕÓỌÔỒỔỖỐỘƠỜỞỠỚỢ',
+ 'uùủũúụưừửữứự',
+ 'UÙỦŨÚỤƯỪỬỮỨỰ',
+ 'yỳỷỹýỵ',
+ 'YỲỶỸÝỴ'
+ ]
for (var i = 0; i < AccentsMap.length; i++) {
- var re = new RegExp("[" + AccentsMap[i].substr(1) + "]", "g");
- var char = AccentsMap[i][0];
- str = str.replace(re, char);
+ var re = new RegExp('[' + AccentsMap[i].substr(1) + ']', 'g')
+ var char = AccentsMap[i][0]
+ str = str.replace(re, char)
}
- return str;
+ return str
}
module.exports = {
sendResponse,
@@ -574,5 +573,5 @@ module.exports = {
shuffleArray,
formatNumber,
getvideourl,
- removeAccents,
-};
+ removeAccents
+}