0
0
Fork 0

Move everything for the server in to a server folder to make room for the site

This commit is contained in:
Oliver-Akins 2021-09-24 22:58:23 -06:00
parent 6a45152d8f
commit 33ca09808e
26 changed files with 8 additions and 6 deletions

View file

@ -0,0 +1,151 @@
import { Request, ResponseToolkit } from "@hapi/hapi";
import { loadHistory, saveHistory } from "@/utils/data";
import { getQuote } from "@/utils/quotes";
import { db, config } from "@/main";
import { BRACKET_DATA, DISCORD_API_URI } from "@/constants";
import axios from "axios";
import { deleteVoteButton } from "@/utils/components/buttons/delete_vote";
import { showUserVoteButton } from "@/utils/components/buttons/my_vote";
import { viewDBButton } from "@/utils/components/buttons/view_db";
import { countVotesButton } from "@/utils/components/buttons/count_votes";
export default {
method: `POST`, path: `/{guild_id}/bracket`,
async handler(request: Request, h: ResponseToolkit) {
let { guild_id: gID } = request.params;
let wh = db[gID].webhook;
function generateFieldTitle(index: number, quote: quote): string {
// Change the name based on if the quote won or not
if (quote.win_streak > 0) {
let name = `👑 Quote ${index + 1}:`;
// Add the win streak information if desired
if ((config.guilds[gID].show_win_streak ?? true)
&& quote.win_streak > 0) {
name += ` (Streak: ${quote.win_streak})`;
};
return name;
}
else {
return `Quote ${index + 1}:`;
};
};
// Create the very first quote bracket
let quotes: quote[];
if (!db[gID].bracket.msg) {
quotes = await getQuote(gID, config.guilds[gID].quote_max);
} else {
await request.server.inject({
method: `DELETE`,
url: `/${gID}/bracket/${config.guilds[gID].delete_mode}`,
auth: request.auth,
});
let pastBrackets = await loadHistory(gID);
pastBrackets.push(db[gID].bracket.quotes);
saveHistory(gID, pastBrackets);
// Calculate the winners from the previous bracket
let r = await request.server.inject({
url: `/${gID}/bracket/winners?finalize=true`,
auth: request.auth,
});
let data = JSON.parse(r.payload);
var winner_count = data.count;
// Check if we are getting rid of all winners
if (data.eliminate_all) {
quotes = [];
winner_count = 0;
} else {
quotes = data.winners;
};
// Get enough quotes to meet the maximum for the guild
let new_quotes = await getQuote(
gID,
config.guilds[gID].quote_max - quotes.length
);
quotes.push(...new_quotes);
};
// Setup the database for the new bracket
db[gID].bracket = JSON.parse(JSON.stringify(BRACKET_DATA));
db[gID].bracket.quotes = quotes;
let message = {
content: `New Quote Bracket!`,
embeds: [
{
description: `Note: If **more than ${Math.floor(config.guilds[gID].quote_max / 2)}** of the quotes tie, they will all be eliminated, otherwise, the ones that tie will move on to the next bracket.`,
fields: quotes.map((quote, i) => { return {
name: generateFieldTitle(i, quote),
value: quote.text,
}}),
}
],
components: [
{
type: 1,
components: [
{
type: 3,
custom_id: `quote`,
placeholder: `Choose Your Favourite Quote`,
options: quotes.map((_, i) => {
return {
label: `Quote ${i + 1}`,
value: i,
emoji: i < winner_count ? {
name: `👑`
} : null
}
}),
}
]
},
{
type: 1,
components: [
showUserVoteButton,
deleteVoteButton,
],
}
]
};
//---------------------------------
// Add the extra buttons as desired
let extra_buttons = config.guilds[gID].extra_buttons ?? [];
if (extra_buttons.length > 0) {
let actionRow: action_row = {
type: 1,
components: [],
};
if (extra_buttons.includes(`DB`)) {
actionRow.components.push(viewDBButton);
};
if (extra_buttons.includes(`voteCount`)) {
actionRow.components.push(countVotesButton);
};
message.components.push(actionRow);
};
let url = `${DISCORD_API_URI}/webhooks/${wh.id}/${wh.token}`;
let r = await axios.post(url, message, { params: { wait: true } });
db[gID].bracket.msg = r.data.id;
db[gID].bracket.channel = r.data.channel_id;
return h.response(r.data).code(r.status);
},
}

View file

@ -0,0 +1,18 @@
import { DISCORD_API_URI } from "@/constants";
import { db } from "@/main";
import { Request, ResponseToolkit } from "@hapi/hapi";
import axios from "axios";
export default {
method: `DELETE`, path: `/{guild_id}/bracket/delete_message`,
async handler(request: Request, h: ResponseToolkit) {
let { guild_id: gID } = request.params;
let wh = db[gID].webhook;
let r = await axios.delete(
`${DISCORD_API_URI}/webhooks/${wh.id}/${wh.token}/messages/${db[gID].bracket.msg}`
);
return h.response(r.data).code(r.status);
},
}

View file

