Created
November 5, 2020 05:50
-
-
Save shepgoba/d8d7cb2f784da0cdd70a39ea1849c526 to your computer and use it in GitHub Desktop.
Election Bot for US 2020 election (late af)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import discord | |
import requests | |
import asyncio | |
from datetime import datetime | |
# bot token | |
TOKEN = "<your token>" | |
# desired post channel id | |
CHANNEL_ID = 0 | |
# how often should we kill the api server | |
POLLING_RATE = 10.0 | |
class ElectionBotClient(discord.Client): | |
trump_latest = 0 | |
biden_latest = 0 | |
async def on_ready(self): | |
print('Logged in as') | |
print(self.user.name) | |
print(self.user.id) | |
print('------') | |
self.get_initial_electoral_votes() | |
self.bg_task = self.loop.create_task(self.polling_task()) | |
def get_initial_electoral_votes(self): | |
data = self.get_election_data() | |
for entry in data: | |
candidate_name = entry["candidate"] | |
electoral_votes = int(entry["electoral"]) | |
if candidate_name == "Joe Biden": | |
self.biden_latest = electoral_votes | |
elif candidate_name == "Donald Trump": | |
self.trump_latest = electoral_votes | |
def get_election_data(self) -> dict: | |
result = requests.get("https://election.krit.me/results.json") | |
return result.json() | |
def print_status(self): | |
now = datetime.now() | |
date_string = now.strftime("%m/%d/%Y %H:%M:%S") | |
print("[%s] Biden: %i, Trump: %i" % (date_string, self.biden_latest, self.trump_latest)) | |
async def polling_task(self): | |
await self.wait_until_ready() | |
counter = 0 | |
channel = self.get_channel(CHANNEL_ID) # channel ID goes here | |
while not self.is_closed(): | |
counter += 1 | |
await self.check_results(self.get_election_data()) | |
self.print_status() | |
await asyncio.sleep(POLLING_RATE) | |
async def check_results(self, data): | |
for entry in data: | |
candidate_name = entry["candidate"] | |
electoral_votes = int(entry["electoral"]) | |
if candidate_name == "Joe Biden": | |
if electoral_votes != self.biden_latest: | |
general_channel = self.get_channel(CHANNEL_ID) | |
await general_channel.send("@everyone Biden now has %i electoral votes (previously %i)" % (electoral_votes, self.biden_latest)) | |
self.biden_latest = electoral_votes | |
elif candidate_name == "Donald Trump": | |
if electoral_votes != self.trump_latest: | |
general_channel = self.get_channel(CHANNEL_ID) | |
await general_channel.send("@everyone Trump now has %i electoral votes (previously %i)" % (electoral_votes, self.trump_latest)) | |
self.trump_latest = electoral_votes | |
client = ElectionBotClient() | |
client.run(TOKEN) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment