Browse Source

style: format with prettier

dependabot/npm_and_yarn/semver-5.7.2
Abheek Dhawan 2 years ago
parent
commit
bd7ffe8e9d
Signed by: abheekd GPG Key ID: 7BE81B8C14475B67
  1. 130
      src/commands/about.ts
  2. 34
      src/commands/help.ts
  3. 303
      src/commands/rounds.ts
  4. 90
      src/commands/score.ts
  5. 508
      src/commands/settings.ts
  6. 138
      src/commands/top.ts
  7. 581
      src/commands/train.ts
  8. 23
      src/deploy-commands.js
  9. 32
      src/events/interactionCreate.ts
  10. 58
      src/events/messageCreate.ts
  11. 21
      src/events/ready.ts
  12. 118
      src/helpers/db.ts
  13. 11
      src/helpers/env.ts
  14. 56
      src/helpers/log.ts
  15. 178
      src/helpers/util/pagination.ts
  16. 62
      src/index.ts
  17. 36
      src/models/generatedRound.ts
  18. 26
      src/models/userConfig.ts
  19. 20
      src/models/userScore.ts

130
src/commands/about.ts

@ -1,58 +1,72 @@
import { SlashCommandBuilder } from '@discordjs/builders'; import { SlashCommandBuilder } from "@discordjs/builders";
import { MessageEmbed, CommandInteraction } from 'discord.js'; import { MessageEmbed, CommandInteraction } from "discord.js";
import gitlog from 'gitlog'; import gitlog from "gitlog";
import userScore from '../models/userScore'; import userScore from "../models/userScore";
import { paginateInteraction } from '../helpers/util/pagination'; import { paginateInteraction } from "../helpers/util/pagination";
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('about') .setName("about")
.setDescription('Commands regarding the creation/development of the bot'); .setDescription("Commands regarding the creation/development of the bot");
export async function execute(interaction: CommandInteraction) { export async function execute(interaction: CommandInteraction) {
await interaction.deferReply(); await interaction.deferReply();
const client = interaction.client; const client = interaction.client;
const embeds: MessageEmbed[] = []; const embeds: MessageEmbed[] = [];
const contributorEmbed = new MessageEmbed().setTitle('Contributors') const contributorEmbed = new MessageEmbed()
.addField('Creator', '<@745063586422063214> [ADawesomeguy#3602]', true) .setTitle("Contributors")
.addField('Contributors', '<@650525101048987649> [tEjAs#8127]\n<@426864344463048705> [tetrident#9396]', true) // Add more contributors here, first one is Abheek, second one is Tejas .addField("Creator", "<@745063586422063214> [ADawesomeguy#3602]", true)
.setTimestamp() .addField(
.setColor('#ffffff'); "Contributors",
embeds.push(contributorEmbed); "<@650525101048987649> [tEjAs#8127]\n<@426864344463048705> [tetrident#9396]",
true
const gitRepoLocation = __dirname; ) // Add more contributors here, first one is Abheek, second one is Tejas
.setTimestamp()
const commits = gitlog({ .setColor("#ffffff");
repo: gitRepoLocation, embeds.push(contributorEmbed);
number: 5,
fields: ['hash', 'abbrevHash', 'subject', 'authorName', 'authorDateRel'], const gitRepoLocation = __dirname;
});
const commits = gitlog({
const changelogEmbed = new MessageEmbed() repo: gitRepoLocation,
.setAuthor({ name: interaction.user.tag, iconURL: interaction.user.displayAvatarURL() }) number: 5,
.setTitle('Changelog') fields: ["hash", "abbrevHash", "subject", "authorName", "authorDateRel"],
.setColor('#ffffff') });
.setTimestamp();
const changelogEmbed = new MessageEmbed()
commits.forEach(commit => { .setAuthor({
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`); name: interaction.user.tag,
}); iconURL: interaction.user.displayAvatarURL(),
embeds.push(changelogEmbed); })
.setTitle("Changelog")
await client.guilds.fetch(); .setColor("#ffffff")
const trainingDocuments = await userScore.countDocuments({}); .setTimestamp();
const aboutBotEmbed = new MessageEmbed()
.setAuthor({ name: interaction.user.tag, iconURL: interaction.user.displayAvatarURL() }) commits.forEach((commit) => {
.setTitle('About AwesomeSciBo') changelogEmbed.addField(
.addField('Servers', `${client.guilds.cache.size}`, true) commit.abbrevHash,
.addField('Training Users', `${trainingDocuments}`, true) `> \`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`
.setTimestamp(); );
});
embeds.push(aboutBotEmbed); embeds.push(changelogEmbed);
paginateInteraction(interaction, embeds); await client.guilds.fetch();
} const trainingDocuments = await userScore.countDocuments({});
const aboutBotEmbed = new MessageEmbed()
.setAuthor({
name: interaction.user.tag,
iconURL: interaction.user.displayAvatarURL(),
})
.setTitle("About AwesomeSciBo")
.addField("Servers", `${client.guilds.cache.size}`, true)
.addField("Training Users", `${trainingDocuments}`, true)
.setTimestamp();
embeds.push(aboutBotEmbed);
paginateInteraction(interaction, embeds);
}

34
src/commands/help.ts

@ -1,16 +1,18 @@
import { SlashCommandBuilder } from '@discordjs/builders'; import { SlashCommandBuilder } from "@discordjs/builders";
import { MessageEmbed, CommandInteraction } from 'discord.js'; import { MessageEmbed, CommandInteraction } from "discord.js";
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('help') .setName("help")
.setDescription('Replies with a help message explaining what the bot can do'); .setDescription("Replies with a help message explaining what the bot can do");
export async function execute(interaction: CommandInteraction) { export async function execute(interaction: CommandInteraction) {
await interaction.deferReply(); await interaction.deferReply();
await interaction.deferReply(); await interaction.deferReply();
const helpEmbed = new MessageEmbed() const helpEmbed = new MessageEmbed()
.setDescription('AwesomeSciBo has migrated to using slash commands! You can take a look at the different commands by typing `/` and clicking on the AwesomeSciBo icon.') .setDescription(
.setColor('#ffffff'); "AwesomeSciBo has migrated to using slash commands! You can take a look at the different commands by typing `/` and clicking on the AwesomeSciBo icon."
interaction.followUp({ embeds: [helpEmbed] }); )
} .setColor("#ffffff");
interaction.followUp({ embeds: [helpEmbed] });
}

303
src/commands/rounds.ts

@ -1,125 +1,178 @@
import { SlashCommandBuilder } from '@discordjs/builders'; import { SlashCommandBuilder } from "@discordjs/builders";
import { MessageEmbed, CommandInteraction } from 'discord.js'; import { MessageEmbed, CommandInteraction } from "discord.js";
import axios from 'axios'; import axios from "axios";
import log from '../helpers/log'; import log from "../helpers/log";
import generatedRound from '../models/generatedRound'; import generatedRound from "../models/generatedRound";
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('rounds') .setName("rounds")
.setDescription('Commands regarding the generation of rounds') .setDescription("Commands regarding the generation of rounds")
.addSubcommand(subcommand => { .addSubcommand((subcommand) => {
subcommand subcommand
.setName('generate') .setName("generate")
.setDescription('Generates a round with randomized questions from https://scibowldb.com/'); .setDescription(
return subcommand; "Generates a round with randomized questions from https://scibowldb.com/"
}) );
.addSubcommand(subcommand => { return subcommand;
subcommand })
.setName('list') .addSubcommand((subcommand) => {
.setDescription('Lists your 5 most recently generated rounds with links'); subcommand
return subcommand; .setName("list")
}) .setDescription("Lists your 5 most recently generated rounds with links");
.addSubcommand(subcommand => { return subcommand;
subcommand })
.setName('hit') .addSubcommand((subcommand) => {
.setDescription('Shows the total number of rounds hit as well as the number for the specific user'); subcommand
return subcommand; .setName("hit")
}); .setDescription(
"Shows the total number of rounds hit as well as the number for the specific user"
export async function execute(interaction: CommandInteraction) { );
const action = interaction.options.getSubcommand(); return subcommand;
switch (action) { });
case 'generate': {
interaction.deferReply({ ephemeral: true }); export async function execute(interaction: CommandInteraction) {
const action = interaction.options.getSubcommand();
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>'; switch (action) {
let tossup_question: string; case "generate": {
let question_category: string; interaction.deferReply({ ephemeral: true });
let tossup_format: string;
let tossup_answer: string; let finalizedHTML =
let bonus_question: string; "<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 bonus_format: string; let tossup_question: string;
let bonus_answer: string; let question_category: string;
let htmlContent = ''; let tossup_format: string;
await axios.post('https://scibowldb.com/api/questions', { categories: ['BIOLOGY', 'PHYSICS', 'CHEMISTRY', 'EARTH AND SPACE', 'ASTRONOMY', 'MATH'] }) let tossup_answer: string;
.then((response) => { let bonus_question: string;
for (let i = 1; i < 26; i++) { let bonus_format: string;
const questionData = response.data.questions[Math.floor(Math.random() * response.data.questions.length)]; let bonus_answer: string;
tossup_question = questionData.tossup_question; let htmlContent = "";
tossup_answer = questionData.tossup_answer; await axios
question_category = questionData.category; .post("https://scibowldb.com/api/questions", {
tossup_format = questionData.tossup_format; categories: [
bonus_question = questionData.bonus_question; "BIOLOGY",
bonus_answer = questionData.bonus_answer; "PHYSICS",
bonus_format = questionData.bonus_format; "CHEMISTRY",
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>'; "EARTH AND SPACE",
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>'; "ASTRONOMY",
htmlContent = htmlContent.replace(/\n/g, '<br>'); "MATH",
finalizedHTML += htmlContent; ],
} })
.then((response) => {
const newGeneratedRound = new generatedRound({ for (let i = 1; i < 26; i++) {
htmlContent: finalizedHTML, const questionData =
requestedBy: interaction.user.id, response.data.questions[
authorTag: interaction.user.tag, Math.floor(Math.random() * response.data.questions.length)
timestamp: new Date().toISOString(), ];
}); tossup_question = questionData.tossup_question;
tossup_answer = questionData.tossup_answer;
newGeneratedRound.save((err, round) => { question_category = questionData.category;
if (err) { tossup_format = questionData.tossup_format;
log({ logger: 'rounds', content: `Saving round to DB failed: ${err}`, level: 'error' }); bonus_question = questionData.bonus_question;
return; bonus_answer = questionData.bonus_answer;
} bonus_format = questionData.bonus_format;
interaction.followUp({ htmlContent =
content: `Here's your round: https://api.adawesome.tech/round/${round._id.toString()}`, "<br><br><h3 style='text-align: center;'><strong>TOSS-UP</strong></h3>\n<br>" +
ephemeral: true, `${i}) <strong>${question_category}</strong>` +
}); " " +
}); `<em>${tossup_format}</em>` +
}); " " +
break; tossup_question +
} "<br><br>" +
"<strong>ANSWER:</strong> " +
case 'list': { tossup_answer +
interaction.deferReply({ ephemeral: true }); "<br>";
htmlContent +=
let roundsList = await generatedRound.find({ requestedBy: interaction.user.id }).sort({ timestamp: -1 }); "<br><br><h3 style='text-align: center;'><strong>BONUS</strong></h3>\n<br>" +
let finalMessage = ''; `${i}) <strong>${question_category}</strong>` +
if (!roundsList) { " " +
interaction.followUp('You haven\'t requested any rounds!'); `<em>${bonus_format}</em>` +
return; " " +
} bonus_question +
"<br><br>" +
if (roundsList.length > 5) { "<strong>ANSWER:</strong> " +
roundsList = roundsList.slice(0, 5); bonus_answer +
} "<br><br><hr><br>";
htmlContent = htmlContent.replace(/\n/g, "<br>");
roundsList.forEach(async (item, index) => { finalizedHTML += htmlContent;
finalMessage += `${index + 1}. [${item.timestamp.split('T')[0]}](https://api.adawesome.tech/round/${item._id.toString()})\n`; }
});
const newGeneratedRound = new generatedRound({
const roundsListEmbed = new MessageEmbed() htmlContent: finalizedHTML,
.setAuthor({ name: interaction.user.tag, iconURL: interaction.user.displayAvatarURL() }) requestedBy: interaction.user.id,
.setTitle('Last 5 rounds requested') authorTag: interaction.user.tag,
.setDescription(finalMessage) timestamp: new Date().toISOString(),
.setTimestamp(); });
interaction.followUp({ newGeneratedRound.save((err, round) => {
embeds: [roundsListEmbed], if (err) {
ephemeral: true, log({
}); logger: "rounds",
break; content: `Saving round to DB failed: ${err}`,
} level: "error",
});
case 'hit': { return;
await interaction.deferReply(); }
interaction.followUp({
const totalCount = await generatedRound.countDocuments({}); content: `Here's your round: https://api.adawesome.tech/round/${round._id.toString()}`,
const userCount = await generatedRound.countDocuments({ requestedBy: interaction.user.id }); ephemeral: true,
});
interaction.followUp(`Total Hits: ${totalCount}\nYour Hits: ${userCount}`); });
break; });
} break;
} }
}
case "list": {
interaction.deferReply({ ephemeral: true });
let roundsList = await generatedRound
.find({ requestedBy: interaction.user.id })
.sort({ timestamp: -1 });
let finalMessage = "";
if (!roundsList) {
interaction.followUp("You haven't requested any rounds!");
return;
}
if (roundsList.length > 5) {
roundsList = roundsList.slice(0, 5);
}
roundsList.forEach(async (item, index) => {
finalMessage += `${index + 1}. [${
item.timestamp.split("T")[0]
}](https://api.adawesome.tech/round/${item._id.toString()})\n`;
});
const roundsListEmbed = new MessageEmbed()
.setAuthor({
name: interaction.user.tag,
iconURL: interaction.user.displayAvatarURL(),
})
.setTitle("Last 5 rounds requested")
.setDescription(finalMessage)
.setTimestamp();
interaction.followUp({
embeds: [roundsListEmbed],
ephemeral: true,
});
break;
}
case "hit": {
await interaction.deferReply();
const totalCount = await generatedRound.countDocuments({});
const userCount = await generatedRound.countDocuments({
requestedBy: interaction.user.id,
});
interaction.followUp(
`Total Hits: ${totalCount}\nYour Hits: ${userCount}`
);
break;
}
}
}

