Browse Source

Clean up code and use ESLint

pull/22/head
Abheek Dhawan 3 years ago
parent
commit
414229b9a7
Signed by: abheekd GPG Key ID: 7BE81B8C14475B67
  1. 797
      index.js

797
index.js

@ -2,433 +2,434 @@
require('dotenv').config(); require('dotenv').config();
const Discord = require("discord.js"); const Discord = require('discord.js');
const client = new Discord.Client({ const client = new Discord.Client({
intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS", "DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS"/*, "GUILD_MEMBERS", "GUILD_PRESENCES"*/], intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MESSAGE_REACTIONS', 'DIRECT_MESSAGES', 'DIRECT_MESSAGE_REACTIONS'],
partials: ["MESSAGE", "CHANNEL", "REACTION"], partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
}); });
const axios = require("axios"); const axios = require('axios');
const mongoose = require("mongoose"); const mongoose = require('mongoose');
const gitlog = require("gitlog").default; const gitlog = require('gitlog').default;
const decode = require('html-entities').decode; const decode = require('html-entities').decode;
const userScore = require("./models/userScore"); const userScore = require('./models/userScore');
const generatedRound = require("./models/generateRound"); const generatedRound = require('./models/generateRound');
const config = require("./config.json"); const config = require('./config.json');
const helpMessage = "AwesomeSciBo has migrated to using slash commands! You can take a look at the different commands by typing `/` and clicking on the AwesomeSciBo icon." const helpMessage = 'AwesomeSciBo has migrated to using slash commands! You can take a look at the different commands by typing `/` and clicking on the AwesomeSciBo icon.';
const slashCommands = require('./slashCommands.json') const slashCommands = require('./slashCommands.json');
client.once("ready", () => { client.once('ready', () => {
client.application.commands.set(slashCommands); client.application.commands.set(slashCommands);
// Connect to MongoDB using mongoose // Connect to MongoDB using mongoose
if (!process.env.CI) { if (!process.env.CI) {
mongoose mongoose
.connect(process.env.MONGO_URI, { .connect(process.env.MONGO_URI, {
useUnifiedTopology: true, useUnifiedTopology: true,
useNewUrlParser: true, useNewUrlParser: true,
}) })
.then(() => { .then(() => {
// Log client tag and set status // Log client tag and set status
console.log(`Logged in as: ${client.user.username}!`); console.log(`Logged in as: ${client.user.username}!`);
client.user.setActivity( client.user.setActivity(
'for /help', 'for /help',
{ type: "WATCHING" } { type: 'WATCHING' },
); );
}) })
.catch((err) => console.log(err)); .catch((err) => console.log(err));
} }
}); });
client.on("guildCreate", (guild) => { client.on('guildCreate', () => {
const topggAuthHeader = { const topggAuthHeader = {
headers: { headers: {
'Authorization': config.topggauth 'Authorization': config.topggauth,
} },
}; };
axios.post(`https://top.gg/api/bots/${client.user.id}/stats`, { server_count: client.guilds.cache.size }, topggAuthHeader).then(response => { console.log(response); }) axios.post(`https://top.gg/api/bots/${client.user.id}/stats`, { server_count: client.guilds.cache.size }, topggAuthHeader).then(response => { console.log(response); });
//guild.commands.set(slashCommands);
const welcomeChannel = guild.channels.cache
.find(
(channel) =>
// Find channel by name
channel.name === "general" && channel.type === "text"
)
if (welcomeChannel) {
welcomeChannel.send("'Sup, I'm the AwesomeSciBo bot! Use `/help` to learn more about me!")
.catch(console.error);
}
}); });
client.on("guildDelete", () => { client.on('guildDelete', () => {
const topggAuthHeader = { const topggAuthHeader = {
headers: { headers: {
'Authorization': config.topggauth 'Authorization': config.topggauth,
} },
}; };
axios.post(`https://top.gg/api/bots/${client.user.id}/stats`, { server_count: client.guilds.cache.size }, topggAuthHeader); axios.post(`https://top.gg/api/bots/${client.user.id}/stats`, { server_count: client.guilds.cache.size }, topggAuthHeader);
}); });
async function updateScore(isCorrect, score, authorId) { async function updateScore(isCorrect, score, authorId) {
if (!isCorrect) { if (!isCorrect) {
return `Nice try! Your score is still ${score}.`; return `Nice try! Your score is still ${score}.`;
} else { }
score += 4; else {
if (score == 4) { score += 4;
const newUserScore = new userScore({ if (score == 4) {
authorID: authorId, const newUserScore = new userScore({
score: score, authorID: authorId,
}); score: score,
newUserScore.save((err) => });
err newUserScore.save((err) =>
? console.log("Error creating new user for scoring") err
: console.log("Sucessfully created user to score.") ? console.log('Error creating new user for scoring')
); : console.log('Sucessfully created user to score.'),
} else { );
const doc = await userScore.findOne({ }
authorID: authorId, else {
}); const doc = await userScore.findOne({
doc.score = doc.score + 4; authorID: authorId,
doc.save(); });
} doc.score = doc.score + 4;
doc.save();
return `Great job! Your score is now ${score}.`; }
}
return `Great job! Your score is now ${score}.`;
}
} }
async function training(subject, interaction) { async function training(subject, interaction) {
const authorId = interaction.user.id; const authorId = interaction.user.id;
let score; let score;
userScore userScore
.findOne({ authorID: authorId }) .findOne({ authorID: authorId })
.lean() .lean()
.then((obj, err) => { .then((obj, err) => {
if (!obj) { if (!obj) {
score = 0; score = 0;
} else if (obj) { }
score = obj.score; else if (obj) {
} else { score = obj.score;
console.log(err); }
} else {
}); console.log(err);
}
let categoryArray = []; });
switch (subject) { let categoryArray = [];
case null:
categoryArray = ["BIOLOGY", "PHYSICS", "CHEMISTRY", "EARTH AND SPACE", "ASTRONOMY", "MATH"]; switch (subject) {
break; case null:
case "astro": categoryArray = ['BIOLOGY', 'PHYSICS', 'CHEMISTRY', 'EARTH AND SPACE', 'ASTRONOMY', 'MATH'];
case "astronomy": break;
categoryArray = ["ASTRONOMY"] case 'astro':
break; case 'astronomy':
case "bio": categoryArray = ['ASTRONOMY'];
case "biology": break;
categoryArray = ["BIOLOGY"]; case 'bio':
break; case 'biology':
case "ess": categoryArray = ['BIOLOGY'];
case "earth science": break;
case "es": case 'ess':
categoryArray = ["EARTH SCIENCE"]; case 'earth science':
break; case 'es':
case "chem": categoryArray = ['EARTH SCIENCE'];
case "chemistry": break;
categoryArray = ["CHEMISTRY"]; case 'chem':
break; case 'chemistry':
case "phys": categoryArray = ['CHEMISTRY'];
case "physics": break;
categoryArray = ["PHYSICS"]; case 'phys':
break; case 'physics':
case "math": categoryArray = ['PHYSICS'];
categoryArray = ["MATH"]; break;
break; case 'math':
case "energy": categoryArray = ['MATH'];
categoryArray = ["ENERGY"]; break;
break; case 'energy':
default: categoryArray = ['ENERGY'];
interaction.reply( break;
new Discord.MessageEmbed() default:
.setDescription("<:red_x:816791117671825409> Not a valid subject!") interaction.reply(
.setColor("#ffffff") new Discord.MessageEmbed()
); .setDescription('<:red_x:816791117671825409> Not a valid subject!')
return; .setColor('#ffffff'),
} );
return;
axios }
.post("https://scibowldb.com/api/questions/random", { categories: categoryArray })
.then((res) => { axios
data = res.data.question; .post('https://scibowldb.com/api/questions/random', { categories: categoryArray })
const tossupQuestion = data.tossup_question; .then((res) => {
const tossupAnswer = data.tossup_answer; const data = res.data.question;
const messageFilter = (m) => m.author.id === authorId; const tossupQuestion = data.tossup_question;
interaction.reply({ content: decode(tossupQuestion) + `\n\n||Source: ${data.uri}||` }) const tossupAnswer = data.tossup_answer;
.then(() => { const messageFilter = (m) => m.author.id === authorId;
interaction.channel.awaitMessages({ interaction.reply({ content: decode(tossupQuestion) + `\n\n||Source: ${data.uri}||` })
messageFilter, .then(() => {
max: 1 interaction.channel.awaitMessages({
}) messageFilter,
.then(collected => { max: 1,
answerMsg = collected.first(); })
.then(collected => {
let predicted = null; const answerMsg = collected.first();
if (data.tossup_format === "Multiple Choice") {
if ( let predicted = null;
answerMsg.content.charAt(0).toLowerCase() === if (data.tossup_format === 'Multiple Choice') {
tossupAnswer.charAt(0).toLowerCase() if (
) { answerMsg.content.charAt(0).toLowerCase() ===
predicted = "correct"; tossupAnswer.charAt(0).toLowerCase()
} else { ) {
predicted = "incorrect"; predicted = 'correct';
} }
} else { else {
if ( predicted = 'incorrect';
answerMsg.content.toLowerCase() === }
tossupAnswer.toLowerCase() }
) { else if (
predicted = "correct"; answerMsg.content.toLowerCase() ===
} else { tossupAnswer.toLowerCase()
predicted = "incorrect"; ) {
} predicted = 'correct';
} }
else {
if (predicted === "correct") { predicted = 'incorrect';
updateScore(true, score, authorId).then((msgToReply) => }
answerMsg.reply(msgToReply)
); if (predicted === 'correct') {
} else { updateScore(true, score, authorId).then((msgToReply) =>
const overrideEmbed = new Discord.MessageEmbed() answerMsg.reply(msgToReply),
.setAuthor(answerMsg.author.tag, answerMsg.author.displayAvatarURL()) );
.addField("Correct answer", `\`${tossupAnswer}\``) }
.setDescription(`It seems your answer was incorrect. Please react with <:override:842778128966615060> to override your answer if you think you got it right.`) else {
.setColor("#ffffff") const overrideEmbed = new Discord.MessageEmbed()
.setTimestamp(); .setAuthor(answerMsg.author.tag, answerMsg.author.displayAvatarURL())
answerMsg.channel.send({ .addField('Correct answer', `\`${tossupAnswer}\``)
embeds: [overrideEmbed] .setDescription('It seems your answer was incorrect. Please react with <:override:842778128966615060> to override your answer if you think you got it right.')
}) .setColor('#ffffff')
.then(overrideMsg => { .setTimestamp();
overrideMsg.react("<:override:842778128966615060>"); answerMsg.channel.send({
const filter = (reaction, user) => { embeds: [overrideEmbed],
return ( })
["override"].includes(reaction.emoji.name) && .then(overrideMsg => {
user.id === answerMsg.author.id overrideMsg.react('<:override:842778128966615060>');
); const filter = (reaction, user) => {
}; return (
overrideMsg ['override'].includes(reaction.emoji.name) &&
.awaitReactions({ user.id === answerMsg.author.id
filter, );
max: 1 };
}) overrideMsg
.then(() => { .awaitReactions({
updateScore(true, score, authorId).then((msgToReply) => filter,
answerMsg.reply(msgToReply) max: 1,
); })
}).catch(console.error); .then(() => {
}).catch(console.error); updateScore(true, score, authorId).then((msgToReply) =>
} answerMsg.reply(msgToReply),
}).catch(console.error); );
}).catch(console.error); }).catch(console.error);
}).catch(console.error); }).catch(console.error);
} }
}).catch(console.error);
}).catch(console.error);
}).catch(console.error);
}
function sendHelpMessage(interaction) { function sendHelpMessage(interaction) {
const helpEmbed = new Discord.MessageEmbed().setDescription(helpMessage).setColor("ffffff"); const helpEmbed = new Discord.MessageEmbed().setDescription(helpMessage).setColor('ffffff');
interaction.reply({ embeds: [helpEmbed] }); interaction.reply({ embeds: [helpEmbed] });
} }
function showLeaderboard(interaction) { function showLeaderboard(interaction) {
let messageContent = ""; let messageContent = '';
userScore userScore
.find({}) .find({})
.sort({ score: -1 }) // Sort by descending order .sort({ score: -1 }) // Sort by descending order
.exec((err, obj) => { .exec((err, obj) => {
if (err) { if (err) {
console.log(err); console.log(err);
return interaction.reply( return interaction.reply(
"Uh oh! :( There was an internal error. Please try again." 'Uh oh! :( There was an internal error. Please try again.',
); );
} }
if (obj.length < 10) { if (obj.length < 10) {
// Need at least 10 scores for top 10 // Need at least 10 scores for top 10
return interaction.reply( return interaction.reply(
`There are only ${obj.length} users, we need at least 10!` `There are only ${obj.length} users, we need at least 10!`,
); );
} }
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
messageContent += `${i + 1}: <@${obj[i].authorID}>: ${obj[i].score}\n`; // Loop through each user and add their name and score to leaderboard content messageContent += `${i + 1}: <@${obj[i].authorID}>: ${obj[i].score}\n`; // Loop through each user and add their name and score to leaderboard content
} }
const leaderboardEmbed = new Discord.MessageEmbed() const leaderboardEmbed = new Discord.MessageEmbed()
.setTitle("Top Ten!") .setTitle('Top Ten!')
.setDescription(messageContent) .setDescription(messageContent)
.setColor("#ffffff") .setColor('#ffffff');
interaction.reply({ embeds: [leaderboardEmbed] }); interaction.reply({ embeds: [leaderboardEmbed] });
}); });
} }
async function about(action, interaction) { async function about(action, interaction) {
if (action === "contributors") { if (action === 'contributors') {
const contributorEmbed = new Discord.MessageEmbed().setTitle("Contributors") const contributorEmbed = new Discord.MessageEmbed().setTitle('Contributors')
.addField("Creator", `<@745063586422063214> [ADawesomeguy#3602]`, true) .addField('Creator', '<@745063586422063214> [ADawesomeguy#3602]', true)
.addField("Contributors", `<@650525101048987649> [tEjAs#8127]\n<@426864344463048705> [tetrident#9396]`, true) // Add more contributors here, first one is Abheek, second one is Tejas .addField('Contributors', '<@650525101048987649> [tEjAs#8127]\n<@426864344463048705> [tetrident#9396]', true) // Add more contributors here, first one is Abheek, second one is Tejas
.setTimestamp() .setTimestamp()
.setColor("#ffffff"); .setColor('#ffffff');
interaction.reply({ embeds: [contributorEmbed] }); interaction.reply({ embeds: [contributorEmbed] });
} else if (action === "changelog") { }
const gitRepoLocation = __dirname; else if (action === 'changelog') {
const gitRepoLocation = __dirname;
const commits = gitlog({
repo: gitRepoLocation, const commits = gitlog({
number: 5, repo: gitRepoLocation,
fields: ["hash", "abbrevHash", "subject", "authorName", "authorDateRel"], number: 5,
}); fields: ['hash', 'abbrevHash', 'subject', 'authorName', 'authorDateRel'],
});
const changelogEmbed = new Discord.MessageEmbed()
.setAuthor(interaction.user.tag, interaction.user.displayAvatarURL()) const changelogEmbed = new Discord.MessageEmbed()
.setTitle("Changelog") .setAuthor(interaction.user.tag, interaction.user.displayAvatarURL())
.setColor("#ffffff") .setTitle('Changelog')
.setTimestamp(); .setColor('#ffffff')
.setTimestamp();
commits.forEach(commit => {
changelogEmbed.addField(commit.abbrevHash, `> \`Hash:\`${commit.hash}\n> \`Subject:\`${commit.subject}\n> \`Author:\`${commit.authorName}\n> \`Date:\`${commit.authorDateRel}\n> \`Link\`: [GitHub](https://github.com/ADawesomeguy/AwesomeSciBo/commit/${commit.hash})\n`); commits.forEach(commit => {
}); changelogEmbed.addField(commit.abbrevHash, `> \`Hash:\`${commit.hash}\n> \`Subject:\`${commit.subject}\n> \`Author:\`${commit.authorName}\n> \`Date:\`${commit.authorDateRel}\n> \`Link\`: [GitHub](https://github.com/ADawesomeguy/AwesomeSciBo/commit/${commit.hash})\n`);
});
interaction.reply({ embeds: [changelogEmbed] });
} else if (action === "bot") { interaction.reply({ embeds: [changelogEmbed] });
await client.guilds.fetch(); }
const trainingDocuments = await userScore.countDocuments({}); else if (action === 'bot') {
const aboutBotEmbed = new Discord.MessageEmbed() await client.guilds.fetch();
.setAuthor(interaction.user.tag, interaction.user.displayAvatarURL()) const trainingDocuments = await userScore.countDocuments({});
.setTitle("About AwesomeSciBo") const aboutBotEmbed = new Discord.MessageEmbed()
.addField("Servers", `${client.guilds.cache.size}`, true) .setAuthor(interaction.user.tag, interaction.user.displayAvatarURL())
.addField("Training Users", `${trainingDocuments}`, true) .setTitle('About AwesomeSciBo')
.setTimestamp(); .addField('Servers', `${client.guilds.cache.size}`, true)
.addField('Training Users', `${trainingDocuments}`, true)
interaction.reply({ embeds: [aboutBotEmbed] }); .setTimestamp();
}
interaction.reply({ embeds: [aboutBotEmbed] });
}
} }
async function rounds(action, interaction) { async function rounds(action, interaction) {
if (action === "generate") { if (action === 'generate') {
let i; let i;
let finalizedHTML = '<html><head><link rel="preconnect" href="https://fonts.gstatic.com"><link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet"> </head><body style="width: 70%; margin-left: auto; margin-right: auto;"><h2 style="text-align: center; text-decoration: underline overline; padding: 7px;">ROUND GENERATED BY AWESOMESCIBO USING THE SCIBOWLDB API</h2>'; let finalizedHTML = '<html><head><link rel=\'preconnect\' href=\'https://fonts.gstatic.com\'><link href=\'https://fonts.googleapis.com/css2?family=Ubuntu&display=swap\' rel=\'stylesheet\'> </head><body style=\'width: 70%; margin-left: auto; margin-right: auto;\'><h2 style=\'text-align: center; text-decoration: underline overline; padding: 7px;\'>ROUND GENERATED BY AWESOMESCIBO USING THE SCIBOWLDB API</h2>';
let tossup_question; let tossup_question;
let question_category; let question_category;
let tossup_format; let tossup_format;
let tossup_answer; let tossup_answer;
let bonus_question; let bonus_question;
let bonus_format; let bonus_format;
let bonus_answer; let bonus_answer;
let htmlContent = ""; let htmlContent = '';
await axios.post("https://scibowldb.com/api/questions", { categories: ["BIOLOGY", "PHYSICS", "CHEMISTRY", "EARTH AND SPACE", "ASTRONOMY", "MATH"] }) await axios.post('https://scibowldb.com/api/questions', { categories: ['BIOLOGY', 'PHYSICS', 'CHEMISTRY', 'EARTH AND SPACE', 'ASTRONOMY', 'MATH'] })
.then((response) => { .then((response) => {
for (i = 1; i < 26; i++) { for (i = 1; i < 26; i++) {
data = response.data.questions[Math.floor(Math.random() * response.data.questions.length)]; const data = response.data.questions[Math.floor(Math.random() * response.data.questions.length)];
tossup_question = data.tossup_question; tossup_question = data.tossup_question;
tossup_answer = data.tossup_answer; tossup_answer = data.tossup_answer;
question_category = data.category; question_category = data.category;
tossup_format = data.tossup_format; tossup_format = data.tossup_format;
bonus_question = data.bonus_question; bonus_question = data.bonus_question;
bonus_answer = data.bonus_answer; bonus_answer = data.bonus_answer;
bonus_format = data.bonus_format; bonus_format = data.bonus_format;
htmlContent = `<br><br><h3 style="text-align: center;"><strong>TOSS-UP</strong></h3>\n<br>` + `${i}) <strong>${question_category}</strong>` + " " + `<em>${tossup_format}</em>` + " " + tossup_question + "<br><br>" + "<strong>ANSWER:</strong> " + tossup_answer + "<br>"; htmlContent = '<br><br><h3 style=\'text-align: center;\'><strong>TOSS-UP</strong></h3>\n<br>' + `${i}) <strong>${question_category}</strong>` + ' ' + `<em>${tossup_format}</em>` + ' ' + tossup_question + '<br><br>' + '<strong>ANSWER:</strong> ' + tossup_answer + '<br>';
htmlContent += `<br><br><h3 style="text-align: center;"><strong>BONUS</strong></h3>\n<br>` + `${i}) <strong>${question_category}</strong>` + " " + `<em>${bonus_format}</em>` + " " + bonus_question + "<br><br>" + "<strong>ANSWER:</strong> " + bonus_answer + "<br><br><hr><br>"; htmlContent += '<br><br><h3 style=\'text-align: center;\'><strong>BONUS</strong></h3>\n<br>' + `${i}) <strong>${question_category}</strong>` + ' ' + `<em>${bonus_format}</em>` + ' ' + bonus_question + '<br><br>' + '<strong>ANSWER:</strong> ' + bonus_answer + '<br><br><hr><br>';
htmlContent = htmlContent.replace(/\n/g, "<br>"); htmlContent = htmlContent.replace(/\n/g, '<br>');
finalizedHTML += htmlContent; finalizedHTML += htmlContent;
} }
newGeneratedRound = new generatedRound({
htmlContent: finalizedHTML, const newGeneratedRound = new generatedRound({
requestedBy: interaction.user.id, htmlContent: finalizedHTML,
authorTag: interaction.user.tag, requestedBy: interaction.user.id,
timestamp: new Date().toISOString(), authorTag: interaction.user.tag,
}); timestamp: new Date().toISOString(),
newGeneratedRound.save((err, round) => { });
if (err) {
console.log(err); newGeneratedRound.save((err, round) => {
return; if (err) {
} console.log(err);
interaction.reply(`Here's your round: https://api.adawesome.tech/round/${round._id.toString()}`, { ephemeral: true }); return;
}); }
}); interaction.reply(`Here's your round: https://api.adawesome.tech/round/${round._id.toString()}`, { ephemeral: true });
} else if (action === "list"){ });
let rounds = await generatedRound.find({ requestedBy: interaction.user.id }).sort({ timestamp: -1 }); });
let finalMessage = ""; }
if (!rounds) { else if (action === 'list') {
interaction.reply("You haven't requested any rounds!"); let roundsList = await generatedRound.find({ requestedBy: interaction.user.id }).sort({ timestamp: -1 });
return; let finalMessage = '';
} if (!roundsList) {
interaction.reply('You haven\'t requested any roundsList!');
if (rounds.length > 5) { return;
rounds = rounds.slice(0, 5); }
}
if (roundsList.length > 5) {
rounds.forEach(async (item, index) => { roundsList = roundsList.slice(0, 5);
finalMessage += `${index + 1}. [${item.timestamp.split("T")[0]}](https://api.adawesome.tech/round/${item._id.toString()})\n`; }
});
roundsList.forEach(async (item, index) => {
const roundsEmbed = new Discord.MessageEmbed() finalMessage += `${index + 1}. [${item.timestamp.split('T')[0]}](https://api.adawesome.tech/round/${item._id.toString()})\n`;
.setAuthor(interaction.user.tag, interaction.user.displayAvatarURL()) });
.setTitle(`Last 5 rounds requested by ${interaction.user.tag}`)
.setDescription(finalMessage) const roundsListEmbed = new Discord.MessageEmbed()
.setTimestamp(); .setAuthor(interaction.user.tag, interaction.user.displayAvatarURL())
.setTitle(`Last 5 roundsList requested by ${interaction.user.tag}`)
interaction.reply({ .setDescription(finalMessage)
embeds: [roundsEmbed], .setTimestamp();
ephemeral: true
}); interaction.reply({
} else if (action === "hit"){ embeds: [roundsListEmbed],
let totalCount = await generatedRound.countDocuments({}); ephemeral: true,
let userCount = await generatedRound.countDocuments({ requestedBy: interaction.user.id }); });
}
interaction.reply(`Total Hits: ${totalCount}\nYour Hits: ${userCount}`); else if (action === 'hit') {
} const totalCount = await generatedRound.countDocuments({});
const userCount = await generatedRound.countDocuments({ requestedBy: interaction.user.id });
interaction.reply(`Total Hits: ${totalCount}\nYour Hits: ${userCount}`);
}
} }
async function result(interaction) { async function result(interaction) {
if (interaction.channel.id !== "930275699644825600") { if (interaction.channel.id !== '930275699644825600') {
return interaction.reply({ content: "This command is unavailable outside of the designated channel.", ephemeral: true }); return interaction.reply({ content: 'This command is unavailable outside of the designated channel.', ephemeral: true });
} }
const resultEmbed = new Discord.MessageEmbed(); const resultEmbed = new Discord.MessageEmbed();
resultEmbed.setTitle(`${interaction.options.get('location').value} Regionals`); resultEmbed.setTitle(`${interaction.options.get('location').value} Regionals`);
resultEmbed.setAuthor(interaction.user.tag, interaction.user.displayAvatarURL()); resultEmbed.setAuthor(interaction.user.tag, interaction.user.displayAvatarURL());
resultEmbed.addField("<a:winner:932137838592552960> Winner", `Congratulations to **${interaction.options.get("winner").value}**!`) resultEmbed.addField('<a:winner:932137838592552960> Winner', `Congratulations to **${interaction.options.get('winner').value}**!`);
if (interaction.options.get("runner-up")) resultEmbed.addField("<:second:932138645601800252> Runners-Up", interaction.options.get("runner-up").value); if (interaction.options.get('runner-up')) resultEmbed.addField('<:second:932138645601800252> Runners-Up', interaction.options.get('runner-up').value);
if (interaction.options.get("third-place")) resultEmbed.addField("<:third:932138645526315080> Third Place", interaction.options.get("third-place").value); if (interaction.options.get('third-place')) resultEmbed.addField('<:third:932138645526315080> Third Place', interaction.options.get('third-place').value);
if (interaction.options.get("honorable-mentions")) resultEmbed.addField("🎖️ Honorable Mentions", interaction.options.get("honorable-mentions").value); if (interaction.options.get('honorable-mentions')) resultEmbed.addField('🎖️ Honorable Mentions', interaction.options.get('honorable-mentions').value);
resultEmbed.setColor("#FFFFFF"); resultEmbed.setColor('#FFFFFF');
resultEmbed.setTimestamp(); resultEmbed.setTimestamp();
await interaction.reply({ embeds: [resultEmbed] }); await interaction.reply({ embeds: [resultEmbed] });
} }
client.on("interactionCreate", async interaction => { client.on('interactionCreate', async interaction => {
// If the interaction isn't a slash command, return // If the interaction isn't a slash command, return
if (!interaction.isCommand()) return; if (!interaction.isCommand()) return;
switch(interaction.commandName) { switch (interaction.commandName) {
case "help": case 'help':
sendHelpMessage(interaction); sendHelpMessage(interaction);
break; break;
case "train": case 'train':
training(interaction.options.get("subject") ? interaction.options.get("subject").value : null, interaction); training(interaction.options.get('subject') ? interaction.options.get('subject').value : null, interaction);
break; break;
case "rounds": case 'roundsList':
rounds(interaction.options.getSubcommand(), interaction); rounds(interaction.options.getSubcommand(), interaction);
break; break;
case "top": case 'top':
showLeaderboard(interaction); showLeaderboard(interaction);
break; break;
case "about": case 'about':
about(interaction.options.getSubcommand(), interaction); about(interaction.options.getSubcommand(), interaction);
break; break;
case "result": case 'result':
result(interaction); result(interaction);
} }
}) });
client client
.login(process.env.TOKEN) .login(process.env.TOKEN)
.then(() => console.log("Running!")) .then(() => console.log('Running!'))
.catch((error) => console.log(error)); .catch((error) => console.log(error));

Loading…
Cancel
Save