diff options
Diffstat (limited to 'bot/exts/easter')
| -rw-r--r-- | bot/exts/easter/april_fools_vids.py | 36 | ||||
| -rw-r--r-- | bot/exts/easter/avatar_easterifier.py | 128 | ||||
| -rw-r--r-- | bot/exts/easter/bunny_name_generator.py | 42 | ||||
| -rw-r--r-- | bot/exts/easter/earth_photos.py | 66 | ||||
| -rw-r--r-- | bot/exts/easter/easter_riddle.py | 30 | ||||
| -rw-r--r-- | bot/exts/easter/egg_decorating.py | 33 | ||||
| -rw-r--r-- | bot/exts/easter/egg_facts.py | 22 | ||||
| -rw-r--r-- | bot/exts/easter/egghead_quiz.py | 31 | ||||
| -rw-r--r-- | bot/exts/easter/save_the_planet.py | 16 | ||||
| -rw-r--r-- | bot/exts/easter/traditions.py | 16 | 
10 files changed, 176 insertions, 244 deletions
diff --git a/bot/exts/easter/april_fools_vids.py b/bot/exts/easter/april_fools_vids.py index efe7e677..5ef40704 100644 --- a/bot/exts/easter/april_fools_vids.py +++ b/bot/exts/easter/april_fools_vids.py @@ -1,38 +1,30 @@  import logging  import random -from json import load +from json import loads  from pathlib import Path  from discord.ext import commands +from bot.bot import Bot +  log = logging.getLogger(__name__) +ALL_VIDS = loads(Path("bot/resources/easter/april_fools_vids.json").read_text("utf-8")) +  class AprilFoolVideos(commands.Cog):      """A cog for April Fools' that gets a random April Fools' video from Youtube.""" -    def __init__(self, bot: commands.Bot): -        self.bot = bot -        self.yt_vids = self.load_json() -        self.youtubers = ['google']  # will add more in future - -    @staticmethod -    def load_json() -> dict: -        """A function to load JSON data.""" -        p = Path('bot/resources/easter/april_fools_vids.json') -        with p.open(encoding="utf-8") as json_file: -            all_vids = load(json_file) -        return all_vids - -    @commands.command(name='fool') +    @commands.command(name="fool")      async def april_fools(self, ctx: commands.Context) -> None:          """Get a random April Fools' video from Youtube.""" -        random_youtuber = random.choice(self.youtubers) -        category = self.yt_vids[random_youtuber] -        random_vid = random.choice(category) -        await ctx.send(f"Check out this April Fools' video by {random_youtuber}.\n\n{random_vid['link']}") +        video = random.choice(ALL_VIDS) + +        channel, url = video["channel"], video["url"] + +        await ctx.send(f"Check out this April Fools' video by {channel}.\n\n{url}") -def setup(bot: commands.Bot) -> None: -    """April Fools' Cog load.""" -    bot.add_cog(AprilFoolVideos(bot)) +def setup(bot: Bot) -> None: +    """Load the April Fools' Cog.""" +    bot.add_cog(AprilFoolVideos()) diff --git a/bot/exts/easter/avatar_easterifier.py b/bot/exts/easter/avatar_easterifier.py deleted file mode 100644 index 8e8a3500..00000000 --- a/bot/exts/easter/avatar_easterifier.py +++ /dev/null @@ -1,128 +0,0 @@ -import asyncio -import logging -from io import BytesIO -from pathlib import Path -from typing import Tuple, Union - -import discord -from PIL import Image -from PIL.ImageOps import posterize -from discord.ext import commands - -log = logging.getLogger(__name__) - -COLOURS = [ -    (255, 247, 0), (255, 255, 224), (0, 255, 127), (189, 252, 201), (255, 192, 203), -    (255, 160, 122), (181, 115, 220), (221, 160, 221), (200, 162, 200), (238, 130, 238), -    (135, 206, 235), (0, 204, 204), (64, 224, 208) -]  # Pastel colours - Easter-like - - -class AvatarEasterifier(commands.Cog): -    """Put an Easter spin on your avatar or image!""" - -    def __init__(self, bot: commands.Bot): -        self.bot = bot - -    @staticmethod -    def closest(x: Tuple[int, int, int]) -> Tuple[int, int, int]: -        """ -        Finds the closest easter colour to a given pixel. - -        Returns a merge between the original colour and the closest colour -        """ -        r1, g1, b1 = x - -        def distance(point: Tuple[int, int, int]) -> Tuple[int, int, int]: -            """Finds the difference between a pastel colour and the original pixel colour.""" -            r2, g2, b2 = point -            return ((r1 - r2)**2 + (g1 - g2)**2 + (b1 - b2)**2) - -        closest_colours = sorted(COLOURS, key=lambda point: distance(point)) -        r2, g2, b2 = closest_colours[0] -        r = (r1 + r2) // 2 -        g = (g1 + g2) // 2 -        b = (b1 + b2) // 2 - -        return (r, g, b) - -    @commands.command(pass_context=True, aliases=["easterify"]) -    async def avatareasterify(self, ctx: commands.Context, *colours: Union[discord.Colour, str]) -> None: -        """ -        This "Easterifies" the user's avatar. - -        Given colours will produce a personalised egg in the corner, similar to the egg_decorate command. -        If colours are not given, a nice little chocolate bunny will sit in the corner. -        Colours are split by spaces, unless you wrap the colour name in double quotes. -        Discord colour names, HTML colour names, XKCD colour names and hex values are accepted. -        """ -        async def send(*args, **kwargs) -> str: -            """ -            This replaces the original ctx.send. - -            When invoking the egg decorating command, the egg itself doesn't print to to the channel. -            Returns the message content so that if any errors occur, the error message can be output. -            """ -            if args: -                return args[0] - -        async with ctx.typing(): - -            # Grabs image of avatar -            image_bytes = await ctx.author.avatar_url_as(size=256).read() - -            old = Image.open(BytesIO(image_bytes)) -            old = old.convert("RGBA") - -            # Grabs alpha channel since posterize can't be used with an RGBA image. -            alpha = old.getchannel("A").getdata() -            old = old.convert("RGB") -            old = posterize(old, 6) - -            data = old.getdata() -            setted_data = set(data) -            new_d = {} - -            for x in setted_data: -                new_d[x] = self.closest(x) -                await asyncio.sleep(0)  # Ensures discord doesn't break in the background. -            new_data = [(*new_d[x], alpha[i]) if x in new_d else x for i, x in enumerate(data)] - -            im = Image.new("RGBA", old.size) -            im.putdata(new_data) - -            if colours: -                send_message = ctx.send -                ctx.send = send  # Assigns ctx.send to a fake send -                egg = await ctx.invoke(self.bot.get_command("eggdecorate"), *colours) -                if isinstance(egg, str):  # When an error message occurs in eggdecorate. -                    return await send_message(egg) - -                ratio = 64 / egg.height -                egg = egg.resize((round(egg.width * ratio), round(egg.height * ratio))) -                egg = egg.convert("RGBA") -                im.alpha_composite(egg, (im.width - egg.width, (im.height - egg.height)//2))  # Right centre. -                ctx.send = send_message  # Reassigns ctx.send -            else: -                bunny = Image.open(Path("bot/resources/easter/chocolate_bunny.png")) -                im.alpha_composite(bunny, (im.width - bunny.width, (im.height - bunny.height)//2))  # Right centre. - -            bufferedio = BytesIO() -            im.save(bufferedio, format="PNG") - -            bufferedio.seek(0) - -            file = discord.File(bufferedio, filename="easterified_avatar.png")  # Creates file to be used in embed -            embed = discord.Embed( -                name="Your Lovely Easterified Avatar", -                description="Here is your lovely avatar, all bright and colourful\nwith Easter pastel colours. Enjoy :D" -            ) -            embed.set_image(url="attachment://easterified_avatar.png") -            embed.set_footer(text=f"Made by {ctx.author.display_name}", icon_url=ctx.author.avatar_url) - -        await ctx.send(file=file, embed=embed) - - -def setup(bot: commands.Bot) -> None: -    """Avatar Easterifier Cog load.""" -    bot.add_cog(AvatarEasterifier(bot)) diff --git a/bot/exts/easter/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index 3ecf9be9..3e97373f 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -7,25 +7,26 @@ from typing import List, Union  from discord.ext import commands +from bot.bot import Bot +  log = logging.getLogger(__name__) -with Path("bot/resources/easter/bunny_names.json").open("r", encoding="utf8") as f: -    BUNNY_NAMES = json.load(f) +BUNNY_NAMES = json.loads(Path("bot/resources/easter/bunny_names.json").read_text("utf8"))  class BunnyNameGenerator(commands.Cog):      """Generate a random bunny name, or bunnify your Discord username!""" -    def __init__(self, bot: commands.Bot): -        self.bot = bot - -    def find_separators(self, displayname: str) -> Union[List[str], None]: +    @staticmethod +    def find_separators(displayname: str) -> Union[List[str], None]:          """Check if Discord name contains spaces so we can bunnify an individual word in the name.""" -        new_name = re.split(r'[_.\s]', displayname) +        new_name = re.split(r"[_.\s]", displayname)          if displayname not in new_name:              return new_name +        return None -    def find_vowels(self, displayname: str) -> str: +    @staticmethod +    def find_vowels(displayname: str) -> str:          """          Finds vowels in the user's display name. @@ -34,11 +35,11 @@ class BunnyNameGenerator(commands.Cog):          Only the most recently matched pattern will apply the changes.          """          expressions = [ -            (r'a.+y', 'patchy'), -            (r'e.+y', 'ears'), -            (r'i.+y', 'ditsy'), -            (r'o.+y', 'oofy'), -            (r'u.+y', 'uffy'), +            ("a.+y", "patchy"), +            ("e.+y", "ears"), +            ("i.+y", "ditsy"), +            ("o.+y", "oofy"), +            ("u.+y", "uffy"),          ]          for exp, vowel_sub in expressions: @@ -46,9 +47,10 @@ class BunnyNameGenerator(commands.Cog):              if new_name != displayname:                  return new_name -    def append_name(self, displayname: str) -> str: +    @staticmethod +    def append_name(displayname: str) -> str:          """Adds a suffix to the end of the Discord name.""" -        extensions = ['foot', 'ear', 'nose', 'tail'] +        extensions = ["foot", "ear", "nose", "tail"]          suffix = random.choice(extensions)          appended_name = displayname + suffix @@ -62,7 +64,7 @@ class BunnyNameGenerator(commands.Cog):      @commands.command()      async def bunnifyme(self, ctx: commands.Context) -> None:          """Gets your Discord username and bunnifies it.""" -        username = ctx.message.author.display_name +        username = ctx.author.display_name          # If name contains spaces or other separators, get the individual words to randomly bunnify          spaces_in_name = self.find_separators(username) @@ -75,7 +77,7 @@ class BunnyNameGenerator(commands.Cog):          unmatched_name = self.append_name(username)          if spaces_in_name is not None: -            replacements = ['Cotton', 'Fluff', 'Floof' 'Bounce', 'Snuffle', 'Nibble', 'Cuddle', 'Velvetpaw', 'Carrot'] +            replacements = ["Cotton", "Fluff", "Floof" "Bounce", "Snuffle", "Nibble", "Cuddle", "Velvetpaw", "Carrot"]              word_to_replace = random.choice(spaces_in_name)              substitute = random.choice(replacements)              bunnified_name = username.replace(word_to_replace, substitute) @@ -87,6 +89,6 @@ class BunnyNameGenerator(commands.Cog):          await ctx.send(bunnified_name) -def setup(bot: commands.Bot) -> None: -    """Bunny Name Generator Cog load.""" -    bot.add_cog(BunnyNameGenerator(bot)) +def setup(bot: Bot) -> None: +    """Load the Bunny Name Generator Cog.""" +    bot.add_cog(BunnyNameGenerator()) diff --git a/bot/exts/easter/earth_photos.py b/bot/exts/easter/earth_photos.py new file mode 100644 index 00000000..f65790af --- /dev/null +++ b/bot/exts/easter/earth_photos.py @@ -0,0 +1,66 @@ +import logging + +import discord +from discord.ext import commands + +from bot.bot import Bot +from bot.constants import Colours +from bot.constants import Tokens + +log = logging.getLogger(__name__) + +API_URL = "https://api.unsplash.com/photos/random" + + +class EarthPhotos(commands.Cog): +    """This cog contains the command for earth photos.""" + +    def __init__(self, bot: Bot): +        self.bot = bot + +    @commands.command(aliases=("earth",)) +    async def earth_photos(self, ctx: commands.Context) -> None: +        """Returns a random photo of earth, sourced from Unsplash.""" +        async with ctx.typing(): +            async with self.bot.http_session.get( +                    API_URL, +                    params={"query": "planet_earth", "client_id": Tokens.unsplash_access_key} +            ) as r: +                jsondata = await r.json() +                linksdata = jsondata.get("urls") +                embedlink = linksdata.get("regular") +                downloadlinksdata = jsondata.get("links") +                userdata = jsondata.get("user") +                username = userdata.get("name") +                userlinks = userdata.get("links") +                profile = userlinks.get("html") +                # Referral flags +                rf = "?utm_source=Sir%20Lancebot&utm_medium=referral" +            async with self.bot.http_session.get( +                downloadlinksdata.get("download_location"), +                    params={"client_id": Tokens.unsplash_access_key} +            ) as _: +                pass + +            embed = discord.Embed( +                title="Earth Photo", +                description="A photo of Earth 🌎 from Unsplash.", +                color=Colours.grass_green +            ) +            embed.set_image(url=embedlink) +            embed.add_field( +                name="Author", +                value=( +                    f"Photo by [{username}]({profile}{rf}) " +                    f"on [Unsplash](https://unsplash.com{rf})." +                ) +            ) +            await ctx.send(embed=embed) + + +def setup(bot: Bot) -> None: +    """Load the Earth Photos cog.""" +    if not Tokens.unsplash_access_key: +        log.warning("No Unsplash access key found. Cog not loading.") +        return +    bot.add_cog(EarthPhotos(bot)) diff --git a/bot/exts/easter/easter_riddle.py b/bot/exts/easter/easter_riddle.py index 3c612eb1..88b3be2f 100644 --- a/bot/exts/easter/easter_riddle.py +++ b/bot/exts/easter/easter_riddle.py @@ -1,18 +1,18 @@  import asyncio  import logging  import random -from json import load +from json import loads  from pathlib import Path  import discord  from discord.ext import commands -from bot.constants import Colours +from bot.bot import Bot +from bot.constants import Colours, NEGATIVE_REPLIES  log = logging.getLogger(__name__) -with Path("bot/resources/easter/easter_riddle.json").open("r", encoding="utf8") as f: -    RIDDLE_QUESTIONS = load(f) +RIDDLE_QUESTIONS = loads(Path("bot/resources/easter/easter_riddle.json").read_text("utf8"))  TIMELIMIT = 10 @@ -20,13 +20,13 @@ TIMELIMIT = 10  class EasterRiddle(commands.Cog):      """This cog contains the command for the Easter quiz!""" -    def __init__(self, bot: commands.Bot): +    def __init__(self, bot: Bot):          self.bot = bot          self.winners = set()          self.correct = ""          self.current_channel = None -    @commands.command(aliases=["riddlemethis", "riddleme"]) +    @commands.command(aliases=("riddlemethis", "riddleme"))      async def riddle(self, ctx: commands.Context) -> None:          """          Gives a random riddle, then provides 2 hints at certain intervals before revealing the answer. @@ -34,9 +34,21 @@ class EasterRiddle(commands.Cog):          The duration of the hint interval can be configured by changing the TIMELIMIT constant in this file.          """          if self.current_channel: -            return await ctx.send(f"A riddle is already being solved in {self.current_channel.mention}!") +            await ctx.send(f"A riddle is already being solved in {self.current_channel.mention}!") +            return + +        # Don't let users start in a DM +        if not ctx.guild: +            await ctx.send( +                embed=discord.Embed( +                    title=random.choice(NEGATIVE_REPLIES), +                    description="You can't start riddles in DMs", +                    colour=discord.Colour.red() +                ) +            ) +            return -        self.current_channel = ctx.message.channel +        self.current_channel = ctx.channel          random_question = random.choice(RIDDLE_QUESTIONS)          question = random_question["question"] @@ -95,6 +107,6 @@ class EasterRiddle(commands.Cog):              self.winners.add(message.author.mention) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None:      """Easter Riddle Cog load."""      bot.add_cog(EasterRiddle(bot)) diff --git a/bot/exts/easter/egg_decorating.py b/bot/exts/easter/egg_decorating.py index b18e6636..fd7620d4 100644 --- a/bot/exts/easter/egg_decorating.py +++ b/bot/exts/easter/egg_decorating.py @@ -10,13 +10,14 @@ import discord  from PIL import Image  from discord.ext import commands +from bot.bot import Bot +from bot.utils import helpers +  log = logging.getLogger(__name__) -with open(Path("bot/resources/evergreen/html_colours.json"), encoding="utf8") as f: -    HTML_COLOURS = json.load(f) +HTML_COLOURS = json.loads(Path("bot/resources/evergreen/html_colours.json").read_text("utf8")) -with open(Path("bot/resources/evergreen/xkcd_colours.json"), encoding="utf8") as f: -    XKCD_COLOURS = json.load(f) +XKCD_COLOURS = json.loads(Path("bot/resources/evergreen/xkcd_colours.json").read_text("utf8"))  COLOURS = [      (255, 0, 0, 255), (255, 128, 0, 255), (255, 255, 0, 255), (0, 255, 0, 255), @@ -31,9 +32,6 @@ IRREPLACEABLE = [  class EggDecorating(commands.Cog):      """Decorate some easter eggs!""" -    def __init__(self, bot: commands.Bot) -> None: -        self.bot = bot -      @staticmethod      def replace_invalid(colour: str) -> Union[int, None]:          """Attempts to match with HTML or XKCD colour names, returning the int value.""" @@ -43,10 +41,10 @@ class EggDecorating(commands.Cog):              return int(XKCD_COLOURS[colour], 16)          return None -    @commands.command(aliases=["decorateegg"]) +    @commands.command(aliases=("decorateegg",))      async def eggdecorate(          self, ctx: commands.Context, *colours: Union[discord.Colour, str] -    ) -> Union[Image.Image, discord.Message]: +    ) -> Union[Image.Image, None]:          """          Picks a random egg design and decorates it using the given colours. @@ -54,7 +52,8 @@ class EggDecorating(commands.Cog):          Discord colour names, HTML colour names, XKCD colour names and hex values are accepted.          """          if len(colours) < 2: -            return await ctx.send("You must include at least 2 colours!") +            await ctx.send("You must include at least 2 colours!") +            return          invalid = []          colours = list(colours) @@ -65,12 +64,14 @@ class EggDecorating(commands.Cog):              if value:                  colours[idx] = discord.Colour(value)              else: -                invalid.append(colour) +                invalid.append(helpers.suppress_links(colour))          if len(invalid) > 1: -            return await ctx.send(f"Sorry, I don't know these colours: {' '.join(invalid)}") +            await ctx.send(f"Sorry, I don't know these colours: {' '.join(invalid)}") +            return          elif len(invalid) == 1: -            return await ctx.send(f"Sorry, I don't know the colour {invalid[0]}!") +            await ctx.send(f"Sorry, I don't know the colour {invalid[0]}!") +            return          async with ctx.typing():              # Expand list to 8 colours @@ -113,6 +114,6 @@ class EggDecorating(commands.Cog):          return new_im -def setup(bot: commands.bot) -> None: -    """Egg decorating Cog load.""" -    bot.add_cog(EggDecorating(bot)) +def setup(bot: Bot) -> None: +    """Load the Egg decorating Cog.""" +    bot.add_cog(EggDecorating()) diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index 761e9059..486e735f 100644 --- a/bot/exts/easter/egg_facts.py +++ b/bot/exts/easter/egg_facts.py @@ -1,6 +1,6 @@  import logging  import random -from json import load +from json import loads  from pathlib import Path  import discord @@ -12,6 +12,8 @@ from bot.utils.decorators import seasonal_task  log = logging.getLogger(__name__) +EGG_FACTS = loads(Path("bot/resources/easter/easter_egg_facts.json").read_text("utf8")) +  class EasterFacts(commands.Cog):      """ @@ -22,17 +24,8 @@ class EasterFacts(commands.Cog):      def __init__(self, bot: Bot):          self.bot = bot -        self.facts = self.load_json() -          self.daily_fact_task = self.bot.loop.create_task(self.send_egg_fact_daily()) -    @staticmethod -    def load_json() -> dict: -        """Load a list of easter egg facts from the resource JSON file.""" -        p = Path("bot/resources/easter/easter_egg_facts.json") -        with p.open(encoding="utf8") as f: -            return load(f) -      @seasonal_task(Month.APRIL)      async def send_egg_fact_daily(self) -> None:          """A background task that sends an easter egg fact in the event channel everyday.""" @@ -41,21 +34,22 @@ class EasterFacts(commands.Cog):          channel = self.bot.get_channel(Channels.community_bot_commands)          await channel.send(embed=self.make_embed()) -    @commands.command(name='eggfact', aliases=['fact']) +    @commands.command(name="eggfact", aliases=("fact",))      async def easter_facts(self, ctx: commands.Context) -> None:          """Get easter egg facts."""          embed = self.make_embed()          await ctx.send(embed=embed) -    def make_embed(self) -> discord.Embed: +    @staticmethod +    def make_embed() -> discord.Embed:          """Makes a nice embed for the message to be sent."""          return discord.Embed(              colour=Colours.soft_red,              title="Easter Egg Fact", -            description=random.choice(self.facts) +            description=random.choice(EGG_FACTS)          )  def setup(bot: Bot) -> None: -    """Easter Egg facts cog load.""" +    """Load the Easter Egg facts Cog."""      bot.add_cog(EasterFacts(bot)) diff --git a/bot/exts/easter/egghead_quiz.py b/bot/exts/easter/egghead_quiz.py index 0498d9db..7c4960cd 100644 --- a/bot/exts/easter/egghead_quiz.py +++ b/bot/exts/easter/egghead_quiz.py @@ -1,28 +1,28 @@  import asyncio  import logging  import random -from json import load +from json import loads  from pathlib import Path  from typing import Union  import discord  from discord.ext import commands +from bot.bot import Bot  from bot.constants import Colours  log = logging.getLogger(__name__) -with open(Path("bot/resources/easter/egghead_questions.json"), "r", encoding="utf8") as f: -    EGGHEAD_QUESTIONS = load(f) +EGGHEAD_QUESTIONS = loads(Path("bot/resources/easter/egghead_questions.json").read_text("utf8"))  EMOJIS = [ -    '\U0001f1e6', '\U0001f1e7', '\U0001f1e8', '\U0001f1e9', '\U0001f1ea', -    '\U0001f1eb', '\U0001f1ec', '\U0001f1ed', '\U0001f1ee', '\U0001f1ef', -    '\U0001f1f0', '\U0001f1f1', '\U0001f1f2', '\U0001f1f3', '\U0001f1f4', -    '\U0001f1f5', '\U0001f1f6', '\U0001f1f7', '\U0001f1f8', '\U0001f1f9', -    '\U0001f1fa', '\U0001f1fb', '\U0001f1fc', '\U0001f1fd', '\U0001f1fe', -    '\U0001f1ff' +    "\U0001f1e6", "\U0001f1e7", "\U0001f1e8", "\U0001f1e9", "\U0001f1ea", +    "\U0001f1eb", "\U0001f1ec", "\U0001f1ed", "\U0001f1ee", "\U0001f1ef", +    "\U0001f1f0", "\U0001f1f1", "\U0001f1f2", "\U0001f1f3", "\U0001f1f4", +    "\U0001f1f5", "\U0001f1f6", "\U0001f1f7", "\U0001f1f8", "\U0001f1f9", +    "\U0001f1fa", "\U0001f1fb", "\U0001f1fc", "\U0001f1fd", "\U0001f1fe", +    "\U0001f1ff"  ]  # Regional Indicators A-Z (used for voting)  TIMELIMIT = 30 @@ -31,11 +31,10 @@ TIMELIMIT = 30  class EggheadQuiz(commands.Cog):      """This cog contains the command for the Easter quiz!""" -    def __init__(self, bot: commands.Bot) -> None: -        self.bot = bot +    def __init__(self) -> None:          self.quiz_messages = {} -    @commands.command(aliases=["eggheadquiz", "easterquiz"]) +    @commands.command(aliases=("eggheadquiz", "easterquiz"))      async def eggquiz(self, ctx: commands.Context) -> None:          """          Gives a random quiz question, waits 30 seconds and then outputs the answer. @@ -64,7 +63,7 @@ class EggheadQuiz(commands.Cog):          del self.quiz_messages[msg.id] -        msg = await ctx.channel.fetch_message(msg.id)  # Refreshes message +        msg = await ctx.fetch_message(msg.id)  # Refreshes message          total_no = sum([len(await r.users().flatten()) for r in msg.reactions]) - len(valid_emojis)  # - bot's reactions @@ -114,6 +113,6 @@ class EggheadQuiz(commands.Cog):              return await reaction.message.remove_reaction(reaction, user) -def setup(bot: commands.Bot) -> None: -    """Egghead Quiz Cog load.""" -    bot.add_cog(EggheadQuiz(bot)) +def setup(bot: Bot) -> None: +    """Load the Egghead Quiz Cog.""" +    bot.add_cog(EggheadQuiz()) diff --git a/bot/exts/easter/save_the_planet.py b/bot/exts/easter/save_the_planet.py index 8f644259..1bd515f2 100644 --- a/bot/exts/easter/save_the_planet.py +++ b/bot/exts/easter/save_the_planet.py @@ -4,26 +4,22 @@ from pathlib import Path  from discord import Embed  from discord.ext import commands +from bot.bot import Bot  from bot.utils.randomization import RandomCycle - -with Path("bot/resources/easter/save_the_planet.json").open('r', encoding='utf8') as f: -    EMBED_DATA = RandomCycle(json.load(f)) +EMBED_DATA = RandomCycle(json.loads(Path("bot/resources/easter/save_the_planet.json").read_text("utf8")))  class SaveThePlanet(commands.Cog):      """A cog that teaches users how they can help our planet.""" -    def __init__(self, bot: commands.Bot) -> None: -        self.bot = bot - -    @commands.command(aliases=('savetheearth', 'saveplanet', 'saveearth')) +    @commands.command(aliases=("savetheearth", "saveplanet", "saveearth"))      async def savetheplanet(self, ctx: commands.Context) -> None:          """Responds with a random tip on how to be eco-friendly and help our planet."""          return_embed = Embed.from_dict(next(EMBED_DATA))          await ctx.send(embed=return_embed) -def setup(bot: commands.Bot) -> None: -    """Save the Planet Cog load.""" -    bot.add_cog(SaveThePlanet(bot)) +def setup(bot: Bot) -> None: +    """Load the Save the Planet Cog.""" +    bot.add_cog(SaveThePlanet()) diff --git a/bot/exts/easter/traditions.py b/bot/exts/easter/traditions.py index 85b4adfb..93404f3e 100644 --- a/bot/exts/easter/traditions.py +++ b/bot/exts/easter/traditions.py @@ -5,19 +5,17 @@ from pathlib import Path  from discord.ext import commands +from bot.bot import Bot +  log = logging.getLogger(__name__) -with open(Path("bot/resources/easter/traditions.json"), "r", encoding="utf8") as f: -    traditions = json.load(f) +traditions = json.loads(Path("bot/resources/easter/traditions.json").read_text("utf8"))  class Traditions(commands.Cog):      """A cog which allows users to get a random easter tradition or custom from a random country.""" -    def __init__(self, bot: commands.Bot): -        self.bot = bot - -    @commands.command(aliases=('eastercustoms',)) +    @commands.command(aliases=("eastercustoms",))      async def easter_tradition(self, ctx: commands.Context) -> None:          """Responds with a random tradition or custom."""          random_country = random.choice(list(traditions)) @@ -25,6 +23,6 @@ class Traditions(commands.Cog):          await ctx.send(f"{random_country}:\n{traditions[random_country]}") -def setup(bot: commands.Bot) -> None: -    """Traditions Cog load.""" -    bot.add_cog(Traditions(bot)) +def setup(bot: Bot) -> None: +    """Load the Traditions Cog.""" +    bot.add_cog(Traditions())  |