Add the refresh button
Some checks failed
Build and Publish / build_and_publish (push) Has been cancelled
Some checks failed
Build and Publish / build_and_publish (push) Has been cancelled
This commit is contained in:
parent
a8f5ae145a
commit
dbd06bfe38
1 changed files with 52 additions and 33 deletions
|
@ -2,6 +2,8 @@
|
||||||
This module is only meant to be loaded during election times.
|
This module is only meant to be loaded during election times.
|
||||||
"""
|
"""
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from calendar import c
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
import logging
|
import logging
|
||||||
import random
|
import random
|
||||||
import datetime
|
import datetime
|
||||||
|
@ -148,46 +150,63 @@ class ElectionCog(commands.Cog):
|
||||||
# ]
|
# ]
|
||||||
return results
|
return results
|
||||||
|
|
||||||
@commands.slash_command(name="election")
|
async def _get_embed(self) -> discord.Embed | None:
|
||||||
async def get_election_results(self, ctx: discord.ApplicationContext):
|
|
||||||
"""Gets the current election results"""
|
|
||||||
await ctx.defer()
|
|
||||||
async with httpx.AsyncClient(headers=self.HEADERS) as client:
|
async with httpx.AsyncClient(headers=self.HEADERS) as client:
|
||||||
response = await client.get(self.SOURCE, follow_redirects=True)
|
response = await client.get(self.SOURCE, follow_redirects=True)
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
return await ctx.respond(
|
raise RuntimeError(f"HTTP {response.status_code} while fetching results from BBC")
|
||||||
"Sorry, I can't do that right now (HTTP %d while fetching results from BBC)" % response.status_code
|
|
||||||
)
|
|
||||||
|
|
||||||
# noinspection PyTypeChecker
|
|
||||||
soup = await asyncio.to_thread(BeautifulSoup, response.text, "html.parser")
|
soup = await asyncio.to_thread(BeautifulSoup, response.text, "html.parser")
|
||||||
results = await self.bot.loop.run_in_executor(None, self.process_soup, soup)
|
results = await self.bot.loop.run_in_executor(None, self.process_soup, soup)
|
||||||
if results:
|
if results:
|
||||||
now = discord.utils.utcnow()
|
now = discord.utils.utcnow()
|
||||||
date = now.date().strftime("%B %Y")
|
date = now.date().strftime("%B %Y")
|
||||||
colour_scores = {}
|
colour_scores = {}
|
||||||
embed = discord.Embed(
|
embed = discord.Embed(
|
||||||
title="Election results - " + date,
|
title="Election results - " + date,
|
||||||
url="https://bbc.co.uk/",
|
url="https://bbc.co.uk/",
|
||||||
timestamp=now
|
timestamp=now
|
||||||
|
)
|
||||||
|
embed.set_footer(text="Source from bbc.co.uk.")
|
||||||
|
description_parts = []
|
||||||
|
|
||||||
|
for party_name, values in results.items():
|
||||||
|
councillors, net, colour = values
|
||||||
|
colour_scores[party_name] = councillors
|
||||||
|
symbol = "+" if net > 0 else ''
|
||||||
|
description_parts.append(
|
||||||
|
f"**{party_name}**: {symbol}{net:,} ({councillors:,} total)"
|
||||||
)
|
)
|
||||||
embed.set_footer(text="Source from bbc.co.uk.")
|
|
||||||
description_parts = []
|
|
||||||
|
|
||||||
for party_name, values in results.items():
|
top_party = list(sorted(colour_scores.keys(), key=lambda k: colour_scores[k], reverse=True))[0]
|
||||||
councillors, net, colour = values
|
embed.colour = discord.Colour(results[top_party][2])
|
||||||
colour_scores[party_name] = councillors
|
embed.description = "\n".join(description_parts)
|
||||||
symbol = "+" if net > 0 else ''
|
return embed
|
||||||
description_parts.append(
|
|
||||||
f"**{party_name}**: {symbol}{net:,} ({councillors:,} total)"
|
|
||||||
)
|
|
||||||
|
|
||||||
top_party = list(sorted(colour_scores.keys(), key=lambda k: colour_scores[k], reverse=True))[0]
|
@commands.slash_command(name="election")
|
||||||
embed.colour = discord.Colour(results[top_party][2])
|
async def get_election_results(self, ctx: discord.ApplicationContext):
|
||||||
embed.description = "\n".join(description_parts)
|
"""Gets the current election results"""
|
||||||
return await ctx.respond(embed=embed)
|
class RefreshView(discord.ui.View):
|
||||||
else:
|
@discord.ui.button(label="Refresh", style=discord.ButtonStyle.primary, emoji="\U0001f501")
|
||||||
return await ctx.respond("Unable to get election results at this time.")
|
async def refresh(_self, _btn, interaction):
|
||||||
|
await interaction.response.defer(invisible=True)
|
||||||
|
try:
|
||||||
|
embed = await self._get_embed()
|
||||||
|
except Exception as e:
|
||||||
|
self.log.exception("Failed to get election results.")
|
||||||
|
return await interaction.followup.send(f"Sorry, I cannot contact the BBC at this time: {e}")
|
||||||
|
if embed is None:
|
||||||
|
return await interaction.followup.send("Sorry, I could not find any election results.")
|
||||||
|
await interaction.edit_original_response(embed=embed)
|
||||||
|
|
||||||
|
await ctx.defer()
|
||||||
|
try:
|
||||||
|
embed = await self._get_embed()
|
||||||
|
except Exception as e:
|
||||||
|
self.log.exception("Failed to get election results.")
|
||||||
|
return await ctx.respond(f"Sorry, I cannot contact the BBC at this time: {e}")
|
||||||
|
if embed is None:
|
||||||
|
return await ctx.respond("Sorry, I could not find any election results.")
|
||||||
|
await ctx.respond(embed=embed, view=RefreshView())
|
||||||
|
|
||||||
|
|
||||||
def setup(bot):
|
def setup(bot):
|
||||||
|
|
Loading…
Reference in a new issue