90
src/commands/score.ts

@ -1,43 +1,47 @@
import { SlashCommandBuilder } from '@discordjs/builders'; import { SlashCommandBuilder } from "@discordjs/builders";
import { CommandInteraction, MessageEmbed } from 'discord.js'; import { CommandInteraction, MessageEmbed } from "discord.js";
import log from '../helpers/log'; import log from "../helpers/log";
import userScore from '../models/userScore'; import userScore from "../models/userScore";
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('score') .setName("score")
.setDescription('Returns the score of the current user or another') .setDescription("Returns the score of the current user or another")
.addUserOption(option => { .addUserOption((option) => {
option option
.setName('user') .setName("user")
.setDescription('The user to find the score for') .setDescription("The user to find the score for")
.setRequired(false); .setRequired(false);
return option; return option;
}); });
export async function execute(interaction: CommandInteraction) { export async function execute(interaction: CommandInteraction) {
const scoreEmbed = new MessageEmbed() const scoreEmbed = new MessageEmbed().setColor("#ffffff");
.setColor('#ffffff');
const user = interaction.options.getUser("user") || interaction.user;
const user = interaction.options.getUser('user') || interaction.user; userScore.findOne({ authorID: user.id }, async (err, score) => {
userScore.findOne({ authorID: user.id }, async (err, score) => { if (err) {
if (err) { log({
log({ logger: 'db', content: `Unable to obtain user: ${err}`, level: 'info' }); logger: "db",
} content: `Unable to obtain user: ${err}`,
level: "info",
if (!score) { });
await interaction.reply({ }
content: 'Unfortunately, that user does not seem to have used AwesomeSciBo yet.',
ephemeral: true, if (!score) {
}); await interaction.reply({
return; content:
} "Unfortunately, that user does not seem to have used AwesomeSciBo yet.",
ephemeral: true,
scoreEmbed });
.setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() }) return;
.setDescription(`Score: \`${score.score}\``); }
await interaction.reply({ embeds: [scoreEmbed] }); scoreEmbed
}); .setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() })
} .setDescription(`Score: \`${score.score}\``);
await interaction.reply({ embeds: [scoreEmbed] });
});
}

508
src/commands/settings.ts