@ -0,0 +1,19 @@
import { Request, ResponseToolkit } from "@hapi/hapi";
import { DISCORD_API_URI } from "@/constants";
import { db } from "@/main";
import axios from "axios";
export default {
method: `DELETE`, path: `/{guild_id}/bracket/remove_components`,
async handler(request: Request, h: ResponseToolkit) {
let { guild_id: gID } = request.params;
let wh = db[gID].webhook;
let r = await axios.patch(
`${DISCORD_API_URI}/webhooks/${wh.id}/${wh.token}/messages/${db[gID].bracket.msg}`,
{ components: [] }
);
return h.response(r.data).code(r.status);
},
}

View file

@ -0,0 +1,95 @@
import { Request, ResponseToolkit } from "@hapi/hapi";
import { DISCORD_API_URI } from "@/constants";
import { config, db } from "@/main";
import axios from "axios";
export default {
method: `GET`, path: `/{guild_id}/bracket/isTied`,
async handler(request: Request, h: ResponseToolkit) {
let { guild_id: gID } = request.params;
let thread_behaviour = config.guilds[gID].tie_reminder;
let r = await request.server.inject({
url: `/${gID}/bracket/winners`,
auth: request.auth,
});
let data = JSON.parse(r.payload);
if (data.count >= 2) {
let bracket = db[gID].bracket;
// Construct the primary body of the message
let content = `The bracket currently has a tie between:\n> `;
content += data.winners
.map((q:quote) => q.text)
.join('\n~~------------------------------------~~\n> ');
// Alert users if all will be eliminated or not
if (data.eliminate_all) {
content += `\n\n**If the tie remains, all quotes will be eliminated**`;
} else {
content += `\n\n**All of these quotes will advance if the tie isn't broken.**`;
};
// Define the query params that are needed all the time
let params: execute_webhook_query_params = { wait: true };
// Check if the user is wanting to use a thread notification
if ((thread_behaviour !== "channel") && config.guilds[gID].bot_token) {
try {
await axios.get(
`${DISCORD_API_URI}/channels/${bracket.msg}`,
{
headers: {
Authorization: `Bot ${config.guilds[gID].bot_token}`
}
}
);
params.thread_id = bracket.msg;
} catch (err) {
try {
await axios.post(
`${DISCORD_API_URI}/channels/${bracket.channel}/messages/${bracket.msg}/threads`,
{
name: config.guilds[gID].thread_name ?? `Quote Bracket Discussion`,
auto_archive_duration: 1440,
},
{
headers: {
Authorization: `Bot ${config.guilds[gID].bot_token}`
}
}
).then(response => {
params.thread_id = bracket.msg
});
} catch (err) {};
};
};
// Add link if we know what channel the message was posted in
if (db[gID].bracket.channel) {
switch (thread_behaviour) {
case "channel":
case "thread":
content += `\n\n[Jump To Bracket](https://discord.com/channels/${gID}/${bracket.channel}/${bracket.msg})`;
break;
case "thread_no_jump_link":
if (!params.thread_id) {
content += `\n\n[Jump To Bracket](https://discord.com/channels/${gID}/${bracket.channel}/${bracket.msg})`;
};
break;
};
};
let wh = db[gID].webhook;
let r = await axios.post(
`${DISCORD_API_URI}/webhooks/${wh.id}/${wh.token}`,
{ content },
{ params }
);
return h.response(r.data).code(r.status);
};
return h.response({ result: `No Tie` }).code(200);
},
}

View file

@ -0,0 +1,33 @@
import { Request, ResponseToolkit } from "@hapi/hapi";
import { DISCORD_API_URI } from "@/constants";
import { config, db } from "@/main";
import axios from "axios";
export default {
method: `GET`, path: `/{guild_id}/bracket`,
async handler(request: Request, h: ResponseToolkit) {
let { guild_id: gID } = request.params;
let { convert_ids } = request.query;
// See if we are adding the user's conversion table to the response
let users: {[index: string]: string} = {};
if (convert_ids?.toLowerCase() === `true` && config.guilds[gID].bot_token) {
for (var k in db[gID].bracket.users) {
let r = await axios.get(
`${DISCORD_API_URI}/users/${k}`,
{
headers: {
Authorization: `Bot ${config.guilds[gID].bot_token}`
}
}
);
users[k] = `${r.data.username}#${r.data.discriminator}`
};
};
return h.response({
db: db[gID].bracket,
user_id_mapping: users,
});
},
}

View file

@ -0,0 +1,50 @@
import { Request, ResponseToolkit, ServerRoute } from "@hapi/hapi";
import { config, db } from "@/main";
import Joi from "joi";
const route: ServerRoute = {
method: `GET`, path: `/{guild_id}/bracket/winners`,
options: {
validate: {
query: Joi.object({
finalize: Joi.boolean().optional().default(false),
}),
},
},
async handler(request: Request, h: ResponseToolkit) {
let gID = request.params.guild_id;
let data = db[gID].bracket;
let { finalize } = request.query;
let winners: quote[] = [];
let highest = -1;
// Run through all of the quotes to find the most voted for ones
for (var quote of data.quotes) {
// New maximum, remove all previous winners
if (quote.votes > highest) {
winners = [ quote ];
highest = quote.votes;
}
else if (quote.votes === highest) {
winners.push( quote );
};
// Reset the bracket data as needed
if (finalize) {
quote.win_streak++;
quote.votes = 0;
};
};
let count = winners.length;
return h.response({
winners,
count,
eliminate_all: count > Math.floor(config.guilds[gID].quote_max / 2),
}).code(200);
},
};
export default route;