diff --git a/.gitignore b/.gitignore index c607f42..fb11a82 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,6 @@ round.pdf bot/README.md .eslintrc .json -.env \ No newline at end of file +.env +userScore +config.json diff --git a/bot/awesomescibo.mjs b/bot/awesomescibo.js similarity index 81% rename from bot/awesomescibo.mjs rename to bot/awesomescibo.js index b58996c..5f30412 100755 --- a/bot/awesomescibo.mjs +++ b/bot/awesomescibo.js @@ -1,40 +1,47 @@ #!/usr/bin/env node -import * as Discord from "discord.js"; -import { execSync } from "child_process"; +const Discord = require("discord.js"); +const execSync = require("child_process").execSync; const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION"], }); -import fetch from "node-fetch"; -import * as fs from "fs"; -import axios from "axios"; -import userScore from "./mongooseModels/mongooseUserScoreModel.js"; -import {} from "dotenv/config.js"; -import mongoose from "mongoose"; +const fetch = require("node-fetch"); +const fs = require("fs"); +const axios = require("axios"); +const userScore = require("./mongooseModels/mongooseUserScoreModel.js"); +const generatedRound = require("./mongooseModels/mongooseGeneratedRoundModel.js"); +const mongoose = require("mongoose"); +let config = {}; +process.env.CI ? config = require("./config.default.json") : config = require("./config.json") const helpMessage = - "`do be helping`: display this help message\n`do be roundgen`: send a pdf round to the channel\n`do be roundgen dm`: dm a pdf round to you\n`do be scoring`: start a scoring session\n > `do be scoring (a/b)(4/10)`: add points to Team A or Team B\n > `do be scoring stop`: end scoring session and post final points\n > `do be servers`: send the number of servers this bot is a part of\n > `do be iss`: show the current location of the International Space Station\n`do be training`: send a quick practice problem (you **must** react to your answer, or the bot will yell at you)\n > subject options: astro, phys, chem, math, bio, ess, energy\n`do be top`: list cross-server top 10 players\n `do be about`: List people who contributed to this bot\n Source Code: https://github.com/ADawesomeguy/AwesomeSciBo (don't forget to star!)"; + "`do be helping`: display this help message\n`do be roundgen`: send a pdf round to the channel\n`do be scoring`: start a scoring session\n > `do be scoring (a/b)(4/10)`: add points to Team A or Team B\n > `do be scoring stop`: end scoring session and post final points\n > `do be servers`: send the number of servers this bot is a part of\n > `do be iss`: show the current location of the International Space Station\n`do be training`: send a quick practice problem (you **must** react to your answer, or the bot will yell at you)\n > subject options: astro, phys, chem, math, bio, ess, energy\n`do be top`: list cross-server top 10 players\n `do be about`: List people who contributed to this bot\n Source Code: https://github.com/ADawesomeguy/AwesomeSciBo (don't forget to star!)"; client.once("ready", () => { - mongoose - .connect(process.env.MONGO_URI, { - useUnifiedTopology: true, - useNewUrlParser: true, - }) - .then(() => { - console.log(client.user.username); - client.user.setActivity( - 'for "do be helping" | Add me to your own server: adat.link/awscibo', - { type: "WATCHING" } - ); - }) - .catch((err) => console.log(err)); + // Connect to MongoDB using mongoose + if (!process.env.CI) { + mongoose + .connect(process.env.MONGO_URI, { + useUnifiedTopology: true, + useNewUrlParser: true, + }) + .then(() => { + // Log client tag and set status + console.log(`Logged in as: ${client.user.username}!`); + client.user.setActivity( + 'for "do be helping" | Add me to your own server: adat.link/awscibo', + { type: "WATCHING" } + ); + }) + .catch((err) => console.log(err)); + } }); client.on("guildCreate", (guild) => { guild.channels.cache .find( (channel) => + // Find channel by name channel.name === process.env.WELCOME_CHANNEL && channel.type === "text" ) .send("'Sup, I'm the AwesomeSciBo bot!") @@ -42,7 +49,7 @@ client.on("guildCreate", (guild) => { }); function getSubjectUrl(subject) { - return `https://moose.lcsrc.org/subjects/${subject}.json`; + return `${config.subjectURL}${subject}.json`; } async function updateScore(isCorrect, score, authorId) { @@ -299,14 +306,10 @@ function sendHelpMessage(message) { ); } -async function generateRound(message, isDM) { - fs.writeFile("index.html", "