@ -1,251 +1,289 @@
import { SlashCommandBuilder } from '@discordjs/builders'; import { SlashCommandBuilder } from "@discordjs/builders";
import { Message, MessageActionRow, MessageSelectMenu } from 'discord.js'; import { Message, MessageActionRow, MessageSelectMenu } from "discord.js";
import { CommandInteraction, MessageEmbed } from 'discord.js'; import { CommandInteraction, MessageEmbed } from "discord.js";
import log from '../helpers/log'; import log from "../helpers/log";
import userConfig from '../models/userConfig'; import userConfig from "../models/userConfig";
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('settings') .setName("settings")
.setDescription('BETA - settings configuration') .setDescription("BETA - settings configuration")
.addSubcommand(subcommand => { .addSubcommand((subcommand) => {
subcommand subcommand.setName("subject").setDescription("Changes subject of problems");
.setName('subject') return subcommand;
.setDescription('Changes subject of problems'); })
return subcommand; .addSubcommand((subcommand) => {
}) subcommand.setName("display").setDescription("Displays current settings");
.addSubcommand(subcommand => { return subcommand;
subcommand })
.setName('display') .addSubcommand((subcommand) => {
.setDescription('Displays current settings'); subcommand
return subcommand; .setName("gradelevels")
}) .setDescription("Changes grade level of problems");
.addSubcommand(subcommand => { return subcommand;
subcommand });
.setName('gradelevels')
.setDescription('Changes grade level of problems');
return subcommand;
});
export async function execute(interaction: CommandInteraction) { export async function execute(interaction: CommandInteraction) {
const action = interaction.options.getSubcommand(); const action = interaction.options.getSubcommand();
switch (action) { switch (action) {
case 'display': { case "display": {
await interaction.deferReply(); await interaction.deferReply();
const settingsEmbed = new MessageEmbed() const settingsEmbed = new MessageEmbed().setColor("#ffffff");
.setColor('#ffffff');
const user = interaction.options.getUser('user') || interaction.user; const user = interaction.options.getUser("user") || interaction.user;
settingsEmbed settingsEmbed
.setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() }) .setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() })
.setDescription('Current selections: '); .setDescription("Current selections: ");
const menu = new MessageActionRow() const menu = new MessageActionRow().addComponents(
.addComponents( new MessageSelectMenu()
new MessageSelectMenu() .setCustomId("selectdisp")
.setCustomId('selectdisp') .setPlaceholder("Nothing selected")
.setPlaceholder('Nothing selected') .addOptions([
.addOptions([ {
{ label: "subjects",
label: 'subjects', description: "subjects",
description: 'subjects', value: "subjects",
value: 'subjects', },
}, {
{ label: "gradelevels",
label: 'gradelevels', description: "grade levels",
description: 'grade levels', value: "gradelevels",
value: 'gradelevels', },
}, ])
]), );
);
interaction.followUp({ interaction
embeds: [/* settingsEmbed*/], .followUp({
components: [menu], embeds: [
}) /* settingsEmbed*/
.then((dispMsg => { ],
const w = dispMsg as Message; components: [menu],
const dispFilter = i => ['selectdisp'].includes(i.customId) && i.user.id == interaction.user.id; // <== ATTENTION! First argument... })
w.awaitMessageComponent({ filter: dispFilter, componentType: 'SELECT_MENU' }) .then((dispMsg) => {
.then(async dispChoice => { const w = dispMsg as Message;
const vals = dispChoice.values; const dispFilter = (i) =>
const config = await userConfig.findById(interaction.user.id); ["selectdisp"].includes(i.customId) &&
if (!config) { i.user.id == interaction.user.id; // <== ATTENTION! First argument...
await interaction.editReply({ w.awaitMessageComponent({
content: 'You don\'t have a configuration!', filter: dispFilter,
embeds: [], componentType: "SELECT_MENU",
components: [], }).then(async (dispChoice) => {
}); const vals = dispChoice.values;
} const config = await userConfig.findById(interaction.user.id);
else if (vals.length === 1 && vals.at(0) === 'subjects') { if (!config) {
await interaction.editReply({ await interaction.editReply({
content: `Current subjects setting: ${config.subjects.toString().split(',').join(', ')}`, content: "You don't have a configuration!",
components: [], embeds: [],
}); components: [],
} });
else if (vals.length === 1 && vals.at(0) === 'gradelevels') { } else if (vals.length === 1 && vals.at(0) === "subjects") {
await interaction.editReply({ await interaction.editReply({
content: `Current grade level setting: ${config.gradeLevels.toString().split(',').join(', ')}`, content: `Current subjects setting: ${config.subjects
components: [], .toString()
}); .split(",")
} .join(", ")}`,
else { components: [],
err => log({ });
logger: '\'Error occurred: /settings:display did not equal subjects or gradelevels.\'', } else if (vals.length === 1 && vals.at(0) === "gradelevels") {
content: `${err}`, await interaction.editReply({
level: 'error', content: `Current grade level setting: ${config.gradeLevels
}); .toString()
} .split(",")
}); .join(", ")}`,
})); components: [],
break; });
} } else {
case 'gradelevels': { (err) =>
await interaction.deferReply(); log({
logger:
"'Error occurred: /settings:display did not equal subjects or gradelevels.'",
content: `${err}`,
level: "error",
});
}
});
});
break;
}
case "gradelevels": {
await interaction.deferReply();
const settingsEmbed = new MessageEmbed() const settingsEmbed = new MessageEmbed().setColor("#ffffff");
.setColor('#ffffff');
const user = interaction.options.getUser('user') || interaction.user; const user = interaction.options.getUser("user") || interaction.user;
settingsEmbed settingsEmbed
.setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() }) .setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() })
.setDescription('Current level settings: '); .setDescription("Current level settings: ");
const menu = new MessageActionRow() const menu = new MessageActionRow().addComponents(
.addComponents( new MessageSelectMenu()
new MessageSelectMenu() .setCustomId("selectlvl")
.setCustomId('selectlvl') .setPlaceholder("Nothing selected")
.setPlaceholder('Nothing selected') .setMinValues(1)
.setMinValues(1) .setMaxValues(2)
.setMaxValues(2) .addOptions([
.addOptions([ {
{ label: "Middle School",
label: 'Middle School', description: "Middle school level problems",
description: 'Middle school level problems', value: "MS",
value: 'MS', },
}, {
{ label: "High School",
label: 'High School', description: "High school level problems",
description: 'High school level problems', value: "HS",
value: 'HS', },
}, ])
]), );
);
interaction.followUp({ interaction
embeds: [/* settingsEmbed*/], .followUp({
components: [menu], embeds: [
}) /* settingsEmbed*/
.then((lvlMsg => { ],
const w = lvlMsg as Message; components: [menu],
const lvlFilter = i => ['selectlvl'].includes(i.customId) && i.user.id == interaction.user.id; // <== ATTENTION! First argument... })
w.awaitMessageComponent({ filter: lvlFilter, componentType: 'SELECT_MENU' }) .then((lvlMsg) => {
.then(async lvlChoice => { const w = lvlMsg as Message;
const vals = lvlChoice.values; const lvlFilter = (i) =>
const levels = new Array<string>(); ["selectlvl"].includes(i.customId) &&
await userConfig.findOneAndUpdate({ _id: interaction.user.id }, { gradeLevels: vals }, { i.user.id == interaction.user.id; // <== ATTENTION! First argument...
upsert: true, w.awaitMessageComponent({
new: true, filter: lvlFilter,
}); componentType: "SELECT_MENU",
await vals.forEach(v => { }).then(async (lvlChoice) => {
switch (v) { const vals = lvlChoice.values;
case 'MS': const levels = new Array<string>();
levels.push('Middle School'); await userConfig.findOneAndUpdate(
break; { _id: interaction.user.id },
case 'HS': { gradeLevels: vals },
levels.push('High School'); {
} upsert: true,
}); new: true,
await interaction.editReply({ }
content: `Level set to: ${levels.toString().split(',').join(', ')}`, );
embeds: [], await vals.forEach((v) => {
components: [], switch (v) {
}); case "MS":
}); levels.push("Middle School");
})); break;
break; case "HS":
} levels.push("High School");
case 'subject': { }
await interaction.deferReply(); });
await interaction.editReply({
content: `Level set to: ${levels
.toString()
.split(",")
.join(", ")}`,
embeds: [],
components: [],
});
});
});
break;
}
case "subject": {
await interaction.deferReply();
const settingsEmbed = new MessageEmbed() const settingsEmbed = new MessageEmbed().setColor("#ffffff");
.setColor('#ffffff');
const user = interaction.options.getUser('user') || interaction.user; const user = interaction.options.getUser("user") || interaction.user;
settingsEmbed settingsEmbed
.setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() }) .setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() })
.setDescription('Current subject settings: '); .setDescription("Current subject settings: ");
const menu = new MessageActionRow() const menu = new MessageActionRow().addComponents(
.addComponents( new MessageSelectMenu()
new MessageSelectMenu() .setCustomId("selectsubject")
.setCustomId('selectsubject') .setPlaceholder("Nothing selected")
.setPlaceholder('Nothing selected') .setMinValues(1)
.setMinValues(1) .setMaxValues(7)
.setMaxValues(7) .addOptions([
.addOptions([ {
{ label: "Astronomy",
label: 'Astronomy', description: "Astronomy",
description: 'Astronomy', value: "ASTRONOMY",
value: 'ASTRONOMY', },
}, {
{ label: "Biology",
label: 'Biology', description: "Biology",
description: 'Biology', value: "BIOLOGY",
value: 'BIOLOGY', },
}, {
{ label: "Earth Science",
label: 'Earth Science', description: "Earth Science",
description: 'Earth Science', value: "EARTH SCIENCE",
value: 'EARTH SCIENCE', },
}, {
{ label: "Chemistry",
label: 'Chemistry', description: "Chemistry",
description: 'Chemistry', value: "CHEMISTRY",
value: 'CHEMISTRY', },
}, {
{ label: "Physics",
label: 'Physics', description: "Physics",
description: 'Physics', value: "PHYSICS",
value: 'PHYSICS', },
}, {
{ label: "Mathematics",
label: 'Mathematics', description: "Mathematics",
description: 'Mathematics', value: "MATH",
value: 'MATH', },
}, {
{ label: "Energy",
label: 'Energy', description: "Energy",
description: 'Energy', value: "ENERGY",
value: 'ENERGY', },
}, ])
]), );
);
interaction.followUp({ interaction
embeds: [/* settingsEmbed*/], .followUp({
components: [menu], embeds: [
}) /* settingsEmbed*/
.then((subjectMsg => { ],
const subjectFilter = i => ['selectsubject'].includes(i.customId) && i.user.id == interaction.user.id; // <== ATTENTION! First argument... components: [menu],
(subjectMsg as Message).awaitMessageComponent({ filter: subjectFilter, componentType: 'SELECT_MENU' }) })
.then(async subjectChoice => { .then((subjectMsg) => {
const vals = subjectChoice.values; const subjectFilter = (i) =>
await userConfig.findOneAndUpdate({ _id: interaction.user.id }, { subjects: vals }, { ["selectsubject"].includes(i.customId) &&
upsert: true, i.user.id == interaction.user.id; // <== ATTENTION! First argument...
new: true, (subjectMsg as Message)
}); .awaitMessageComponent({
const subjects = new Array<string>(); filter: subjectFilter,
await vals.forEach(v => { componentType: "SELECT_MENU",
subjects.push(v.toLowerCase().split(' ').map(w => w[0].toUpperCase() + w.substring(1)).join(' ')); })
}); .then(async (subjectChoice) => {
await interaction.editReply({ const vals = subjectChoice.values;
content: `Subjects set to: ${subjects.toString().split(',').join(', ')}`, await userConfig.findOneAndUpdate(
components: [], { _id: interaction.user.id },
embeds: [], { subjects: vals },
}); {
}); upsert: true,
})); new: true,
break; }
} );
} const subjects = new Array<string>();
await vals.forEach((v) => {
subjects.push(
v
.toLowerCase()
.split(" ")
.map((w) => w[0].toUpperCase() + w.substring(1))
.join(" ")
);
});
await interaction.editReply({
content: `Subjects set to: ${subjects
.toString()
.split(",")
.join(", ")}`,
components: [],
embeds: [],
});
});
});
break;
}
}
} }

