Browse Source

Major changes: going to detail more

pull/7/head
TejasOS 4 years ago
parent
commit
7b019a34b8
  1. 4
      .gitignore
  2. 828
      bot/awesomescibo.mjs
  3. 3
      bot/package.json
  4. 1
      bot/userScore/id
  5. 2868
      package-lock.json
  6. 10
      package.json

4
.gitignore

@ -5,4 +5,6 @@ round.html
round.md round.md
round.pdf round.pdf
bot/README.md bot/README.md
.eslintrc.json .eslintrc
.json
.env

828
bot/awesomescibo.mjs

@ -7,435 +7,475 @@ const client = new Discord.Client({
}); });
import fetch from "node-fetch"; import fetch from "node-fetch";
import * as fs from "fs"; import * as fs from "fs";
import * as path from "path";
import axios from "axios"; import axios from "axios";
import userScore from "./mongooseModels/mongooseUserScoreModel.js"; import userScore from "./mongooseModels/mongooseUserScoreModel.js";
import {} from 'dotenv/config.js'; import {} from "dotenv/config.js";
import mongoose from "mongoose"; import mongoose from "mongoose";
const helpMessage = 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\nSource 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 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\nSource Code: https://github.com/ADawesomeguy/AwesomeSciBo (don't forget to star!)";
client.once("ready", () => { client.once("ready", () => {
mongoose.connect(process.env.MONGO_URI, {useUnifiedTopology: true, useNewUrlParser: true}).then(() => { mongoose
console.log(client.user.username); .connect(process.env.MONGO_URI, {
client.user.setActivity( useUnifiedTopology: true,
'for "do be helping" | Add me to your own server: adat.link/awscibo', useNewUrlParser: true,
{ type: "WATCHING" } })
) .then(() => {
}).catch(err => console.log(err)) 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));
}); });
client.on("guildCreate", (guild) => { client.on("guildCreate", (guild) => {
guild.channels.cache guild.channels.cache
.find((channel) => channel.name === "general" && channel.type === "text") .find(
(channel) =>
channel.name === process.env.WELCOME_CHANNEL && channel.type === "text"
)
.send("'Sup, I'm the AwesomeSciBo bot!") .send("'Sup, I'm the AwesomeSciBo bot!")
.catch(console.error); .catch(console.error);
}); });
client.on("message", async (message) => { function getSubjectUrl(subject) {
if (message.author.bot) { return `https://moose.lcsrc.org/subjects/${subject}.json`;
return; }
}
async function updateScore(isCorrect, score, authorId) {
const formattedMessage = message.content.toLowerCase().replace(/\s+/g, ""); if (!isCorrect) {
if (formattedMessage.startsWith("dobe")) { return `Nice try! Your score is still ${score}.`;
switch (formattedMessage) { } else {
case "dobehelping": score += 4;
sendHelpMessage(); if (score == 4) {
break; const newUserScore = new userScore({
case "doberoundgen": authorID: authorId,
generateRound(false); score: score,
break; });
case "doberoundgendm": newUserScore.save((err) =>
generateRound(true); err
break; ? console.log("Error creating new user for scoring")
case "dobescoring": : console.log("Sucessfully created user to score.")
startScoring(); );
break; } else {
case "dobetop": const doc = await userScore.findOne({
showLeaderboard(); authorID: authorId,
break; });
case "dobehappy": doc.score = doc.score + 4;
dontWorryBeHappy(); doc.save();
break; console.log("Succesfully updated score.");
case "dobeservers":
showServerNumber();
break;
case "dobeiss":
showIssLocation();
break;
default:
otherCommands();
} }
return `Great job! Your score is now ${score}.`;
} }
}
async function otherCommands() { async function otherCommands(message) {
if ( if (
message.content.toLowerCase().startsWith("do be announcing") && message.content.toLowerCase().startsWith("do be announcing") &&
message.author.id === process.argv[3] (message.author.id === process.env.ABHEEK_USER_ID ||
) { message.author.id === process.env.TEJAS_USER_ID)
const announcement = message.content.substring(17); ) {
client.guilds.cache.forEach((guild) => { const announcement = message.content.substring(17);
const channel = guild.channels.cache.find( client.guilds.cache.forEach((guild) => {
(channelGeneral) => channelGeneral.name === "general" const channel = guild.channels.cache.find(
); (channelGeneral) =>
if (channel) { channelGeneral.name === process.env.ANNOUNCING_CHANNEL
if (channel.type === "text") { );
channel.send(announcement).catch(console.error); if (channel) {
} if (channel.type === "text") {
channel.send(announcement).catch(console.error);
}
}
});
} else if (message.content.toLowerCase().startsWith("do be training")) {
const authorId = message.author.id;
let score;
userScore
.findOne({ authorID: authorId })
.lean()
.then((obj, err) => {
if (!obj) {
score = 0;
} else if (obj) {
score = obj.score;
} else {
console.log(err);
} }
}); });
} else if (message.content.toLowerCase().startsWith("do be training")) { if (message.content === "do be training") {
// BEGIN CHANGES axios.get("https://scibowldb.com/api/questions/random").then((res) => {
if (message.content === "do be training") { const data = res.data;
axios.get("https://scibowldb.com/api/questions/random").then(data => { const messageAuthorFilter = (m) => m.author.id === message.author.id;
const messageAuthorFilter = (m) => m.author.id === message.author.id; message.reply(data.question.tossup_question).then(() => {
message message.channel
.reply(data.data.question.tossup_question) .awaitMessages(messageAuthorFilter, {
.then(() => { max: 1,
message.channel.awaitMessages(messageAuthorFilter, { time: 30000,
max: 1, errors: ["time"],
time: 30000,
errors: ["time"],
});
}) })
.then(resMessage => { .then((answerMsg) => {
const responseAuthorID = resMessage.first().author.id; answerMsg = answerMsg.first();
}); let predicted = null;
});
} else { if (data.question.tossup_format === "Multiple Choice") {
const subject = message.content.substring(15); if (
let subjectURL; answerMsg.content.charAt(0).toLowerCase() ===
switch (subject) { data.question.tossup_answer.charAt(0).toLowerCase()
case "astro": ) {
case "astronomy": predicted = "correct";
subjectURL = `https://moose.lcsrc.org/subjects/astronomy.json`; } else {
break; predicted = "incorrect";
case "bio": }
case "biology": } else {
subjectURL = `https://moose.lcsrc.org/subjects/biology.json`; if (
break; answerMsg.content.toLowerCase() ===
case "ess": data.question.tossup_answer.toLowerCase()
case "earth science": ) {
case "es": predicted = "correct";
subjectURL = `https://moose.lcsrc.org/subjects/ess.json`; } else {
break; predicted = "incorrect";
case "chem": }
case "chemistry": }
subjectURL = `https://moose.lcsrc.org/subjects/chemistry.json`; answerMsg.channel.send(
break; `Correct answer: **${data.question.tossup_answer}**. Predicted: **${predicted}**. Please react to your answer!`
case "phys": );
case "physics": answerMsg.react("✅");
subjectURL = `https://moose.lcsrc.org/subjects/physics.json`; answerMsg.react("❌");
break; const filter = (reaction, user) => {
case "math": return (
subjectURL = `https://moose.lcsrc.org/subjects/math.json`; ["❌", "✅"].includes(reaction.emoji.name) &&
break; user.id === answerMsg.author.id
case "energy": );
subjectURL = `https://moose.lcsrc.org/subjects/energy.json`; };
break; answerMsg
default: .awaitReactions(filter, {
message.channel.send("Not a valid subject!");
return;
}
const authorId = message.author.id;
fetch(subjectURL)
.then((response) => response.json())
.then((data) => {
const questionNum = Math.floor(Math.random() * data.length);
const messageFilter = (m) => m.author.id === authorId;
message.reply(data[questionNum].tossup_question).then(() => {
message.channel
.awaitMessages(messageFilter, {
max: 1, max: 1,
time: 30000, time: 600000,
errors: ["time"], errors: ["time"],
}) })
.then((answerMsg) => { .then((userReaction) => {
answerMsg = answerMsg.first(); const reaction = userReaction.first();
const userDocScore = userScore.findOne({authorID: authorId}).select("score"); if (reaction.emoji.name === "❌") {
let score = userDocScore || 0; updateScore(false, score, authorId).then((msgToReply) =>
answerMsg.reply(msgToReply)
let predicted = null; );
if (data[questionNum].tossup_format === "Multiple Choice") {
if (
answerMsg.content.charAt(0).toLowerCase() ===
data[questionNum].tossup_answer.charAt(0).toLowerCase()
) {
predicted = "correct";
} else {
predicted = "incorrect";
}
} else { } else {
if ( updateScore(true, score, authorId).then((msgToReply) =>
answerMsg.content.toLowerCase() === answerMsg.reply(msgToReply)
data[questionNum].tossup_answer.toLowerCase()
) {
predicted = "correct";
} else {
predicted = "incorrect";
}
}
answerMsg.channel.send(
`Correct answer: **${data[questionNum].tossup_answer}**. Predicted: **${predicted}**. Please react to your answer!`
);
answerMsg.react("✅");
answerMsg.react("❌");
const reactionFilter = (reaction, user) => {
return (
["❌", "✅"].includes(reaction.emoji.name) &&
user.id === answerMsg.author.id
); );
}; }
answerMsg
.awaitReactions(reactionFilter, {
max: 1,
time: 600000,
errors: ["time"],
})
.then(async (userReaction) => {
const reaction = userReaction.first();
if (reaction.emoji.name === "❌") {
answerMsg.reply(`nice try! Your score is now ${score.toString()}`);
} else {
score += 4;
if (score == 4) {
const newUserScore = new userScore({
authorID: authorId,
score: score,
});
newUserScore.save((err) =>
err
? console.log(
"Error creating new user for scoring"
)
: console.log(
"Sucessfully created user to score."
)
);
} else {
const doc = await userScore.findOne({
authorID: authorId,
});
doc.score = doc.score + 4;
doc.save();
}
answerMsg.reply(`nice job! Your score is now ${score.toString()}`);
}
})
.catch((collected) => {});
})
.catch((collected, error) => {
message.reply("\n**ANSWER TIMEOUT**");
}); });
}); });
}) });
.catch(console.error); });
}
} else { } else {
if (formattedMessage.startsWith("dobescoring" || "dobetraining")) { const subject = message.content.substring(15);
return; let subjectURL;
switch (subject) {
case "astro":
case "astronomy":
subjectURL = getSubjectUrl("astronomy");
break;
case "bio":
case "biology":
subjectURL = getSubjectUrl("biology");
break;
case "ess":
case "earth science":
case "es":
subjectURL = getSubjectUrl("ess");
break;
case "chem":
case "chemistry":
subjectURL = getSubjectUrl("astronomy");
break;
case "phys":
case "physics":
subjectURL = getSubjectUrl("physics");
break;
case "math":
subjectURL = getSubjectUrl("math");
break;
case "energy":
subjectURL = getSubjectUrl("energy");
break;
default:
message.channel.send("Not a valid subject!");
return;
} }
message.channel.send(
"That didn't quite make sense! Please use `do be helping` to see the available commands."
);
}
}
async function sendHelpMessage() { axios
message.channel.send( .get(subjectURL)
new Discord.MessageEmbed().setTitle("Help").setDescription(helpMessage) .then((res) => {
); const data = res.data;
} const questionNum = Math.floor(Math.random() * data.length);
const messageFilter = (m) => m.author.id === authorId;
message.reply(data[questionNum].tossup_question).then(() => {
message.channel
.awaitMessages(messageFilter, {
max: 1,
time: 30000,
errors: ["time"],
})
.then((answerMsg) => {
answerMsg = answerMsg.first();
async function generateRound(isDM) { let predicted = null;
fs.writeFile("index.html", "<h1>Here's your round!</h1>", (error) => { if (data[questionNum].tossup_format === "Multiple Choice") {
if (error) { if (
console.log(error); answerMsg.content.charAt(0).toLowerCase() ===
} data[questionNum].tossup_answer.charAt(0).toLowerCase()
}); ) {
let i; predicted = "correct";
let generatingMsg = await message.channel.send("Generating..."); } else {
for (i = 1; i < 26; i++) { predicted = "incorrect";
let tossup_question; }
let question_category; } else {
let tossup_format; if (
let tossup_answer; answerMsg.content.toLowerCase() ===
let bonus_question; data[questionNum].tossup_answer.toLowerCase()
let bonus_format; ) {
let bonus_answer; predicted = "correct";
let htmlContent = ""; } else {
await fetch("https://scibowldb.com/api/questions/random") predicted = "incorrect";
.then((response) => response.json()) }
.then((data) => { }
tossup_question = data.question.tossup_question; answerMsg.channel.send(
tossup_answer = data.question.tossup_answer; `Correct answer: **${data[questionNum].tossup_answer}**. Predicted: **${predicted}**. Please react to your answer!`
question_category = data.question.category; );
tossup_format = data.question.tossup_format; answerMsg.react("✅");
bonus_question = data.question.bonus_question; answerMsg.react("❌");
bonus_answer = data.question.bonus_answer; const reactionFilter = (reaction, user) => {
bonus_format = data.question.bonus_format; return (
htmlContent = ["❌", "✅"].includes(reaction.emoji.name) &&
`<br><br>${i}. Tossup\n<br><br>` + user.id === answerMsg.author.id
`<strong>${question_category}</strong>` + );
" " + };
`<em>${tossup_format}</em>` + answerMsg
" " + .awaitReactions(reactionFilter, {
tossup_question + max: 1,
"<br><br>" + time: 600000,
"<strong>ANSWER:</strong> " + errors: ["time"],
tossup_answer + })
"<br><br>"; .then(async (userReaction) => {
htmlContent += const reaction = userReaction.first();
"<br><br>Bonus\n<br><br>" + if (reaction.emoji.name == "❌") {
`<strong>${question_category}</strong>` + updateScore(false, score, authorId).then((msgToReply) =>
" " + answerMsg.reply(msgToReply)
`<em>${bonus_format}</em>` + );
" " + } else {
bonus_question + updateScore(true, score, authorId).then((msgToReply) =>
"<br><br>" + answerMsg.reply(msgToReply)
"<strong>ANSWER:</strong> " + );
bonus_answer + }
"<br><br>"; })
htmlContent = htmlContent.replace(/\n/g, "<br>"); .catch((collected) => {});
fs.appendFile("index.html", htmlContent, (error) => { })
if (error) { .catch((collected, error) => {
console.log(error); message.reply("\n**ANSWER TIMEOUT**");
} });
}); });
}); })
.catch(console.error);
} }
if (generatingMsg) { } else {
generatingMsg.delete({ timeout: 100 }).catch(console.error); message.channel.send(
} "That didn't quite make sense! Please use `do be helping` to see the available commands."
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")
);
}
} }
}
async function startScoring() { async function sendHelpMessage(message) {
let scoreA = 0; message.channel.send(
let scoreB = 0; new Discord.MessageEmbed().setTitle("Help").setDescription(helpMessage)
const scoreboard = await message.channel );
.send(`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}`) }
.then((scoreboard) => {
const filter = (m) => m.content.includes("do be"); async function generateRound(message, isDM) {
const collector = message.channel.createMessageCollector(filter, { fs.writeFile("index.html", "<h1>Here's your round!</h1>", (error) => {
time: 1500000, if (error) {
}); console.log(error);
collector.on("collect", (m) => { }
if (m.content.toLowerCase() === "do be scoring a 4") { });
m.delete({ timeout: 1000 }).catch(console.error); let i;
scoreA += 4; let generatingMsg = await message.channel.send("Generating...");
scoreboard.channel.send( for (i = 1; i < 26; i++) {
`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}` let tossup_question;
); let question_category;
} else if (m.content.toLowerCase() === "do be scoring a 10") { let tossup_format;
m.delete({ timeout: 1000 }).catch(console.error); let tossup_answer;
scoreA += 10; let bonus_question;
scoreboard.channel.send( let bonus_format;
`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}` let bonus_answer;
); let htmlContent = "";
} else if (m.content.toLowerCase() === "do be scoring b 4") { await fetch("https://scibowldb.com/api/questions/random")
m.delete({ timeout: 1000 }).catch(console.error); .then((response) => response.json())
scoreB += 4; .then((data) => {
scoreboard.channel.send( tossup_question = data.question.tossup_question;
`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}` tossup_answer = data.question.tossup_answer;
); question_category = data.question.category;
} else if (m.content.toLowerCase() === "do be scoring b 10") { tossup_format = data.question.tossup_format;
m.delete({ timeout: 1000 }).catch(console.error); bonus_question = data.question.bonus_question;
scoreB += 10; bonus_answer = data.question.bonus_answer;
scoreboard.channel.send( bonus_format = data.question.bonus_format;
`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}` htmlContent =
); `<br><br>${i}. Tossup\n<br><br>` +
} else if (m.content === "do be scoring stop") { `<strong>${question_category}</strong>` +
m.delete({ timeout: 1000 }).catch(console.error); " " +
scoreboard.delete({ timeout: 1000 }); `<em>${tossup_format}</em>` +
m.channel.send( " " +
`**FINAL SCORE:**\nTeam A: ${scoreA}\nTeam B: ${scoreB}` tossup_question +
); "<br><br>" +
collector.stop(); "<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 = htmlContent.replace(/\n/g, "<br>");
fs.appendFile("index.html", htmlContent, (error) => {
if (error) {
console.log(error);
} }
}); });
}); });
} }
async function dontWorryBeHappy() { 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( message.channel.send(
new Discord.MessageEmbed() new Discord.MessageEmbed()
.setTitle(`Don't Worry Be Happy!`) .setTitle("Here's your round!")
.setImage("https://media.giphy.com/media/7OKC8ZpTT0PVm/giphy.gif") .attachFiles("round.pdf")
.setURL("https://youtu.be/d-diB65scQU")
); );
} }
}
async function showServerNumber() { async function startScoring(message) {
message.channel.send(client.guilds.cache.size); let scoreA = 0;
} let scoreB = 0;
await message.channel
async function showIssLocation() { .send(`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}`)
await fetch("http://api.open-notify.org/iss-now.json") .then((scoreboard) => {
.then((request) => request.json()) const filter = (m) => m.content.includes("do be");
.then((data) => { const collector = message.channel.createMessageCollector(filter, {
message.channel.send( time: 1500000,
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")
);
}); });
} collector.on("collect", (m) => {
if (m.content.toLowerCase() === "do be scoring a 4") {
m.delete({ timeout: 1000 }).catch(console.error);
scoreA += 4;
scoreboard.channel.send(
`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}`
);
} else if (m.content.toLowerCase() === "do be scoring a 10") {
m.delete({ timeout: 1000 }).catch(console.error);
scoreA += 10;
scoreboard.channel.send(
`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}`
);
} else if (m.content.toLowerCase() === "do be scoring b 4") {
m.delete({ timeout: 1000 }).catch(console.error);
scoreB += 4;
scoreboard.channel.send(
`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}`
);
} else if (m.content.toLowerCase() === "do be scoring b 10") {
m.delete({ timeout: 1000 }).catch(console.error);
scoreB += 10;
scoreboard.channel.send(
`Here's the score:\nTeam A: ${scoreA}\nTeam B: ${scoreB}`
);
} else if (m.content === "do be scoring stop") {
m.delete({ timeout: 1000 }).catch(console.error);
scoreboard.delete({ timeout: 1000 });
m.channel.send(
`**FINAL SCORE:**\nTeam A: ${scoreA}\nTeam B: ${scoreB}`
);
collector.stop();
}
});
});
}
async function showLeaderboard() { async function dontWorryBeHappy(message) {
let messageContent = ""; message.channel.send(
let scores = []; new Discord.MessageEmbed()
.setTitle(`Don't Worry Be Happy!`)
.setImage("https://media.giphy.com/media/7OKC8ZpTT0PVm/giphy.gif")
.setURL("https://youtu.be/d-diB65scQU")
);
}
const directoryPath = path.join("userScore"); async function showServerNumber(message) {
fs.readdir(directoryPath, function (err, files) { message.channel.send(client.guilds.cache.size);
}
async function showIssLocation(message) {
await fetch("http://api.open-notify.org/iss-now.json")
.then((request) => request.json())
.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")
);
});
}
async function showLeaderboard(message) {
let messageContent = "";
userScore
.find({})
.sort({ score: -1 })
.exec((err, obj) => {
if (err) { if (err) {
return console.log("Unable to scan directory: " + err); console.log(err);
return message.reply(
"Uh oh! :( There was an internal error. Please try again."
);
} }
files.forEach(function (file) { if (obj.length < 2) {
scores.push( return message.reply(
`${fs.readFileSync("userScore/" + file, "utf8")}|<@${file}>` `There are only ${obj.length} users, we need at least 10!`
); );
});
const scoresFormatted = 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 < 2; i++) {
const currentScore = scoresFormatted[i].split("|"); messageContent += `${i + 1}: <@${obj[i].authorID}>: ${obj[i].score}\n`;
messageContent += `${currentScore[1]}: ${currentScore[0]}\n\n`;
} }
message.channel.send( message.channel.send(
new Discord.MessageEmbed() new Discord.MessageEmbed()
@ -443,9 +483,49 @@ client.on("message", async (message) => {
.setDescription(messageContent) .setDescription(messageContent)
); );
}); });
console.log(messageContent);
}
client.on("message", async (message) => {
if (message.author.bot) {
return;
}
const formattedMessage = message.content.toLowerCase().replace(/\s+/g, "");
if (formattedMessage.startsWith("dobe")) {
switch (formattedMessage) {
case "dobehelping":
sendHelpMessage(message);
break;
case "doberoundgen":
generateRound(message, false);
break;
case "doberoundgendm":
generateRound(message, true);
break;
case "dobescoring":
startScoring(message);
break;
case "dobetop":
showLeaderboard(message);
break;
case "dobehappy":
dontWorryBeHappy(message);
break;
case "dobeservers":
showServerNumber(message);
break;
case "dobeiss":
showIssLocation(message);
break;
default:
otherCommands(message);
}
} }
}); });
client client
.login(process.env.TOKEN) .login(process.env.TOKEN)
.then(() => console.log("Running!"))
.catch((error) => console.log(error)); .catch((error) => console.log(error));

3
bot/package.json

@ -12,7 +12,8 @@
"awscibo": "./awesomescibo.mjs" "awscibo": "./awesomescibo.mjs"
}, },
"scripts": { "scripts": {
"test": "node awesomescibo.mjs randomtoken" "test": "node awesomescibo.mjs randomtoken",
"start": "nodemon awesomescibo.mjs"
}, },
"keywords": [ "keywords": [
"discord", "discord",

1
bot/userScore/id

@ -1 +0,0 @@
0

2868
package-lock.json

File diff suppressed because it is too large

10
package.json

@ -0,0 +1,10 @@
{
"dependencies": {
"axios": "^0.21.1",
"dotenv": "^8.2.0",
"mongoose": "^5.12.4"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
Loading…
Cancel
Save