2024-06-04 00:43:42 -04:00
|
|
|
import {REST, Routes, Client, GatewayIntentBits, CommandInteraction, EmbedBuilder, CommandInteractionOption, CommandInteractionOptionResolver } from "discord.js";
|
2024-06-01 02:14:08 -04:00
|
|
|
import * as fs from "node:fs";
|
|
|
|
import commands from "./commands.js";
|
|
|
|
import {MakePrediction} from "./predictor.js";
|
2024-06-04 00:43:42 -04:00
|
|
|
import Election from "./election.js";
|
2024-07-23 02:58:50 -04:00
|
|
|
import CandidateEmojis from "./candidateEmojis.js";
|
2024-06-04 00:43:42 -04:00
|
|
|
import Elections from "./elections/elections.js";
|
2024-06-18 22:57:55 -04:00
|
|
|
import VoteType from "./VoteType.js";
|
2024-06-01 02:14:08 -04:00
|
|
|
|
|
|
|
const configraw = fs.readFileSync("config.json", "utf-8");
|
|
|
|
const config = JSON.parse(configraw);
|
|
|
|
|
|
|
|
if (!config.token) {
|
|
|
|
console.error("Please provide a Token and Client ID in config.json");
|
|
|
|
process.exit(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
(async () => {
|
|
|
|
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
|
|
|
|
|
|
|
|
client.on('ready', async () => {
|
|
|
|
console.log(`Logged in as ${client.user!.tag}!`);
|
|
|
|
await publishSlashCommands(client.application!.id);
|
|
|
|
});
|
|
|
|
|
|
|
|
client.on('interactionCreate', async i => {
|
|
|
|
if (i instanceof CommandInteraction) {
|
2024-06-04 01:16:47 -04:00
|
|
|
await i.deferReply();
|
2024-06-01 02:14:08 -04:00
|
|
|
switch (i.commandName) {
|
2024-06-05 18:58:23 -04:00
|
|
|
case "approval":
|
2024-07-23 02:58:50 -04:00
|
|
|
// TODO: Replace this with API!
|
2024-06-05 18:58:23 -04:00
|
|
|
let poll_data = JSON.parse(fs.readFileSync('data/approval_rating.json', "utf-8"));
|
2024-06-03 15:02:57 -04:00
|
|
|
let polls = "";
|
2024-06-05 18:58:23 -04:00
|
|
|
var source = i.options.get('source')?.value as string
|
|
|
|
switch (source) {
|
|
|
|
case "thehill":
|
|
|
|
// source: https://elections2024.thehill.com/national/biden-approval-rating/
|
|
|
|
polls = `${poll_data.thehill.description}:\n\n`;
|
|
|
|
Object.keys(poll_data.thehill.polls).forEach(poll => {
|
|
|
|
polls += `:red_circle: **${poll_data.thehill.polls[poll].pollster}** - (**${poll_data.thehill.polls[poll].date}**), ${poll_data.thehill.polls[poll].sample}, **${poll_data.thehill.polls[poll].approve}**% approve, **${poll_data.thehill.polls[poll].disapprove}**% disapprove (**${poll_data.thehill.polls[poll].spread}**)\n`;
|
|
|
|
});
|
|
|
|
break;
|
|
|
|
case "fivethirtyeight":
|
|
|
|
// source: https://projects.fivethirtyeight.com/biden-approval-rating/
|
|
|
|
polls = `${poll_data.fivethirtyeight.description}:\n\n`;
|
|
|
|
Object.keys(poll_data.fivethirtyeight.polls).forEach(poll => {
|
|
|
|
polls += `:red_circle: **${poll_data.fivethirtyeight.polls[poll].pollster}** - (**${poll_data.fivethirtyeight.polls[poll].date}**), ${poll_data.fivethirtyeight.polls[poll].sample}, **${poll_data.fivethirtyeight.polls[poll].approve}**% approve, **${poll_data.fivethirtyeight.polls[poll].disapprove}**% disapprove (adjusted: **${poll_data.fivethirtyeight.polls[poll].approve_adjusted}**% approve, **${poll_data.fivethirtyeight.polls[poll].disapprove_adjusted}**% disapprove) (**${poll_data.fivethirtyeight.polls[poll].spread}**)\n`;
|
|
|
|
});
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
// source: https://www.realclearpolling.com/polls/approval/joe-biden/approval-rating
|
|
|
|
polls = `${poll_data.rcp.description}:\n\n`;
|
|
|
|
Object.keys(poll_data.rcp.polls).forEach(poll => {
|
|
|
|
polls += `:red_circle: **${poll_data.rcp.polls[poll].pollster}** - (**${poll_data.rcp.polls[poll].date}**), ${poll_data.rcp.polls[poll].sample}, **${poll_data.rcp.polls[poll].approve}**% approve, **${poll_data.rcp.polls[poll].disapprove}**% disapprove (spread: **${poll_data.rcp.polls[poll].spread}**)\n`;
|
|
|
|
});
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
await i.editReply(`${polls}`);
|
2024-06-03 15:02:57 -04:00
|
|
|
break;
|
2024-07-23 02:58:50 -04:00
|
|
|
|
|
|
|
case "test":
|
2024-07-23 17:24:05 -04:00
|
|
|
var country = i.options.get('country')?.value as string
|
|
|
|
var election_type = i.options.get('type')?.value as string
|
2024-07-23 02:58:50 -04:00
|
|
|
var year = Number(i.options.get('year')?.value)
|
2024-07-23 17:24:05 -04:00
|
|
|
let query = await fetch(`http://127.0.0.1:3000/api/v1/election/${country}/${election_type}/${year}`); // temp test url
|
2024-07-23 02:58:50 -04:00
|
|
|
let results = await query.json();
|
|
|
|
|
|
|
|
if (query.ok) {
|
|
|
|
if(results[year] != undefined) {
|
|
|
|
var embed = new EmbedBuilder()
|
|
|
|
.setTitle(` ${results[year][0].election_name}`)
|
|
|
|
.setDescription("API test")
|
|
|
|
.addFields(Object.values(results[year][0].candidates).map((candidate: any) => ({
|
|
|
|
name: `${candidate.winner ? ":white_check_mark:" : ""} ${CandidateEmojis[candidate.party] ?? ""} ${candidate.name} ${candidate.incumbent ? "(I)" : ""} (${candidate.party})`,
|
2024-07-23 17:55:44 -04:00
|
|
|
value: `${results[year][0].election_type === "electoral" ? `${candidate.electoral_votes} electoral votes\n` : ""} ${candidate.votes.toLocaleString()} votes (${candidate.percent}%)`,
|
2024-07-23 02:58:50 -04:00
|
|
|
inline: true
|
|
|
|
})))
|
|
|
|
.setTimestamp();
|
2024-07-23 17:47:14 -04:00
|
|
|
|
|
|
|
if(results[year][0].has_map === true) {
|
|
|
|
const map = await fetch(`http://127.0.0.1:3000/api/v1/election/${country}/${election_type}/${year}/map`); // temp test url
|
|
|
|
if (map.ok) {
|
|
|
|
const arrayBuffer = await map.arrayBuffer();
|
|
|
|
const buffer = Buffer.from(arrayBuffer);
|
|
|
|
embed.setImage("attachment://map.png");
|
|
|
|
await i.editReply({embeds: [embed], files: [{attachment: buffer, name: "map.png"}]});
|
|
|
|
break;
|
|
|
|
} else {
|
|
|
|
await i.editReply({embeds: [embed]});
|
|
|
|
break;
|
|
|
|
}
|
2024-07-23 17:24:05 -04:00
|
|
|
} else {
|
|
|
|
await i.editReply({embeds: [embed]});
|
|
|
|
break;
|
|
|
|
}
|
2024-07-23 02:58:50 -04:00
|
|
|
} else {
|
|
|
|
await i.editReply("Election not found");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
await i.editReply("An error occurred fetching the data");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
|
2024-06-01 02:14:08 -04:00
|
|
|
case "simulate":
|
2024-06-04 00:43:42 -04:00
|
|
|
var electionname = (i.options as CommandInteractionOptionResolver).getSubcommand();
|
2024-06-03 15:02:57 -04:00
|
|
|
|
2024-06-04 00:43:42 -04:00
|
|
|
var election = structuredClone(Elections[electionname]);
|
|
|
|
for (const candidate of election.candidates) {
|
|
|
|
var option = (i.options as CommandInteractionOptionResolver).getString(candidate.party.toLowerCase().replace(/ /g, "_") + "_candidate");
|
|
|
|
if (option) {
|
|
|
|
candidate.name = option;
|
|
|
|
}
|
|
|
|
var bias = (i.options as CommandInteractionOptionResolver).getNumber(candidate.party.toLowerCase().replace(/ /g, "_") + "_bias");
|
|
|
|
if (bias) {
|
|
|
|
for (const state of Object.keys(election.states)) {
|
|
|
|
election.states[state].odds[candidate.party] += bias;
|
2024-06-03 15:02:57 -04:00
|
|
|
}
|
2024-06-04 00:43:42 -04:00
|
|
|
}
|
2024-06-03 15:02:57 -04:00
|
|
|
}
|
2024-06-04 00:43:42 -04:00
|
|
|
|
|
|
|
var newcandidate = (i.options as CommandInteractionOptionResolver).getString("add_candidate");
|
|
|
|
if (newcandidate) {
|
|
|
|
var party = (i.options as CommandInteractionOptionResolver).getString("with_party") || "Independent";
|
|
|
|
var color = (i.options as CommandInteractionOptionResolver).getString("with_color") || "#bfab22";
|
|
|
|
var odds = (i.options as CommandInteractionOptionResolver).getNumber("with_odds") || 0.33;
|
|
|
|
if (!/^#[0-9A-Fa-f]{3,6}$/.test(color)) {
|
2024-06-04 01:16:47 -04:00
|
|
|
await i.editReply("Please provide a valid hex color code");
|
2024-06-04 00:43:42 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (election.candidates.some(c => c.party === party || c.name === newcandidate)) {
|
2024-06-04 01:16:47 -04:00
|
|
|
await i.editReply("A candidate with that name or party already exists");
|
2024-06-04 00:43:42 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
election.candidates.push({
|
|
|
|
name: newcandidate,
|
|
|
|
party: party,
|
|
|
|
color: color
|
|
|
|
});
|
|
|
|
for (const state of Object.keys(election.states))
|
|
|
|
election.states[state].odds[party] = odds;
|
|
|
|
}
|
|
|
|
var result = await MakePrediction(election);
|
|
|
|
var embed = new EmbedBuilder()
|
|
|
|
.setTitle(election.title)
|
|
|
|
.setDescription(election.description.replace("$WINNER", result.winner))
|
|
|
|
.addFields(result.candidates.map(c => {
|
|
|
|
return {
|
|
|
|
name: `${(result.winner === c.name ? ":white_check_mark:" : "")} ${c.name} (${c.party})`,
|
2024-07-23 02:58:50 -04:00
|
|
|
value: `${election.voteType === VoteType.Electoral ? `${c.electoralVotes} electoral votes\n` : ""}${c.votes} votes (${((c.votes / result.totalVotes) * 100).toFixed(2)}%)`,
|
2024-06-04 00:43:42 -04:00
|
|
|
inline: true
|
|
|
|
}
|
|
|
|
}))
|
|
|
|
.setImage("attachment://election.png")
|
|
|
|
.setTimestamp();
|
2024-06-04 01:16:47 -04:00
|
|
|
await i.editReply({embeds: [embed], files: [{attachment: result.png, name: "election.png"}]});
|
2024-06-01 02:14:08 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
client.login(config.token);
|
|
|
|
})();
|
|
|
|
|
|
|
|
async function publishSlashCommands(clientid : string) {
|
|
|
|
const rest = new REST({ version: '10' }).setToken(config.token);
|
|
|
|
await rest.put(Routes.applicationCommands(clientid), {body: commands});
|
|
|
|
console.log("Successfully registered slash commands");
|
|
|
|
}
|