138
src/commands/top.ts

@ -1,63 +1,75 @@
import { SlashCommandBuilder } from '@discordjs/builders'; import { SlashCommandBuilder } from "@discordjs/builders";
import { CommandInteraction, MessageEmbed } from 'discord.js'; import { CommandInteraction, MessageEmbed } from "discord.js";
import log from '../helpers/log'; import log from "../helpers/log";
import userScore from '../models/userScore'; import userScore from "../models/userScore";
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('top') .setName("top")
.setDescription('Lists top ten scores across servers and in the current server'); .setDescription(
"Lists top ten scores across servers and in the current server"
export async function execute(interaction: CommandInteraction) { );
await interaction.deferReply();
export async function execute(interaction: CommandInteraction) {
userScore await interaction.deferReply();
.find({})
.sort({ score: -1 }) // Sort by descending order userScore
.exec(async (err, obj) => { .find({})
if (err) { .sort({ score: -1 }) // Sort by descending order
log({ logger: 'top', content: `Getting top players failed: ${err}`, level: 'error' }); .exec(async (err, obj) => {
console.log(err); if (err) {
} log({
logger: "top",
if (obj.length < 10) { content: `Getting top players failed: ${err}`,
// Need at least 10 scores for top 10 level: "error",
return interaction.followUp( });
`There are only ${obj.length} users, we need at least 10!`, console.log(err);
); }
}
if (obj.length < 10) {
const embeds: MessageEmbed[] = []; // Need at least 10 scores for top 10
let lbMessageContent = ''; return interaction.followUp(
`There are only ${obj.length} users, we need at least 10!`
for (let i = 0; i < 10; i++) { );
lbMessageContent += `${i + 1}: <@${obj[i].authorID}>: ${obj[i].score}\n`; // Loop through each user and add their name and score to leaderboard content }
}
const embeds: MessageEmbed[] = [];
const leaderboardEmbed = new MessageEmbed() let lbMessageContent = "";
.setTitle('Top Ten!')
.setDescription(lbMessageContent) for (let i = 0; i < 10; i++) {
.setColor('#ffffff'); lbMessageContent += `${i + 1}: <@${obj[i].authorID}>: ${
obj[i].score
embeds.push(leaderboardEmbed); }\n`; // Loop through each user and add their name and score to leaderboard content
}
let sMessageContent = '';
const members = await interaction.guild?.members.fetch(); const leaderboardEmbed = new MessageEmbed()
.setTitle("Top Ten!")
const serverLeaderBoardArray = await obj.filter(o => members?.some(m => m.user.id === o.authorID)); .setDescription(lbMessageContent)
if (serverLeaderBoardArray.length > 10) { .setColor("#ffffff");
for (let i = 0; i < 10; i++) {
sMessageContent += `${i + 1}: <@${serverLeaderBoardArray[i].authorID}>: ${serverLeaderBoardArray[i].score}\n`; embeds.push(leaderboardEmbed);
}
let sMessageContent = "";
const sLeaderboardEmbed = new MessageEmbed() const members = await interaction.guild?.members.fetch();
.setTitle(`Top Ten in ${interaction.guild?.name}!`)
.setDescription(sMessageContent) const serverLeaderBoardArray = await obj.filter((o) =>
.setColor('#ffffff'); members?.some((m) => m.user.id === o.authorID)
);
embeds.push(sLeaderboardEmbed); if (serverLeaderBoardArray.length > 10) {
} for (let i = 0; i < 10; i++) {
sMessageContent += `${i + 1}: <@${
interaction.followUp({ embeds: embeds }); serverLeaderBoardArray[i].authorID
}); }>: ${serverLeaderBoardArray[i].score}\n`;
} }
const sLeaderboardEmbed = new MessageEmbed()
.setTitle(`Top Ten in ${interaction.guild?.name}!`)
.setDescription(sMessageContent)
.setColor("#ffffff");
embeds.push(sLeaderboardEmbed);
}
interaction.followUp({ embeds: embeds });
});
}

581
src/commands/train.ts

@ -1,259 +1,322 @@
import { SlashCommandBuilder } from '@discordjs/builders'; import { SlashCommandBuilder } from "@discordjs/builders";
import { MessageEmbed, MessageActionRow, MessageButton, CommandInteraction, Message } from 'discord.js'; import {
MessageEmbed,
import { decode } from 'html-entities'; MessageActionRow,
import axios from 'axios'; MessageButton,
CommandInteraction,
import userScore from '../models/userScore'; Message,
import userConfig from '../models/userConfig'; } from "discord.js";
import log from '../helpers/log.js'; import { decode } from "html-entities";
import { updateScore } from '../helpers/db.js'; import axios from "axios";
export const data = new SlashCommandBuilder() import userScore from "../models/userScore";
.setName('train') import userConfig from "../models/userConfig";
.setDescription('Sends a training question to be answered')
.addStringOption(option => { import log from "../helpers/log.js";
option import { updateScore } from "../helpers/db.js";
.setName('subject')
.setDescription('Optional subject to be used as a filter') export const data = new SlashCommandBuilder()
.setRequired(false) .setName("train")
.addChoices( .setDescription("Sends a training question to be answered")
{ name: 'astro', value: 'astro' }, .addStringOption((option) => {
{ name: 'bio', value: 'bio' }, option
{ name: 'chem', value: 'chem' }, .setName("subject")
{ name: 'ess', value: 'ess' }, .setDescription("Optional subject to be used as a filter")
{ name: 'phys', value: 'phys' }, .setRequired(false)
{ name: 'math', value: 'math' }, .addChoices(
{ name: 'energy', value: 'energy' }, { name: "astro", value: "astro" },
) { name: "bio", value: "bio" },
.setRequired(false); { name: "chem", value: "chem" },
return option; { name: "ess", value: "ess" },
}); { name: "phys", value: "phys" },
{ name: "math", value: "math" },
export async function execute(interaction: CommandInteraction) { { name: "energy", value: "energy" }
await interaction.deferReply(); )
.setRequired(false);
const subject = interaction.options.get('subject') ? interaction.options.get('subject')?.value : null; return option;
const authorId = interaction.user.id; });
let score: number;
userScore export async function execute(interaction: CommandInteraction) {
.findOne({ authorID: authorId }) await interaction.deferReply();
.lean()
.then((obj: { score: number; }, err: unknown) => { const subject = interaction.options.get("subject")
if (!obj) { ? interaction.options.get("subject")?.value
score = 0; : null;
const firstTimeEmbed = new MessageEmbed() const authorId = interaction.user.id;
.setAuthor({ let score: number;
name: interaction.client.user?.tag ? interaction.client.user?.tag : '', userScore
iconURL: interaction.client.user?.displayAvatarURL(), .findOne({ authorID: authorId })
}) .lean()
.setDescription('Hey! It seems like it\'s your first time using AwesomeSciBo. Here\'s some information regarding the bot if you need it (for issues, contributions, etc.):') .then((obj: { score: number }, err: unknown) => {
.addField('Creator', '<@745063586422063214> [@abheekd#3602]') if (!obj) {
.addField('GitHub', '[Link](https://github.com/ADawesomeguy/AwesomeSciBo) (a star couldn\'t hurt...)') score = 0;
.setColor('#ffffff') const firstTimeEmbed = new MessageEmbed()
.setTimestamp(); .setAuthor({
interaction.user.send({ embeds: [firstTimeEmbed] }) name: interaction.client.user?.tag
.catch(err => log({ logger: 'train', content: `${err}`, level: 'error' })); ? interaction.client.user?.tag
} : "",
else if (obj) { iconURL: interaction.client.user?.displayAvatarURL(),
score = obj.score; })
} .setDescription(
else { "Hey! It seems like it's your first time using AwesomeSciBo. Here's some information regarding the bot if you need it (for issues, contributions, etc.):"
log({ logger: 'train', content: `Getting user score failed: ${err}`, level: 'error' }); )
} .addField("Creator", "<@745063586422063214> [@abheekd#3602]")
}); .addField(
"GitHub",
let categoryArray: string[] = []; "[Link](https://github.com/ADawesomeguy/AwesomeSciBo) (a star couldn't hurt...)"
const allCategories = ['BIOLOGY', 'PHYSICS', 'CHEMISTRY', 'EARTH AND SPACE', 'ASTRONOMY', 'MATH']; )
const configCategories = await userConfig.findById(interaction.user.id); .setColor("#ffffff")
.setTimestamp();
switch (subject) { interaction.user
case null: .send({ embeds: [firstTimeEmbed] })
categoryArray = (configCategories ? (configCategories.subjects || allCategories) : allCategories); .catch((err) =>
break; log({ logger: "train", content: `${err}`, level: "error" })
case 'astro': );
case 'astronomy': } else if (obj) {
categoryArray = ['ASTRONOMY']; score = obj.score;
break; } else {
case 'bio': log({
case 'biology': logger: "train",
categoryArray = ['BIOLOGY']; content: `Getting user score failed: ${err}`,
break; level: "error",
case 'ess': });
case 'earth science': }
case 'es': });
categoryArray = ['EARTH SCIENCE'];
break; let categoryArray: string[] = [];
case 'chem': const allCategories = [
case 'chemistry': "BIOLOGY",
categoryArray = ['CHEMISTRY']; "PHYSICS",
break; "CHEMISTRY",
case 'phys': "EARTH AND SPACE",
case 'physics': "ASTRONOMY",
categoryArray = ['PHYSICS']; "MATH",
break; ];
case 'math': const configCategories = await userConfig.findById(interaction.user.id);
categoryArray = ['MATH'];
break; switch (subject) {
case 'energy': case null:
categoryArray = ['ENERGY']; categoryArray = configCategories
break; ? configCategories.subjects || allCategories
default: : allCategories;
interaction.followUp({ break;
embeds: [new MessageEmbed() case "astro":
.setDescription('<:red_x:816791117671825409> Not a valid subject!') case "astronomy":
.setColor('#ffffff')], categoryArray = ["ASTRONOMY"];
}); break;
return; case "bio":
} case "biology":
categoryArray = ["BIOLOGY"];
axios break;
.post('https://scibowldb.com/api/questions/random', { categories: categoryArray }) case "ess":
.then((res) => { case "earth science":
const questionData = res.data.question; case "es":
const tossupQuestion = questionData.tossup_question; categoryArray = ["EARTH SCIENCE"];
const tossupAnswer = questionData.tossup_answer; break;
const tossupFormat = questionData.tossup_format; case "chem":
let answers = tossupAnswer.split(' (ACCEPT: '); case "chemistry":
if (answers.length > 1) { categoryArray = ["CHEMISTRY"];
answers[1] = answers[1].slice(0, answers[1].length - 1); // If there are multiple elements, it means there was an 'accept' and therefore a trailing ')' which should be removed break;
answers = [answers[0], ...answers[1].split(new RegExp(' OR ', 'i'))]; // Use the first element plus the last element split by 'OR' case insensitive case "phys":
} case "physics":
interaction.followUp({ content: decode(tossupQuestion), fetchReply: true }) categoryArray = ["PHYSICS"];
.then(q => { break;
const questionMessage = q as Message; case "math":
const sourceButton = new MessageActionRow() categoryArray = ["MATH"];
.addComponents( break;
new MessageButton() case "energy":
.setURL(questionData.uri) categoryArray = ["ENERGY"];
.setLabel('Source') break;
.setStyle('LINK'), default:
); interaction.followUp({
switch (tossupFormat) { embeds: [
case 'Short Answer': { new MessageEmbed()
// eslint-disable-next-line no-case-declarations .setDescription("<:red_x:816791117671825409> Not a valid subject!")
const messageFilter = m => m.author.id === interaction.user.id || m.author.id === interaction.client.user?.id; .setColor("#ffffff"),
interaction.channel?.awaitMessages({ ],
filter: messageFilter, });
max: 1, return;
}) }
.then(collected => {
const answerMsg = collected.first(); axios
.post("https://scibowldb.com/api/questions/random", {
if (answerMsg?.author.id === interaction.client.user?.id) return; categories: categoryArray,
})
let predicted = ''; .then((res) => {
if (answerMsg?.content.toLowerCase() === tossupAnswer.toLowerCase() || answers.includes(answerMsg?.content.toUpperCase())) { const questionData = res.data.question;
predicted = 'correct'; const tossupQuestion = questionData.tossup_question;
} const tossupAnswer = questionData.tossup_answer;
else { const tossupFormat = questionData.tossup_format;
predicted = 'incorrect'; let answers = tossupAnswer.split(" (ACCEPT: ");
} if (answers.length > 1) {
answers[1] = answers[1].slice(0, answers[1].length - 1); // If there are multiple elements, it means there was an 'accept' and therefore a trailing ')' which should be removed
if (predicted === 'correct') { answers = [answers[0], ...answers[1].split(new RegExp(" OR ", "i"))]; // Use the first element plus the last element split by 'OR' case insensitive
updateScore(true, score, authorId).then((msgToReply) => }
answerMsg?.reply(msgToReply), interaction
); .followUp({ content: decode(tossupQuestion), fetchReply: true })
} .then((q) => {
else { const questionMessage = q as Message;
const overrideEmbed = new MessageEmbed() const sourceButton = new MessageActionRow().addComponents(
.setAuthor({ new MessageButton()
name: answerMsg?.author.tag ? answerMsg.author.tag : '', .setURL(questionData.uri)
iconURL: answerMsg?.author.displayAvatarURL(), .setLabel("Source")
}) .setStyle("LINK")
.addField('Correct answer', `\`${tossupAnswer}\``) );
.setDescription('It seems your answer was incorrect. Please react with <:override:955265585086857236> to override your answer if you think you got it right.') switch (tossupFormat) {
.setColor('#ffffff') case "Short Answer": {
.setTimestamp(); // eslint-disable-next-line no-case-declarations
const overrideButton = new MessageActionRow() const messageFilter = (m) =>
.addComponents( m.author.id === interaction.user.id ||
new MessageButton() m.author.id === interaction.client.user?.id;
.setCustomId('override') interaction.channel
.setEmoji('<:override:955265585086857236>') ?.awaitMessages({
.setStyle('SECONDARY'), filter: messageFilter,
); max: 1,
answerMsg?.channel.send({ })
embeds: [overrideEmbed], .then((collected) => {
components: [overrideButton], const answerMsg = collected.first();
})
.then(overrideMsg => { if (answerMsg?.author.id === interaction.client.user?.id)
const overrideFilter = i => { return;
return (
['override'].includes(i.customId) && let predicted = "";
i.user.id === answerMsg.author.id if (
); answerMsg?.content.toLowerCase() ===
}; tossupAnswer.toLowerCase() ||
overrideMsg answers.includes(answerMsg?.content.toUpperCase())
.awaitMessageComponent({ ) {
filter: overrideFilter, predicted = "correct";
}) } else {
.then(i => { predicted = "incorrect";
updateScore(true, score, authorId).then(async msgToReply => { }
await i.reply(msgToReply);
overrideMsg.edit({ components: [] }); if (predicted === "correct") {
}); updateScore(true, score, authorId).then((msgToReply) =>
}).catch(err => log({ answerMsg?.reply(msgToReply)
logger: 'train', );
content: `Failed to override score: ${err}`, } else {
level: 'error', const overrideEmbed = new MessageEmbed()
})); .setAuthor({
}).catch(err => log({ name: answerMsg?.author.tag ? answerMsg.author.tag : "",
logger: 'train', iconURL: answerMsg?.author.displayAvatarURL(),
content: `Failed to send override message: ${err}`, })
level: 'error', .addField("Correct answer", `\`${tossupAnswer}\``)
})); .setDescription(
} "It seems your answer was incorrect. Please react with <:override:955265585086857236> to override your answer if you think you got it right."
interaction.editReply({ components: [sourceButton] }); )
}).catch(err => log({ logger: 'train', content: `${err}`, level: 'error' })); .setColor("#ffffff")
break; .setTimestamp();
} const overrideButton = new MessageActionRow().addComponents(
case 'Multiple Choice': { new MessageButton()
const choices = new MessageActionRow() .setCustomId("override")
.addComponents( .setEmoji("<:override:955265585086857236>")
new MessageButton() .setStyle("SECONDARY")
.setCustomId('w') );
.setLabel('W') answerMsg?.channel
.setStyle('SECONDARY'), .send({
new MessageButton() embeds: [overrideEmbed],
.setCustomId('x') components: [overrideButton],
.setLabel('X') })
.setStyle('SECONDARY'), .then((overrideMsg) => {
new MessageButton() const overrideFilter = (i) => {
.setCustomId('y') return (
.setLabel('Y') ["override"].includes(i.customId) &&
.setStyle('SECONDARY'), i.user.id === answerMsg.author.id
new MessageButton() );
.setCustomId('z') };
.setLabel('Z') overrideMsg
.setStyle('SECONDARY'), .awaitMessageComponent({
); filter: overrideFilter,
interaction.editReply({ components: [choices] }); })
const mcFilter = i => ['w', 'x', 'y', 'z'].includes(i.customId) && i.user.id === interaction.user.id; .then((i) => {
questionMessage.awaitMessageComponent({ filter: mcFilter }) updateScore(true, score, authorId).then(
.then(mcChoice => { async (msgToReply) => {
if (tossupAnswer.charAt(0).toLowerCase() === mcChoice.customId) { await i.reply(msgToReply);
updateScore(true, score, authorId).then((msgToReply) => overrideMsg.edit({ components: [] });
mcChoice.reply(msgToReply), }
); );
} })
else { .catch((err) =>
const incorrectEmbed = new MessageEmbed() log({
.setAuthor({ logger: "train",
name: interaction.user.tag, content: `Failed to override score: ${err}`,
iconURL: interaction.user.displayAvatarURL(), level: "error",
}) })
.addField('Correct answer', `\`${tossupAnswer}\``) );
.setDescription(`It seems your answer ${mcChoice.customId.toUpperCase()} was incorrect.`) })
.setColor('#ffffff') .catch((err) =>
.setTimestamp(); log({
mcChoice.reply({ embeds: [incorrectEmbed] }); logger: "train",
} content: `Failed to send override message: ${err}`,
interaction.editReply({ components: [sourceButton] }); level: "error",
}); })
break; );
} }
} interaction.editReply({ components: [sourceButton] });
}).catch(err => log({ logger: 'train', content: `${err}`, level: 'error' })); })
}).catch(err => log({ logger: 'train', content: `${err}`, level: 'error' })); .catch((err) =>
} log({ logger: "train", content: `${err}`, level: "error" })
);
break;
}
case "Multiple Choice": {
const choices = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId("w")
.setLabel("W")
.setStyle("SECONDARY"),
new MessageButton()
.setCustomId("x")
.setLabel("X")
.setStyle("SECONDARY"),
new MessageButton()
.setCustomId("y")
.setLabel("Y")
.setStyle("SECONDARY"),
new MessageButton()
.setCustomId("z")
.setLabel("Z")
.setStyle("SECONDARY")
);
interaction.editReply({ components: [choices] });
const mcFilter = (i) =>
["w", "x", "y", "z"].includes(i.customId) &&
i.user.id === interaction.user.id;
questionMessage
.awaitMessageComponent({ filter: mcFilter })
.then((mcChoice) => {
if (
tossupAnswer.charAt(0).toLowerCase() === mcChoice.customId
) {
updateScore(true, score, authorId).then((msgToReply) =>
mcChoice.reply(msgToReply)
);
} else {
const incorrectEmbed = new MessageEmbed()
.setAuthor({
name: interaction.user.tag,
iconURL: interaction.user.displayAvatarURL(),
})
.addField("Correct answer", `\`${tossupAnswer}\``)
.setDescription(
`It seems your answer ${mcChoice.customId.toUpperCase()} was incorrect.`
)
.setColor("#ffffff")
.setTimestamp();
mcChoice.reply({ embeds: [incorrectEmbed] });
}
interaction.editReply({ components: [sourceButton] });
});
break;
}
}
})
.catch((err) =>
log({ logger: "train", content: `${err}`, level: "error" })
);
})
.catch((err) =>
log({ logger: "train", content: `${err}`, level: "error" })
);
}

23
src/deploy-commands.js

@ -1,20 +1,23 @@
#!/usr/bin/env node #!/usr/bin/env node
const fs = require('node:fs'); const fs = require('node:fs');
const {REST} = require('@discordjs/rest'); const { REST } = require('@discordjs/rest');
const {Routes} = require('discord-api-types/v9'); const { Routes } = require('discord-api-types/v9');
const {clientId, token} = require('./helpers/env'); const { clientId, token } = require('./helpers/env');
const commands = []; const commands = [];
const commandFiles = fs.readdirSync(__dirname + '/commands').filter(file => file.endsWith('.js')); const commandFiles = fs
.readdirSync(__dirname + '/commands')
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) { for (const file of commandFiles) {
const command = require(`${__dirname}/commands/${file}`); const command = require(`${__dirname}/commands/${file}`);
commands.push(command.data.toJSON()); commands.push(command.data.toJSON());
} }
const rest = new REST({version: '9'}).setToken(token); const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationCommands(clientId), {body: commands}) rest
.then(() => console.log('Successfully registered application commands.')) .put(Routes.applicationCommands(clientId), { body: commands })
.catch(console.error); .then(() => console.log('Successfully registered application commands.'))
.catch(console.error);

32
src/events/interactionCreate.ts

@ -1,23 +1,29 @@
import log from '../helpers/log'; import log from "../helpers/log";
export const name = 'interactionCreate'; export const name = "interactionCreate";
export const once = false; export const once = false;
export async function execute(interaction) { export async function execute(interaction) {
const client = interaction.client; const client = interaction.client;
if (!interaction.isCommand()) return; if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName); const command = client.commands.get(interaction.commandName);
if (!command) return; if (!command) return;
try { try {
await command.execute(interaction); await command.execute(interaction);
} } catch (error) {
catch (error) { log({
log({ logger: 'interaction', content: `Interaction ${interaction.commandName} failed!`, level: 'error' }); logger: "interaction",
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true }); content: `Interaction ${interaction.commandName} failed!`,
} level: "error",
});
await interaction.followUp({
content: "There was an error while executing this command!",
ephemeral: true,
});
}
} }

58
src/events/messageCreate.ts

@ -1,36 +1,36 @@
import axios from 'axios'; import axios from "axios";
import { MessageEmbed } from 'discord.js'; import { MessageEmbed } from "discord.js";
import { decode } from 'html-entities'; import { decode } from "html-entities";
import { testingGuild } from '../helpers/env'; import { testingGuild } from "../helpers/env";
export const name = 'messageCreate'; export const name = "messageCreate";
export const once = false; export const once = false;
export async function execute(message) { export async function execute(message) {
if (message.author.bot || message.guild.id != testingGuild) return; if (message.author.bot || message.guild.id != testingGuild) return;
if (message.content.startsWith('!q')) { if (message.content.startsWith("!q")) {
const questionId = message.content.split(' ')[1]; const questionId = message.content.split(" ")[1];
axios axios
.get(`https://scibowldb.com/api/questions/${questionId}`) .get(`https://scibowldb.com/api/questions/${questionId}`)
.then((res) => { .then((res) => {
const data = res.data.question; const data = res.data.question;
const tossupQuestion = data.tossup_question; const tossupQuestion = data.tossup_question;
const tossupAnswer = data.tossup_answer; const tossupAnswer = data.tossup_answer;
let answers = tossupAnswer.split(' (ACCEPT: '); let answers = tossupAnswer.split(" (ACCEPT: ");
if (answers.length > 1) { if (answers.length > 1) {
answers[1] = answers[1].slice(0, answers[1].length - 1); // If there are multiple elements, it means there was an 'accept' and therefore a trailing ')' which should be removed answers[1] = answers[1].slice(0, answers[1].length - 1); // If there are multiple elements, it means there was an 'accept' and therefore a trailing ')' which should be removed
answers = [answers[0], ...answers[1].split(new RegExp(' OR ', 'i'))]; // Use the first element plus the last element split by 'OR' case insensitive answers = [answers[0], ...answers[1].split(new RegExp(" OR ", "i"))]; // Use the first element plus the last element split by 'OR' case insensitive
} }
const dataEmbed = new MessageEmbed() const dataEmbed = new MessageEmbed()
.setTitle('Data') .setTitle("Data")
.setDescription(`\`\`\`json\n${JSON.stringify(data, null, 2)}\`\`\``); .setDescription(`\`\`\`json\n${JSON.stringify(data, null, 2)}\`\`\``);
message.reply({ message.reply({
content: decode(tossupQuestion) + `\n\nAnswers: [${answers}]`, content: decode(tossupQuestion) + `\n\nAnswers: [${answers}]`,
embeds: [dataEmbed], embeds: [dataEmbed],
}); });
}); });
} }
} }

21
src/events/ready.ts

@ -1,16 +1,17 @@
import * as db from '../helpers/db'; import * as db from "../helpers/db";
import { mongoUri } from '../helpers/env'; import { mongoUri } from "../helpers/env";
import log from '../helpers/log'; import log from "../helpers/log";
export const name = 'ready'; export const name = "ready";
export const once = true; export const once = true;
export async function execute(client) { export async function execute(client) {
await db.connect(mongoUri); await db.connect(mongoUri);
log({ logger: 'status', content: `Logged in as ${client.user.tag}!`, level: 'info' }); log({
client.user.setActivity( logger: "status",
'for /help', content: `Logged in as ${client.user.tag}!`,
{ type: 'WATCHING' }, level: "info",
); });
client.user.setActivity("for /help", { type: "WATCHING" });
} }

118
src/helpers/db.ts

@ -1,51 +1,67 @@
import mongoose from 'mongoose'; import mongoose from "mongoose";
import log from '../helpers/log'; import log from "../helpers/log";
import userScore from '../models/userScore'; import userScore from "../models/userScore";
export async function updateScore(isCorrect: boolean, score: number, authorId: string) { export async function updateScore(
if (!isCorrect) { isCorrect: boolean,
return `Nice try! Your score is still ${score}.`; score: number,
} authorId: string
else { ) {
// TODO: Error handling if (!isCorrect) {
const doc = await userScore.findOne({ return `Nice try! Your score is still ${score}.`;
authorID: authorId, } else {
}); // TODO: Error handling
if (!doc) { const doc = await userScore.findOne({
const newUserScore = new userScore({ authorID: authorId,
authorID: authorId, });
score: score + 4, if (!doc) {
}); const newUserScore = new userScore({
newUserScore.save(err => { authorID: authorId,
if (err) { score: score + 4,
log({ logger: 'db', content: `Error creating new user ${authorId} for scoring`, level: 'error' }); });
} newUserScore.save((err) => {
else { if (err) {
log({ logger: 'db', content: `Successfully created user ${authorId} for scoring`, level: 'debug' }); log({
} logger: "db",
}); content: `Error creating new user ${authorId} for scoring`,
} level: "error",
else { });
doc.score = doc.score + 4; } else {
doc.save(); log({
} logger: "db",
content: `Successfully created user ${authorId} for scoring`,
return `Great job! Your score is now ${score + 4}.`; level: "debug",
} });
} }
});
export async function connect(mongoUri) { } else {
mongoose doc.score = doc.score + 4;
.connect(mongoUri, { doc.save();
useUnifiedTopology: true, }
useNewUrlParser: true,
}) return `Great job! Your score is now ${score + 4}.`;
.then(() => log({ logger: 'db', content: `Connected to the database at ${mongoUri}!`, level: 'info' })) }
.catch(err => log({ }
logger: 'db',
content: `Failed to connect to the database at ${mongoUri}: ${err}`, export async function connect(mongoUri) {
level: 'fatal', mongoose
})); .connect(mongoUri, {
} useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() =>
log({
logger: "db",
content: `Connected to the database at ${mongoUri}!`,
level: "info",
})
)
.catch((err) =>
log({
logger: "db",
content: `Failed to connect to the database at ${mongoUri}: ${err}`,
level: "fatal",
})
);
}

