Browse Source

Major changes to command flow and recognition. Please check diff for more info.

pull/8/head
Abheek Dhawan 4 years ago
parent
commit
05cac0aa64
  1. 561
      bot/awesomescibo.mjs
  2. 1219
      bot/package-lock.json

561
bot/awesomescibo.mjs

@ -8,6 +8,7 @@ import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
let hits = 0; let hits = 0;
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 hits`: send the number of rounds generated\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\nSource Code: https://github.com/ADawesomeguy/AwesomeSciBo (don't forget to star!)";
if (fs.existsSync('numhits.txt')) { if (fs.existsSync('numhits.txt')) {
fs.readFile('numhits.txt', 'utf8', function (err, data) { fs.readFile('numhits.txt', 'utf8', function (err, data) {
@ -20,151 +21,267 @@ if (fs.existsSync('numhits.txt')) {
fs.writeFile('numhits.txt', hits.toString(), (error) => { if (error) { console.log(error); } }); fs.writeFile('numhits.txt', hits.toString(), (error) => { if (error) { console.log(error); } });
} }
client.once('ready', () => { client.once('ready', () => {
console.log(client.user.username); console.log(client.user.username);
client.user.setActivity("for \"do be helping\"", { type: "WATCHING" }); client.user.setActivity("for \"do be helping\"", { type: "WATCHING" });
}); });
client.on('guildCreate', guild => { client.on('guildCreate', guild => {
guild.channels.cache.find(channel => channel.name === 'general').send("What is up peeps I am the AwesomeSciBo Bot!"); guild.channels.cache.find(channel => channel.name === 'general').send("'Sup, I'm the AwesomeSciBo bot!");
}); });
client.on('message', async message => { client.on('message', async message => {
if (message.content.startsWith("do be announcing") && message.author.id === process.argv[3]) {
const announcement = message.content.substring(17);
client.guilds.cache.forEach((guild) => {
const channel = guild.channels.cache.find(channel => channel.name === 'general');
if (channel) {
if (channel.type === "text") {
channel.send(announcement).catch(console.error);
}
}
});
}
if (message.content.toLowerCase() === "do be hits") {
message.channel.send(hits);
fs.writeFile('numhits.txt', hits.toString(), (error) => { if (error) { console.log(error); } });
}
if (message.content.toLowerCase() === ("do be helping")) {
message.channel.send(new Discord.MessageEmbed().setTitle("Help").setDescription("`do be helping`: display this help message\n`do be roundgen html`: send a round to the channel\n`do be roundgen html dm`: dm a round to you\n`do be roundgen pdf`: send a pdf round to the channel\n`do be roundgen pdf 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 hits`: send the number of rounds generated\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\nSource Code: https://github.com/ADawesomeguy/AwesomeSciBo (don't forget to star!)"));
if (message.author.bot) {
return;
} }
if (message.content.toLowerCase() === ("do be roundgen html dm")) {
fs.writeFile('round.html', "<h1>Here's your round!</h1>", (error) => { if (error) { console.log(error); } }); const formattedMessage = message.content.toLowerCase().replace(/\s+/g, '');
const person = client.users.cache.get(message.author.id); console.log(formattedMessage)
const i; if (formattedMessage.startsWith("dobe")) {
let generatingMsg = await message.channel.send("Generating..."); switch (formattedMessage) {
for (i = 1; i < 26; i++) { case 'dobehits':
const tossup_question; checkHits();
const question_category; break;
const tossup_format; case 'dobehelping':
const tossup_answer; sendHelpMessage();
const bonus_question; break;
const bonus_format; case 'doberoundgen':
const bonus_answer; generateRound(false);
const htmlContent = ""; break;
await fetch('https://scibowldb.com/api/questions/random') case 'doberoundgendm':
.then(response => response.json()) generateRound(true);
.then(data => { break;
tossup_question = data.question.tossup_question; case 'dobescoring':
tossup_answer = data.question.tossup_answer; startScoring();
question_category = data.question.category; break;
tossup_format = data.question.tossup_format; case 'dobetop':
bonus_question = data.question.bonus_question; showLeaderboard();
bonus_answer = data.question.bonus_answer; break;
bonus_format = data.question.bonus_format; case 'dobehappy':
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>"; dontWorryBeHappy();
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>"; break;
htmlContent = htmlContent.replace(/\n/g, "<br>"); case 'dobeservers':
fs.appendFile('round.html', htmlContent, (error) => { if (error) { console.log(error); } }); showServerNumber();
}); break;
case 'dobeiss':
showIssLocation();
break;
default:
otherCommands();
} }
generatingMsg.delete({ timeout: 1000 });
setTimeout(function () { person.send(new Discord.MessageEmbed().setTitle("Here's your round!").attachFiles("round.html")); }, 1000);
hits++;
} }
if (message.content.toLowerCase() === ("do be roundgen html")) {
fs.writeFile('round.html', "<h1>Here's your round!</h1>", (error) => { if (error) { console.log(error); } }); async function otherCommands() {
let i; if (message.content.toLowerCase().startsWith("do be announcing") && message.author.id === process.argv[3]) {
let generatingMsg = await message.channel.send("Generating..."); const announcement = message.content.substring(17);
for (i = 1; i < 26; i++) { client.guilds.cache.forEach((guild) => {
const tossup_question; const channel = guild.channels.cache.find(channel => channel.name === 'general');
const question_category; if (channel) {
const tossup_format; if (channel.type === "text") {
const tossup_answer; channel.send(announcement).catch(console.error);
const bonus_question; }
const bonus_format; }
const bonus_answer; });
const htmlContent = ""; } else if (message.content.toLowerCase().startsWith("do be training")) {
await fetch('https://scibowldb.com/api/questions/random') if (message.content === "do be training") {
const author = message.author;
fetch("https://scibowldb.com/api/questions/random")
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
tossup_question = data.question.tossup_question; let filter = m => m.author.id === message.author.id;
tossup_answer = data.question.tossup_answer; message.reply(data.question.tossup_question).then(() => {
question_category = data.question.category; message.channel.awaitMessages(filter, {
tossup_format = data.question.tossup_format; max: 1,
bonus_question = data.question.bonus_question; time: 30000,
bonus_answer = data.question.bonus_answer; errors: ['time']
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>"; .then(message => {
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>"; message = message.first();
htmlContent = htmlContent.replace(/\n/g, "<br>"); let score = 0;
fs.appendFile('round.html', htmlContent, (error) => { if (error) { console.log(error); } }); if (fs.existsSync(`userScore/${message.author.id}`)) {
}); fs.readFile(`userScore/${message.author.id}`, 'utf8', function (err, data) {
} score = Number(data);
generatingMsg.delete({ timeout: 1000 }); if (err) {
setTimeout(function () { message.channel.send(new Discord.MessageEmbed().setTitle("Here's your round!").attachFiles("round.html")); }, 1000); console.log(err);
hits++; }
} });
if (message.content.toLowerCase() === ("do be roundgen pdf dm")) { } else {
fs.writeFile('index.html', "<h1>Here's your round!</h1>", (error) => { if (error) { console.log(error); } }); fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
const person = client.users.cache.get(message.author.id); }
let i; let predicted = "unsure";
let generatingMsg = await message.channel.send("Generating..."); if (data.question.tossup_format === "Multiple Choice") {
for (i = 1; i < 26; i++) { if (message.content.charAt(0).toLowerCase() === data.question.tossup_answer.charAt(0).toLowerCase()) {
const tossup_question; predicted = "correct";
const question_category; } else {
const tossup_format; predicted = "incorrect";
const tossup_answer; }
const bonus_question; } else {
const bonus_format; if (message.content.toLowerCase() === data.question.tossup_answer.toLowerCase()) {
const bonus_answer; predicted = "correct";
const htmlContent = ""; } else {
await fetch('https://scibowldb.com/api/questions/random') predicted = "incorrect";
}
}
message.channel.send(`Correct answer: **${data.question.tossup_answer}**. Predicted: **${predicted}**. Please react to your answer!`);
message.react('✅');
message.react('❌');
const filter = (reaction, user) => {
return ['❌', '✅'].includes(reaction.emoji.name) && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 1, time: 600000, errors: ['time'] })
.then(userReaction => {
const reaction = userReaction.first();
if (reaction.emoji.name === "❌") {
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
message.reply(`nice try! Your score is now ${score}`);
} else {
score += 4;
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
message.reply(`nice job! Your score is now ${score}`);
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
}
})
.catch(collected => {
})
})
.catch ((collected, error) => {
message.reply('\n**ANSWER TIMEOUT**');
})
})
})
} else {
const subject = message.content.substring(15);
let subjectURL;
switch (subject) {
case 'astro':
case 'astronomy':
subjectURL = `https://moose.lcsrc.org/subjects/astronomy.json`;
break;
case 'bio':
case 'biology':
subjectURL = `https://moose.lcsrc.org/subjects/biology.json`;
break;
case 'ess':
case 'earth science':
case 'es':
subjectURL = `https://moose.lcsrc.org/subjects/ess.json`;
break;
case 'chem':
case 'chemistry':
subjectURL = `https://moose.lcsrc.org/subjects/chemistry.json`;
break;
case 'phys':
case 'physics':
subjectURL = `https://moose.lcsrc.org/subjects/physics.json`;
break;
case 'math':
subjectURL = `https://moose.lcsrc.org/subjects/math.json`;
break;
case 'energy':
subjectURL = `https://moose.lcsrc.org/subjects/energy.json`;
break;
default:
subjectURL = `https://scibowldb.com/api/questions/random`;
break;
}
const author = message.author;
fetch(subjectURL)
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
tossup_question = data.question.tossup_question; const questionNum = Math.floor(Math.random() * data.length);
tossup_answer = data.question.tossup_answer; let filter = m => m.author.id === message.author.id;
question_category = data.question.category; message.reply(data[questionNum].tossup_question).then(() => {
tossup_format = data.question.tossup_format; message.channel.awaitMessages(filter, {
bonus_question = data.question.bonus_question; max: 1,
bonus_answer = data.question.bonus_answer; time: 30000,
bonus_format = data.question.bonus_format; errors: ['time']
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>"; .then(message => {
htmlContent = htmlContent.replace(/\n/g, "<br>"); message = message.first();
fs.appendFile('index.html', htmlContent, (error) => { if (error) { console.log(error); } }); let score = 0;
}); if (fs.existsSync(`userScore/${message.author.id}`)) {
fs.readFile(`userScore/${message.author.id}`, 'utf8', function (err, data) {
score = Number(data);
if (err) {
console.log(err);
}
});
} else {
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
}
let predicted = "unsure";
if (data[questionNum].tossup_format === "Multiple Choice") {
if (message.content.charAt(0).toLowerCase() === data[questionNum].tossup_answer.charAt(0).toLowerCase()) {
predicted = "correct";
} else {
predicted = "incorrect";
}
} else {
if (message.content.toLowerCase() === data[questionNum].tossup_answer.toLowerCase()) {
predicted = "correct";
} else {
predicted = "incorrect";
}
}
message.channel.send(`Correct answer: **${data[questionNum].tossup_answer}**. Predicted: **${predicted}**. Please react to your answer!`);
message.react('✅');
message.react('❌');
const filter = (reaction, user) => {
return ['❌', '✅'].includes(reaction.emoji.name) && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 1, time: 600000, errors: ['time'] })
.then(userReaction => {
const reaction = userReaction.first();
if (reaction.emoji.name === "❌") {
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
message.reply(`nice try! Your score is now ${score}`);
} else {
score += 4;
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
message.reply(`nice job! Your score is now ${score}`);
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
}
})
.catch(collected => {
})
})
.catch ((collected, error) => {
message.reply('\n**ANSWER TIMEOUT**');
})
})
})
}
} else {
if (formattedMessage.startsWith("dobescoring" || "dobetraining")) {
return;
}
message.channel.send("That didn't quite make sense! Please use `do be helping` to see the available commands.")
} }
generatingMsg.delete({ timeout: 1000 });
execSync("curl --request POST --url http://localhost:3136/convert/html --header 'Content-Type: multipart/form-data' --form files=@index.html -o round.pdf", { encoding: 'utf-8' });
setTimeout(function () { person.send(new Discord.MessageEmbed().setTitle("Here's your round!").attachFiles("round.pdf")); }, 1000);
hits++;
} }
if (message.content.toLowerCase() === ("do be roundgen pdf")) {
async function checkHits() {
message.channel.send(hits);
fs.writeFile('numhits.txt', hits.toString(), (error) => { if (error) { console.log(error); } });
}
async function sendHelpMessage() {
message.channel.send(new Discord.MessageEmbed().setTitle("Help").setDescription(helpMessage));
}
async function generateRound(isDM) {
fs.writeFile('index.html', "<h1>Here's your round!</h1>", (error) => { if (error) { console.log(error); } }); fs.writeFile('index.html', "<h1>Here's your round!</h1>", (error) => { if (error) { console.log(error); } });
let i; let i;
let generatingMsg = await message.channel.send("Generating..."); let generatingMsg = await message.channel.send("Generating...");
for (i = 1; i < 26; i++) { for (i = 1; i < 26; i++) {
const tossup_question; let tossup_question;
const question_category; let question_category;
const tossup_format; let tossup_format;
const tossup_answer; let tossup_answer;
const bonus_question; let bonus_question;
const bonus_format; let bonus_format;
const bonus_answer; let bonus_answer;
const htmlContent = ""; let htmlContent = "";
await fetch('https://scibowldb.com/api/questions/random') await fetch('https://scibowldb.com/api/questions/random')
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
@ -181,12 +298,17 @@ client.on('message', async message => {
fs.appendFile('index.html', htmlContent, (error) => { if (error) { console.log(error); } }); fs.appendFile('index.html', htmlContent, (error) => { if (error) { console.log(error); } });
}); });
} }
generatingMsg.delete({ timeout: 1000 }); generatingMsg.delete({ timeout: 100 });
execSync("curl --request POST --url http://localhost:3136/convert/html --header 'Content-Type: multipart/form-data' --form files=@index.html -o round.pdf", { encoding: 'utf-8' }); execSync("curl --request POST --url http://localhost:3136/convert/html --header 'Content-Type: multipart/form-data' --form files=@index.html -o round.pdf", { encoding: 'utf-8' });
message.channel.send(new Discord.MessageEmbed().setTitle("Here's your round!").attachFiles("round.pdf")); if (isDM) {
client.users.cache.get(message.author.id).send(new Discord.MessageEmbed().setTitle("Here's your round!").attachFiles("round.pdf"));
} else {
message.channel.send(new Discord.MessageEmbed().setTitle("Here's your round!").attachFiles("round.pdf"));
}
hits++; hits++;
} }
if (message.content.toLowerCase() === "do be scoring") {
async function startScoring() {
let scoreA = 0; let scoreA = 0;
let scoreB = 0; let scoreB = 0;
const scoreboard = await message.channel.send(`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}`) const scoreboard = await message.channel.send(`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}`)
@ -219,190 +341,23 @@ client.on('message', async message => {
}); });
}) })
} }
if (message.content.toLowerCase() === "do be happy") { async function dontWorryBeHappy() {
message.channel.send(new Discord.MessageEmbed().setTitle(`Don't Worry Be Happy!`).setImage("https://media.giphy.com/media/7OKC8ZpTT0PVm/giphy.gif").setURL("https://youtu.be/d-diB65scQU")); message.channel.send(new Discord.MessageEmbed().setTitle(`Don't Worry Be Happy!`).setImage("https://media.giphy.com/media/7OKC8ZpTT0PVm/giphy.gif").setURL("https://youtu.be/d-diB65scQU"));
} }
if (message.content.toLowerCase() === "do be servers") {
async function showServerNumber() {
message.channel.send(client.guilds.cache.size); message.channel.send(client.guilds.cache.size);
} }
if (message.content.toLowerCase() === "do be iss") {
async function showIssLocation() {
await fetch("http://api.open-notify.org/iss-now.json") await fetch("http://api.open-notify.org/iss-now.json")
.then(request => request.json()) .then(request => request.json())
.then(data => { .then(data => {
message.channel.send(new Discord.MessageEmbed().setTitle("The current location of the ISS!").setImage(`https://api.mapbox.com/styles/v1/mapbox/light-v10/static/pin-s+000(${data.iss_position.longitude},${data.iss_position.latitude})/-87.0186,20,1/1000x1000?access_token=pk.eyJ1IjoiYWRhd2Vzb21lZ3V5IiwiYSI6ImNrbGpuaWdrYzJ0bGYydXBja2xsNmd2YTcifQ.Ude0UFOf9lFcQ-3BANWY5A`).setURL('https://spotthestation.nasa.gov/tracking_map.cfm'); message.channel.send(new Discord.MessageEmbed().setTitle("The current location of the ISS!").setImage(`https://api.mapbox.com/styles/v1/mapbox/light-v10/static/pin-s+000(${data.iss_position.longitude},${data.iss_position.latitude})/-87.0186,20,1/1000x1000?access_token=pk.eyJ1IjoiYWRhd2Vzb21lZ3V5IiwiYSI6ImNrbGpuaWdrYzJ0bGYydXBja2xsNmd2YTcifQ.Ude0UFOf9lFcQ-3BANWY5A`).setURL('https://spotthestation.nasa.gov/tracking_map.cfm'));
}); });
} }
if (message.content.startsWith("do be training")) {
if (message.content === "do be training") { async function showLeaderboard() {
const author = message.author;
fetch("https://scibowldb.com/api/questions/random")
.then(response => response.json())
.then(data => {
let filter = m => m.author.id === message.author.id;
message.reply(data.question.tossup_question).then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
let score = 0;
if (fs.existsSync(`userScore/${message.author.id}`)) {
fs.readFile(`userScore/${message.author.id}`, 'utf8', function (err, data) {
score = Number(data);
if (err) {
console.log(err);
}
});
} else {
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
}
let predicted = "unsure";
if (data.question.tossup_format === "Multiple Choice") {
if (message.content.charAt(0).toLowerCase() === data.question.tossup_answer.charAt(0).toLowerCase()) {
predicted = "correct";
} else {
predicted = "incorrect";
}
} else {
if (message.content.toLowerCase() === data.question.tossup_answer.toLowerCase()) {
predicted = "correct";
} else {
predicted = "incorrect";
}
}
message.channel.send(`Correct answer: **${data.question.tossup_answer}**. Predicted: **${predicted}**. Please react to your answer!`);
message.react('✅');
message.react('❌');
const filter = (reaction, user) => {
return ['❌', '✅'].includes(reaction.emoji.name) && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 1, time: 600000, errors: ['time'] })
.then(reaction => {
const reaction = reaction.first();
if (reaction.emoji.name === "❌") {
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
message.reply(`nice try! Your score is now ${score}`);
} else {
score += 4;
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
message.reply(`nice job! Your score is now ${score}`);
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
}
})
.catch(collected => {
})
})
.catch ((collected, error) => {
message.reply('\n**ANSWER TIMEOUT**');
})
})
})
} else {
const subject = message.content.substring(15);
let subjectURL;
switch (subject) {
case 'astro':
case 'astronomy':
subjectURL = `https://moose.lcsrc.org/subjects/astronomy.json`;
break;
case 'bio':
case 'biology':
subjectURL = `https://moose.lcsrc.org/subjects/biology.json`;
break;
case 'ess':
case 'earth science':
case 'es':
subjectURL = `https://moose.lcsrc.org/subjects/ess.json`;
break;
case 'chem':
case 'chemistry':
subjectURL = `https://moose.lcsrc.org/subjects/chemistry.json`;
break;
case 'phys':
case 'physics':
subjectURL = `https://moose.lcsrc.org/subjects/physics.json`;
break;
case 'math':
subjectURL = `https://moose.lcsrc.org/subjects/math.json`;
break;
case 'energy':
subjectURL = `https://moose.lcsrc.org/subjects/energy.json`;
break;
default:
subjectURL = `https://scibowldb.com/api/questions/random`;
break;
}
const author = message.author;
fetch(subjectURL)
.then(response => response.json())
.then(data => {
const questionNum = Math.floor(Math.random() * data.length);
let filter = m => m.author.id === message.author.id;
message.reply(data[questionNum].tossup_question).then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
let score = 0;
if (fs.existsSync(`userScore/${message.author.id}`)) {
fs.readFile(`userScore/${message.author.id}`, 'utf8', function (err, data) {
score = Number(data);
if (err) {
console.log(err);
}
});
} else {
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
}
let predicted = "unsure";
if (data[questionNum].tossup_format === "Multiple Choice") {
if (message.content.charAt(0).toLowerCase() === data[questionNum].tossup_answer.charAt(0).toLowerCase()) {
predicted = "correct";
} else {
predicted = "incorrect";
}
} else {
if (message.content.toLowerCase() === data[questionNum].tossup_answer.toLowerCase()) {
predicted = "correct";
} else {
predicted = "incorrect";
}
}
message.channel.send(`Correct answer: **${data[questionNum].tossup_answer}**. Predicted: **${predicted}**. Please react to your answer!`);
message.react('✅');
message.react('❌');
const filter = (reaction, user) => {
return ['❌', '✅'].includes(reaction.emoji.name) && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 1, time: 600000, errors: ['time'] })
.then(reaction => {
const reaction = reaction.first();
if (reaction.emoji.name === "❌") {
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
message.reply(`nice try! Your score is now ${score}`);
} else {
score += 4;
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
message.reply(`nice job! Your score is now ${score}`);
fs.writeFile(`userScore/${message.author.id}`, score.toString(), (error) => { if (error) { console.log(error); } });
}
})
.catch(collected => {
})
})
.catch ((collected, error) => {
message.reply('\n**ANSWER TIMEOUT**');
})
})
})
}
}
if (message.content.toLowerCase() === "do be top") {
let messageContent = ''; let messageContent = '';
let scores = []; let scores = [];
@ -414,7 +369,11 @@ client.on('message', async message => {
files.forEach(function (file) { files.forEach(function (file) {
scores.push(`${fs.readFileSync('userScore/' + file, 'utf8')}|<@${file}>`) scores.push(`${fs.readFileSync('userScore/' + file, 'utf8')}|<@${file}>`)
}); });
const scoresFormatted = scores.sort(function(a, b){return b.split('|')[0] - a.split('|')[0]}); const scoresFodrmatted = scores.sort(function(a, b){return b.split('|')[0] - a.split('|')[0]});
if (scores.length < 10) {
message.channel.send("Not enough scores yet!");
return;
}
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
const currentScore = scoresFormatted[i].split('|'); const currentScore = scoresFormatted[i].split('|');
messageContent += `${currentScore[1]}: ${currentScore[0]}\n\n`; messageContent += `${currentScore[1]}: ${currentScore[0]}\n\n`;

1219
bot/package-lock.json

File diff suppressed because it is too large
Loading…
Cancel
Save