Browse Source

Merge branch 'master' of github.com:ADawesomeguy/AwesomeSciBo

pull/9/head
Abheek Dhawan 4 years ago
parent
commit
9a4a1a688c
  1. 4
      .gitignore
  2. 141
      bot/awesomescibo.js
  3. 4
      bot/config.default.json
  4. 38
      bot/migrateScores.js
  5. 14
      bot/mongooseModels/mongooseGeneratedRoundModel.js
  6. 6
      bot/package-lock.json
  7. 8
      bot/package.json
  8. 1
      bot/userScore/745063586422063214

4
.gitignore

@ -7,4 +7,6 @@ round.pdf
bot/README.md
.eslintrc
.json
.env
.env
userScore
config.json

141
bot/awesomescibo.mjs → 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", "<h1>Here's your round!</h1>", (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 = '<html><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>';
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 =
`<br><br>${i}. Tossup\n<br><br>` +
`<strong>${question_category}</strong>` +
" " +
`<em>${tossup_format}</em>` +
" " +
tossup_question +
"<br><br>" +
"<strong>ANSWER:</strong> " +
tossup_answer +
"<br><br>";
htmlContent +=
"<br><br>Bonus\n<br><br>" +
`<strong>${question_category}</strong>` +
" " +
`<em>${bonus_format}</em>` +
" " +
bonus_question +
"<br><br>" +
"<strong>ANSWER:</strong> " +
bonus_answer +
"<br><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 = htmlContent.replace(/\n/g, "<br>");
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) {

4
bot/config.default.json

@ -0,0 +1,4 @@
{
"subjectURL": "https://moose.lcsrc.org/subjects/",
"gotenbergURL": "https://localhost:3136/convert/html"
}

38
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));

14
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);

6
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",

8
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",

1
bot/userScore/745063586422063214

@ -1 +0,0 @@
8
Loading…
Cancel
Save