rHomelab / LabBot-Cogs

Cogs for the Red-based Homelab Discord server bot.
GNU General Public License v3.0
36 stars 14 forks source link

[FEAT] Is it Read-Only Friday check #275

Closed MrMrRubic closed 3 months ago

MrMrRubic commented 3 months ago

Overview

A command which returns wether it's readonly friday or not using isitreadonlyfriday's API

Commands

[p]isitreadonlyfriday [UTC offset]

DoD

Stretch

MrMrRubic commented 3 months ago

I basically copied xkcd.py and modified it to something that might work, though i don't have the setup to test it properly. That's also how i discovered issue #274.

import aiohttp
import discord
from redbot.core import commands

async def fetch_get(url_in: str) -> dict:
    """Make web requests"""
    async with aiohttp.request("GET", url_in) as response:
        if response.status != 200:
            return {}
        return await response.json()

class IsItReadOnlyFriday(commands.Cog):
    """IsItReadOnlyFriday Cog"""

    def __init__(self):
        pass

    @commands.command()
    async def isitreadonlyfriday(self, ctx: commands.Context, offset: int = 0):
        """Returns isitreadonlyfriday readonly of given offset, otherwise return UTC."""

        if not offset:
            # No offset specified, get UTC
            url = "https://isitreadonlyfriday.com/api/isitreadonlyfriday/"
        else:
            url = f"https://isitreadonlyfriday.com/api/isitreadonlyfriday/{offset}"

        # Get readonly data from isitreadonlyfriday api
        readonly_json = await fetch_get(url)

        # If the response isn't 200 throw an error
        if not readonly_json:
            embed = await self.make_error_embed(ctx, "404")
            await ctx.send(embed=embed)
            return

        embed = await self.make_readonly_embed(ctx, readonly_json)
        await ctx.send(embed=embed)

    async def make_readonly_embed(self, ctx: commands.Context, data: dict) -> discord.Embed:
        """Generate embed for isitreadonlyfriday readonly"""
        if not data["readonly"] == true:
            isitreadonlyfriday_embed = discord.Embed(
                title=f"Is It Read-Only Friday?",
                description=f"No! Change away!",
                colour=await ctx.embed_colour()
            )
        else
            isitreadonlyfriday_embed = discord.Embed(
                title=f"Is It Read-Only Friday?",
                description=f"Yes! Don't change anything!",
                colour=await ctx.embed_colour()
            )
        return isitreadonlyfriday_embed

    async def make_error_embed(self, ctx: commands.Context, error_type: str) -> discord.Embed:
        """Generate error message embeds"""
        error_msgs = {"404": "readonly not found"}
        return discord.Embed(
            title="Error",
            description=error_msgs[error_type],
            colour=await ctx.embed_colour(),
        )

I highly doubt this is actually usable though, which is why i'm not bold enough to issue a pull request.