Here's your round!

", (error) => { - if (error) { - console.log(error); - } - }); +async function generateRound(message) { + const generatingMessage = message.channel.send("Generating..."); let i; - let generatingMsg = await message.channel.send("Generating..."); + let finalizedHTML = '

ROUND GENERATED BY AWESOMESCIBO USING THE SCIBOWLDB API

'; for (i = 1; i < 26; i++) { let tossup_question; let question_category; @@ -326,62 +329,28 @@ async function generateRound(message, isDM) { bonus_question = data.question.bonus_question; bonus_answer = data.question.bonus_answer; bonus_format = data.question.bonus_format; - htmlContent = - `

${i}. Tossup\n

` + - `${question_category}` + - " " + - `${tossup_format}` + - " " + - tossup_question + - "

" + - "ANSWER: " + - tossup_answer + - "

"; - htmlContent += - "

Bonus\n

" + - `${question_category}` + - " " + - `${bonus_format}` + - " " + - bonus_question + - "

" + - "ANSWER: " + - bonus_answer + - "

"; + htmlContent = `

TOSS-UP

\n
` + `${i}) ${question_category}` + " " + `${tossup_format}` + " " + tossup_question + "

" + "ANSWER: " + tossup_answer + "
"; + htmlContent += `

BONUS

\n
` + `${i}) ${question_category}` + " " + `${bonus_format}` + " " + bonus_question + "

" + "ANSWER: " + bonus_answer + "



"; htmlContent = htmlContent.replace(/\n/g, "
"); - fs.appendFile("index.html", htmlContent, (error) => { - if (error) { - console.log(error); - } - }); + finalizedHTML += htmlContent; + if (i === 25) { + newGeneratedRound = new generatedRound({ + htmlContent: finalizedHTML, + requestedBy: message.author.id, + }); + newGeneratedRound.save((err, round) => { + if (err) { + console.log(err); + return; + } + message.channel.messages.fetch(generatingMessage.id) + .then(generatingMessage => { + const msg = generatingMessage.first(); + msg.edit(`${message.author}, here's your round: https://api.adawesome.tech/round/${round._id.toString()}`); + }); }); - } - if (generatingMsg) { - generatingMsg.delete({ timeout: 100 }).catch(console.error); - } - execSync( - "curl --request POST --url https://localhost:3136/convert/html --header 'Content-Type: multipart/form-data' --form files=@index.html -o round.pdf", - { encoding: "utf-8" } - ); - if (isDM) { - client.users.cache - .get(message.author.id) - .send( - new Discord.MessageEmbed() - .setTitle("Here's your round!") - .attachFiles("round.pdf") - ) - .catch(() => - message.reply( - "Unable to DM you! Make sure DMs from server members are allowed." - ) - ); - } else { - message.channel.send( - new Discord.MessageEmbed() - .setTitle("Here's your round!") - .attachFiles("round.pdf") - ); + } + }); } } @@ -496,7 +465,7 @@ function showLeaderboard(message) { function aboutMessage(message) { message.channel.send( new Discord.MessageEmbed().setTitle("Contributors: ").setDescription(` - <@745063586422063214> + <@745063586422063214> <@650525101048987649> `) // Add more contributors here, first one is Abheek, second one is Tejas ); @@ -507,7 +476,7 @@ client.on("message", async (message) => { return; } - const formattedMessage = message.content.toLowerCase().replace(" ", ""); + const formattedMessage = message.content.toLowerCase().replace(/ /g, ""); if (formattedMessage.startsWith("dobe")) { // Bot prefix is "do be" switch (formattedMessage) { diff --git a/bot/config.default.json b/bot/config.default.json new file mode 100644 index 0000000..7bfe57b --- /dev/null +++ b/bot/config.default.json @@ -0,0 +1,4 @@ +{ + "subjectURL": "https://moose.lcsrc.org/subjects/", + "gotenbergURL": "https://localhost:3136/convert/html" +} diff --git a/bot/migrateScores.js b/bot/migrateScores.js new file mode 100644 index 0000000..2e208bb --- /dev/null +++ b/bot/migrateScores.js @@ -0,0 +1,38 @@ +const fs = require("fs"); +const mongoose = require("mongoose"); +const Schema = mongoose.Schema; + +const dirName = "userScore"; + +const fileNames = fs.readdirSync(dirName); + +const userScoreSchema = new Schema({ + authorID: { + type: String, + required: true, + }, + score: { + type: Number, + required: true, + }, +}); + +const userScore = mongoose.model("UserScore", userScoreSchema); + +mongoose + .connect(process.env.MONGO_URI, { + useUnifiedTopology: true, + useNewUrlParser: true, + }) + .then(() => { + fileNames.forEach(file => { + fs.readFile(dirName + "/" + file, 'utf-8', (err, content) => { + const migrateScore = new userScore({ + authorID: file, + score: content, + }); + migrateScore.save(); + }); + }); + }) + .catch((err) => console.log(err)); diff --git a/bot/mongooseModels/mongooseGeneratedRoundModel.js b/bot/mongooseModels/mongooseGeneratedRoundModel.js new file mode 100644 index 0000000..b0e9515 --- /dev/null +++ b/bot/mongooseModels/mongooseGeneratedRoundModel.js @@ -0,0 +1,14 @@ +const mongoose = require("mongoose"); + +const generatedRoundSchema = new mongoose.Schema({ + htmlContent: { + type: String, + required: true, + }, + requestedBy: { + type: String, + required: true, + }, +}); + +module.exports = mongoose.model("GeneratedRounds", generatedRoundSchema); diff --git a/bot/package-lock.json b/bot/package-lock.json index 8207f1a..df633ab 100644 --- a/bot/package-lock.json +++ b/bot/package-lock.json @@ -391,7 +391,6 @@ "node": ">=0.10" } }, - "node_modules/discord.js": { "version": "12.5.1", "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-12.5.1.tgz", @@ -944,8 +943,7 @@ "bson": "^1.1.4", "denque": "^1.4.1", "optional-require": "^1.0.2", - "safe-buffer": "^5.1.2", - "saslprep": "^1.0.0" + "safe-buffer": "^5.1.2" }, "engines": { "node": ">=4" @@ -2578,7 +2576,7 @@ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" } } - }, + }, "text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", diff --git a/bot/package.json b/bot/package.json index ac6dc2d..c1b06cb 100644 --- a/bot/package.json +++ b/bot/package.json @@ -10,13 +10,13 @@ }, "name": "awscibo", "version": "0.4.1", - "main": "awesomescibo.mjs", + "main": "awesomescibo.js", "bin": { - "awscibo": "./awesomescibo.mjs" + "awscibo": "./awesomescibo.js" }, "scripts": { - "test": "node awesomescibo.mjs randomtoken", - "start": "nodemon awesomescibo.mjs" + "test": "node awesomescibo.js randomtoken", + "start": "nodemon awesomescibo.js" }, "keywords": [ "discord", diff --git a/bot/userScore/745063586422063214 b/bot/userScore/745063586422063214 deleted file mode 100644 index 301160a..0000000 --- a/bot/userScore/745063586422063214 +++ /dev/null @@ -1 +0,0 @@ -8 \ No newline at end of file