diff options
Diffstat (limited to 'bot/exts')
-rw-r--r-- | bot/exts/fun/latex.py | 41 | ||||
-rw-r--r-- | bot/exts/fun/uwu.py | 2 | ||||
-rw-r--r-- | bot/exts/holidays/pride/pride_facts.py | 67 | ||||
-rw-r--r-- | bot/exts/utilities/colour.py | 2 | ||||
-rw-r--r-- | bot/exts/utilities/epoch.py | 2 | ||||
-rw-r--r-- | bot/exts/utilities/reddit.py | 2 |
6 files changed, 55 insertions, 61 deletions
diff --git a/bot/exts/fun/latex.py b/bot/exts/fun/latex.py index 12f2d0b6..b7bd708e 100644 --- a/bot/exts/fun/latex.py +++ b/bot/exts/fun/latex.py @@ -9,7 +9,7 @@ from typing import BinaryIO import discord from PIL import Image -from aiohttp import web +from aiohttp import client_exceptions, web from discord.ext import commands from bot.bot import Bot @@ -72,6 +72,11 @@ class InvalidLatexError(Exception): self.logs = logs +class LatexServerError(Exception): + """Represents an error raised from Latex rendering server.""" + + + class Latex(commands.Cog): """Renders latex.""" @@ -81,8 +86,11 @@ class Latex(commands.Cog): async def _generate_image(self, query: str, out_file: BinaryIO) -> None: """Make an API request and save the generated image to cache.""" payload = {"code": query, "format": "png"} - async with self.bot.http_session.post(LATEX_API_URL, data=payload, raise_for_status=True) as response: - response_json = await response.json() + try: + async with self.bot.http_session.post(LATEX_API_URL, data=payload, raise_for_status=True) as response: + response_json = await response.json() + except client_exceptions.ClientResponseError: + raise LatexServerError if response_json["status"] != "success": raise InvalidLatexError(logs=response_json.get("log")) async with self.bot.http_session.get( @@ -105,6 +113,21 @@ class Latex(commands.Cog): except web.HTTPClientError as e: log.info("Error when uploading latex output to pastebin. %s", e) + async def _prepare_error_embed(self, err: InvalidLatexError | LatexServerError | None) -> discord.Embed: + title = "Server encountered an issue, please retry later." + if isinstance(err, InvalidLatexError): + title = "Failed to render input." + + embed = discord.Embed(title=title) + embed.description = "No logs available." + logs = getattr(err, "logs", None) + if logs: + logs_paste_url = await self._upload_to_pastebin(logs) + embed.description = "Couldn't upload logs." + if logs_paste_url: + embed.description = f"[View Logs]({logs_paste_url})" + return embed + @commands.command() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @whitelist_override(channels=LATEX_ALLOWED_CHANNNELS) @@ -120,16 +143,8 @@ class Latex(commands.Cog): try: with open(image_path, "wb") as out_file: await self._generate_image(TEMPLATE.substitute(text=query), out_file) - except InvalidLatexError as err: - embed = discord.Embed(title="Failed to render input.") - if err.logs is None: - embed.description = "No logs available." - else: - logs_paste_url = await self._upload_to_pastebin(err.logs) - if logs_paste_url: - embed.description = f"[View Logs]({logs_paste_url})" - else: - embed.description = "Couldn't upload logs." + except (InvalidLatexError, LatexServerError) as err: + embed = await self._prepare_error_embed(err) await ctx.send(embed=embed) image_path.unlink() return diff --git a/bot/exts/fun/uwu.py b/bot/exts/fun/uwu.py index 488c68f3..f548d24b 100644 --- a/bot/exts/fun/uwu.py +++ b/bot/exts/fun/uwu.py @@ -30,7 +30,7 @@ EMOJIS = [ "o.O", "-.-", ">w<", - "σωσ", # noqa: RUF001 + "σωσ", "òωó", "ʘwʘ", ":3", diff --git a/bot/exts/holidays/pride/pride_facts.py b/bot/exts/holidays/pride/pride_facts.py index f3ce50a9..3d52a3c7 100644 --- a/bot/exts/holidays/pride/pride_facts.py +++ b/bot/exts/holidays/pride/pride_facts.py @@ -4,7 +4,6 @@ import random from datetime import UTC, datetime from pathlib import Path -import dateutil.parser import discord from discord.ext import commands @@ -28,65 +27,45 @@ class PrideFacts(commands.Cog): async def send_pride_fact_daily(self) -> None: """Background task to post the daily pride fact every day.""" channel = self.bot.get_channel(Channels.sir_lancebot_playground) - await self.send_select_fact(channel, datetime.now(tz=UTC)) + await self.send_select_fact(channel, datetime.now(tz=UTC).day) - async def send_random_fact(self, ctx: commands.Context) -> None: - """Provides a fact from any previous day, or today.""" - now = datetime.now(tz=UTC) - previous_years_facts = (y for x, y in FACTS.items() if int(x) < now.year) - current_year_facts = FACTS.get(str(now.year), [])[:now.day] - previous_facts = current_year_facts + [x for y in previous_years_facts for x in y] + async def send_select_fact(self, target: discord.abc.Messageable, day_num: int) -> None: + """Provides the fact for the specified day.""" try: - await ctx.send(embed=self.make_embed(random.choice(previous_facts))) + await target.send(embed=self.get_fact_embed(day_num)) except IndexError: - await ctx.send("No facts available") - - async def send_select_fact(self, target: discord.abc.Messageable, _date: str | datetime) -> None: - """Provides the fact for the specified day, if the day is today, or is in the past.""" - now = datetime.now(tz=UTC) - if isinstance(_date, str): - try: - date = dateutil.parser.parse(_date, dayfirst=False, yearfirst=False, fuzzy=True) - except (ValueError, OverflowError) as err: - await target.send(f"Error parsing date: {err}") - return - else: - date = _date - if date.year < now.year or (date.year == now.year and date.day <= now.day): - try: - await target.send(embed=self.make_embed(FACTS[str(date.year)][date.day - 1])) - except KeyError: - await target.send(f"The year {date.year} is not yet supported") - return - except IndexError: - await target.send(f"Day {date.day} of {date.year} is not yet support") - return - else: - await target.send("The fact for the selected day is not yet available.") + await target.send(f"Day {day_num} is not supported") + return @commands.command(name="pridefact", aliases=("pridefacts",)) - async def pridefact(self, ctx: commands.Context, option: str = None) -> None: + async def pridefact(self, ctx: commands.Context, option: int | str = None) -> None: """ Sends a message with a pride fact of the day. - If "random" is given as an argument, a random previous fact will be provided. - - If a date is given as an argument, and the date is in the past, the fact from that day - will be provided. + "option" is an optional setting, which has two has two accepted values: + - "random": a random previous fact will be provided. + - If a option is a number (1-30), the fact for that given day of June is returned. """ if not option: - await self.send_select_fact(ctx, datetime.now(tz=UTC)) + await self.send_select_fact(ctx, datetime.now(tz=UTC).day) + elif isinstance(option, int): + await self.send_select_fact(ctx, option) elif option.lower().startswith("rand"): - await self.send_random_fact(ctx) + await ctx.send(embed=self.get_fact_embed()) else: - await self.send_select_fact(ctx, option) + await ctx.send(f"Could not parse option {option}") @staticmethod - def make_embed(fact: str) -> discord.Embed: - """Makes a nice embed for the fact to be sent.""" + def get_fact_embed(day_num: int | None=None) -> discord.Embed: + """ + Makes a embed for the fact on the given day_num to be sent. + + if day_num is not set, a random fact is selected. + """ + fact = FACTS[day_num-1] if day_num else random.choice(FACTS) return discord.Embed( colour=Colours.pink, - title="Pride Fact!", + title=f"Day {day_num}'s pride fact!" if day_num else "Random pride fact!", description=fact ) diff --git a/bot/exts/utilities/colour.py b/bot/exts/utilities/colour.py index b8f1d62d..95f9ac22 100644 --- a/bot/exts/utilities/colour.py +++ b/bot/exts/utilities/colour.py @@ -182,7 +182,7 @@ class Colour(commands.Cog): hex_tuple = ImageColor.getrgb(f"#{hex_colour}") await self.send_colour_response(ctx, hex_tuple) - def get_colour_conversions(self, rgb: tuple[int, int, int]) -> dict[str, str]: + def get_colour_conversions(self, rgb: tuple[int, int, int]) -> dict[str, tuple[int, ...] | str]: """Create a dictionary mapping of colour types and their values.""" colour_name = self._rgb_to_name(rgb) if colour_name is None: diff --git a/bot/exts/utilities/epoch.py b/bot/exts/utilities/epoch.py index d1ba98bb..1f65b935 100644 --- a/bot/exts/utilities/epoch.py +++ b/bot/exts/utilities/epoch.py @@ -118,7 +118,7 @@ class TimestampMenuView(discord.ui.View): self.dropdown.add_option(label=label, description=date_time) @discord.ui.select(placeholder="Select the format of your timestamp") - async def select_format(self, interaction: discord.Interaction, _: discord.ui.Select) -> discord.Message: + async def select_format(self, interaction: discord.Interaction, _: discord.ui.Select) -> None: """Drop down menu which contains a list of formats which discord timestamps can take.""" selected = interaction.data["values"][0] if selected == "Epoch": diff --git a/bot/exts/utilities/reddit.py b/bot/exts/utilities/reddit.py index f8e358de..cfc70d85 100644 --- a/bot/exts/utilities/reddit.py +++ b/bot/exts/utilities/reddit.py @@ -37,7 +37,7 @@ class Reddit(Cog): self.access_token = None self.client_auth = BasicAuth(RedditConfig.client_id.get_secret_value(), RedditConfig.secret.get_secret_value()) - self.auto_poster_loop.start() + # self.auto_poster_loop.start() async def cog_unload(self) -> None: """Stop the loop task and revoke the access token when the cog is unloaded.""" |