11
src/helpers/env.ts

@ -1,6 +1,7 @@
import 'dotenv/config'; import "dotenv/config";
export const clientId = process.env.CLIENT_ID || ''; export const clientId = process.env.CLIENT_ID || "";
export const testingGuild = process.env.TESTING_GUILD || ''; export const testingGuild = process.env.TESTING_GUILD || "";
export const token = process.env.TOKEN || ''; export const token = process.env.TOKEN || "";
export const mongoUri = process.env.MONGO_URI = 'mongodb://mongo:27017/AWESOME'; export const mongoUri = (process.env.MONGO_URI =
"mongodb://mongo:27017/AWESOME");

56
src/helpers/log.ts

@ -1,29 +1,29 @@
import log4js from 'log4js'; import log4js from "log4js";
export default function(config) { export default function (config) {
const logger = log4js.getLogger(config.logger); const logger = log4js.getLogger(config.logger);
logger.level = 'debug'; logger.level = "debug";
switch (config.level) { switch (config.level) {
case 'trace': case "trace":
logger.trace(config.content); logger.trace(config.content);
break; break;
case 'debug': case "debug":
logger.debug(config.content); logger.debug(config.content);
break; break;
case 'info': case "info":
logger.info(config.content); logger.info(config.content);
break; break;
case 'warn': case "warn":
logger.warn(config.content); logger.warn(config.content);
break; break;
case 'error': case "error":
logger.error(config.content); logger.error(config.content);
break; break;
case 'fatal': case "fatal":
logger.fatal(config.content); logger.fatal(config.content);
break; break;
default: default:
logger.debug(config.content); logger.debug(config.content);
break; break;
} }
} }

178
src/helpers/util/pagination.ts

@ -1,87 +1,113 @@
import { CommandInteraction, Message, MessageActionRow, MessageButton, MessageEmbed } from 'discord.js'; import {
CommandInteraction,
Message,
MessageActionRow,
MessageButton,
MessageEmbed,
} from "discord.js";
export async function paginateMessage(message: Message, embeds: MessageEmbed[]) { export async function paginateMessage(
let index = 0; message: Message,
embeds: MessageEmbed[]
) {
let index = 0;
const row = new MessageActionRow; const row = new MessageActionRow();
row.addComponents( row.addComponents(
new MessageButton() new MessageButton()
.setCustomId('paginator-left') .setCustomId("paginator-left")
.setEmoji('868552005977788466') .setEmoji("868552005977788466")
.setStyle('SECONDARY'), .setStyle("SECONDARY"),
new MessageButton() new MessageButton()
.setCustomId('paginator-right') .setCustomId("paginator-right")
.setEmoji('868551772887711754') .setEmoji("868551772887711754")
.setStyle('SECONDARY') .setStyle("SECONDARY")
); );
await message.reply({ content: `Page 1 of ${embeds.length}:`, embeds: [embeds[index]], components: [row] }) await message
.then(async paginatorMessage => { .reply({
const filter = m => m.author.id === message.author.id; content: `Page 1 of ${embeds.length}:`,
embeds: [embeds[index]],
components: [row],
})
.then(async (paginatorMessage) => {
const filter = (m) => m.author.id === message.author.id;
const paginatorCollector = paginatorMessage.createMessageComponentCollector({ const paginatorCollector =
componentType: 'BUTTON', paginatorMessage.createMessageComponentCollector({
filter: filter, componentType: "BUTTON",
}); filter: filter,
});
paginatorCollector.on('collect', async i => { paginatorCollector.on("collect", async (i) => {
switch (i.customId) { switch (i.customId) {
case 'paginator-left': case "paginator-left":
index--; index--;
if (index < 0) index = embeds.length - 1; if (index < 0) index = embeds.length - 1;
break; break;
case 'paginator-right': case "paginator-right":
index++; index++;
if (index > embeds.length - 1) index = 0; if (index > embeds.length - 1) index = 0;
break; break;
} }
paginatorMessage.edit({ content: `Page ${index + 1} of ${embeds.length}:`, embeds: [embeds[index]] }); paginatorMessage.edit({
}); content: `Page ${index + 1} of ${embeds.length}:`,
}); embeds: [embeds[index]],
});
});
});
} }
export async function paginateInteraction(interaction: CommandInteraction, embeds: MessageEmbed[]) { export async function paginateInteraction(
let index = 0; interaction: CommandInteraction,
embeds: MessageEmbed[]
) {
let index = 0;
const row = new MessageActionRow; const row = new MessageActionRow();
row.addComponents( row.addComponents(
new MessageButton() new MessageButton()
.setCustomId('paginator-left') .setCustomId("paginator-left")
.setEmoji('868552005977788466') .setEmoji("868552005977788466")
.setStyle('SECONDARY'), .setStyle("SECONDARY"),
new MessageButton() new MessageButton()
.setCustomId('paginator-right') .setCustomId("paginator-right")
.setEmoji('868551772887711754') .setEmoji("868551772887711754")
.setStyle('SECONDARY') .setStyle("SECONDARY")
); );
await interaction.followUp({ await interaction
content: `Page 1 of ${embeds.length}:`, .followUp({
embeds: [embeds[index]], content: `Page 1 of ${embeds.length}:`,
components: [row], embeds: [embeds[index]],
fetchReply: true, components: [row],
}) fetchReply: true,
.then(async p => { })
const paginatorMessage = p as Message; .then(async (p) => {
const filter = i => i.user.id === interaction.user.id; const paginatorMessage = p as Message;
const filter = (i) => i.user.id === interaction.user.id;
const paginatorCollector = paginatorMessage.createMessageComponentCollector({ const paginatorCollector =
componentType: 'BUTTON', paginatorMessage.createMessageComponentCollector({
filter: filter, componentType: "BUTTON",
}); filter: filter,
});
paginatorCollector.on('collect', async i => { paginatorCollector.on("collect", async (i) => {
switch (i.customId) { switch (i.customId) {
case 'paginator-left': case "paginator-left":
index--; index--;
if (index < 0) index = embeds.length - 1; if (index < 0) index = embeds.length - 1;
break; break;
case 'paginator-right': case "paginator-right":
index++; index++;
if (index > embeds.length - 1) index = 0; if (index > embeds.length - 1) index = 0;
break; break;
} }
await i.update({ content: `Page ${index + 1} of ${embeds.length}:`, embeds: [embeds[index]] }); await i.update({
}); content: `Page ${index + 1} of ${embeds.length}:`,
}); embeds: [embeds[index]],
} });
});
});
}

62
src/index.ts

@ -1,38 +1,54 @@
#!/usr/bin/env node #!/usr/bin/env node
import fs from 'node:fs'; import fs from "node:fs";
import { Client, Collection, Intents } from 'discord.js'; import { Client, Collection, Intents } from "discord.js";
import { token } from './helpers/env'; import { token } from "./helpers/env";
import log from './helpers/log'; import log from "./helpers/log";
const client = new Client({ const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.DIRECT_MESSAGE_REACTIONS], intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.DIRECT_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
],
}); });
client['commands'] = new Collection(); client["commands"] = new Collection();
const commandFiles = fs.readdirSync(`${__dirname}/commands`).filter(file => file.endsWith('.js')); const commandFiles = fs
const eventFiles = fs.readdirSync(`${__dirname}/events`).filter(file => file.endsWith('.js')); .readdirSync(`${__dirname}/commands`)
.filter((file) => file.endsWith(".js"));
const eventFiles = fs
.readdirSync(`${__dirname}/events`)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) { for (const file of commandFiles) {
import(`${__dirname}/commands/${file}`) import(`${__dirname}/commands/${file}`).then((command) => {
.then(command => { client["commands"].set(command.data.name, command);
client['commands'].set(command.data.name, command); log({
log({ logger: 'command', content: `Registered command ${file}!`, level: 'info' }); logger: "command",
}); content: `Registered command ${file}!`,
level: "info",
});
});
} }
for (const file of eventFiles) { for (const file of eventFiles) {
import(`${__dirname}/events/${file}`) import(`${__dirname}/events/${file}`).then((event) => {
.then(event => { if (event.once) {
if (event.once) { client.once(event.name, (...args) => event.execute(...args));
client.once(event.name, (...args) => event.execute(...args)); } else {
} client.on(event.name, (...args) => event.execute(...args));
else { }
client.on(event.name, (...args) => event.execute(...args)); log({
} logger: "event",
log({ logger: 'event', content: `Registered event ${file}!`, level: 'info' }); content: `Registered event ${file}!`,
}); level: "info",
});
});
} }
client.login(token); client.login(token);

36
src/models/generatedRound.ts

@ -1,22 +1,22 @@
import mongoose from 'mongoose'; import mongoose from "mongoose";
const generatedRoundSchema = new mongoose.Schema({ const generatedRoundSchema = new mongoose.Schema({
htmlContent: { htmlContent: {
type: String, type: String,
required: true, required: true,
}, },
requestedBy: { requestedBy: {
type: String, type: String,
required: true, required: true,
}, },
authorTag: { authorTag: {
type: String, type: String,
required: true, required: true,
}, },
timestamp: { timestamp: {
type: String, type: String,
required: true, required: true,
}, },
}); });
export default mongoose.model('GeneratedRound', generatedRoundSchema); export default mongoose.model("GeneratedRound", generatedRoundSchema);

26
src/models/userConfig.ts

@ -1,17 +1,17 @@
import mongoose from 'mongoose'; import mongoose from "mongoose";
const userConfigSchema = new mongoose.Schema({ const userConfigSchema = new mongoose.Schema({
_id: String, _id: String,
subjects: { subjects: {
type: [String], type: [String],
required: true, required: true,
default: null, default: null,
}, },
gradeLevels: { gradeLevels: {
type: [String], type: [String],
required: true, required: true,
default: null, default: null,
}, },
}); });
export default mongoose.model('UserConfig', userConfigSchema); export default mongoose.model("UserConfig", userConfigSchema);

20
src/models/userScore.ts

@ -1,14 +1,14 @@
import mongoose from 'mongoose'; import mongoose from "mongoose";
const userScoreSchema = new mongoose.Schema({ const userScoreSchema = new mongoose.Schema({
authorID: { authorID: {
type: String, type: String,
required: true, required: true,
}, },
score: { score: {
type: Number, type: Number,
required: true, required: true,
}, },
}); });
export default mongoose.model('UserScore', userScoreSchema); export default mongoose.model("UserScore", userScoreSchema);

Loading…
Cancel
Save