From a40967bab9ae60bc78c96a978350cb7a79372ac6 Mon Sep 17 00:00:00 2001 From: Joe Banks Date: Wed, 10 Mar 2021 17:51:57 +0000 Subject: Load environment variables from .env --- bot/__init__.py | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'bot') diff --git a/bot/__init__.py b/bot/__init__.py index bdb18666..ffd43d1f 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -1,3 +1,10 @@ +try: + from dotenv import load_dotenv + print("Found .env file, loading environment variables from it.") + load_dotenv(override=True) +except ModuleNotFoundError: + pass + import asyncio import logging import logging.handlers -- cgit v1.2.3 From bdfeef5d16ff64a7ca8a9a610d39a654f2e1fb99 Mon Sep 17 00:00:00 2001 From: Chris Date: Sun, 28 Mar 2021 23:01:55 +0100 Subject: Rework bookmark command to allow other users to bookmark the same message. --- bot/exts/evergreen/bookmark.py | 116 +++++++++++++++++++++++++++++++++-------- 1 file changed, 95 insertions(+), 21 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 5fa05d2e..d26c4845 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -1,14 +1,18 @@ +import asyncio import logging import random import discord from discord.ext import commands -from bot.constants import Colours, ERROR_REPLIES, Emojis, Icons +from bot.constants import Colours, ERROR_REPLIES, Icons from bot.utils.converters import WrappedMessageConverter log = logging.getLogger(__name__) +# Number of seconds to wait for other users to bookmark the same message +TIMEOUT = 120 + class Bookmark(commands.Cog): """Creates personal bookmarks by relaying a message link to the user's DMs.""" @@ -16,6 +20,64 @@ class Bookmark(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot + @staticmethod + def build_bookmark_dm(target_message: WrappedMessageConverter, title: str) -> discord.Embed: + """Builds the embed to DM the bookmark requestor.""" + embed = discord.Embed( + title=title, + description=target_message.content, + colour=Colours.soft_green + ) + embed.add_field(name="Wanna give it a visit?", value=f"[Visit original message]({target_message.jump_url})") + embed.set_author(name=target_message.author, icon_url=target_message.author.avatar_url) + embed.set_thumbnail(url=Icons.bookmark) + + return embed + + @staticmethod + def build_error_embed(user: discord.Member) -> discord.Embed: + """Builds an error embed for when a bookmark requestor has DMs disabled.""" + return discord.Embed( + title=random.choice(ERROR_REPLIES), + description=f"{user.mention}, please enable your DMs to receive the bookmark", + colour=Colours.soft_red + ) + + async def action_bookmark( + self, + channel: discord.TextChannel, + user: discord.Member, + target_message: WrappedMessageConverter, + title: str + ) -> None: + """Sends the bookmark DM, or sends an error embed when a user bookmarks a message.""" + try: + embed = self.build_bookmark_dm(target_message, title) + await user.send(embed=embed) + except discord.Forbidden: + error_embed = self.build_error_embed(user) + await channel.send(embed=error_embed) + else: + log.info(f"{user} bookmarked {target_message.jump_url} with title '{title}'") + + @staticmethod + async def send_reaction_embed( + channel: discord.TextChannel, + target_message: WrappedMessageConverter + ) -> discord.Message: + """Sends an embed, with a reaction, so users can react to bookmark the message too.""" + message = await channel.send( + embed=discord.Embed( + description=( + f"React with 📌 to be sent your very own bookmark to [this message]({target_message.jump_url})." + ), + colour=Colours.soft_green + ) + ) + + await message.add_reaction("📌") + return message + @commands.command(name="bookmark", aliases=("bm", "pin")) async def bookmark( self, @@ -37,27 +99,39 @@ class Bookmark(commands.Cog): await ctx.send(embed=embed) return - embed = discord.Embed( - title=title, - colour=Colours.soft_green, - description=target_message.content - ) - embed.add_field(name="Wanna give it a visit?", value=f"[Visit original message]({target_message.jump_url})") - embed.set_author(name=target_message.author, icon_url=target_message.author.avatar_url) - embed.set_thumbnail(url=Icons.bookmark) - - try: - await ctx.author.send(embed=embed) - except discord.Forbidden: - error_embed = discord.Embed( - title=random.choice(ERROR_REPLIES), - description=f"{ctx.author.mention}, please enable your DMs to receive the bookmark", - colour=Colours.soft_red + def event_check(reaction_: discord.Reaction, user_: discord.Member) -> bool: + """Make sure that this reaction is what we want to operate on.""" + return ( + # Conditions for a successful pagination: + all(( + # Reaction is on this message + reaction_.message.id == reaction_message.id, + # User has not already bookmarked this message + user_.id not in bookmarked_users, + # Reaction is the 📌 emoji + str(reaction_.emoji) == "📌", + # Reaction was not made by the Bot + user_.id != self.bot.user.id + )) ) - await ctx.send(embed=error_embed) - else: - log.info(f"{ctx.author} bookmarked {target_message.jump_url} with title '{title}'") - await ctx.message.add_reaction(Emojis.envelope) + await self.action_bookmark(ctx.channel, ctx.author, target_message, title) + + # Keep track of who has already bookmarked, so users can't spam reactions and cause loads of DMs + bookmarked_users = [ctx.author.id] + reaction_message = await self.send_reaction_embed(ctx.channel, target_message) + + while True: + try: + _, user = await self.bot.wait_for("reaction_add", timeout=TIMEOUT, check=event_check) + except asyncio.TimeoutError: + log.debug("Timed out waiting for a reaction") + break # We're done, no reactions for the last 5 minutes + log.trace(f"{user} has sucessfully bookmarked from a reaction, attempting to DM them.") + await self.action_bookmark(ctx.channel, user, target_message, title) + bookmarked_users.append(user.id) + + # Delete the message now that we're done with it. + await reaction_message.delete() def setup(bot: commands.Bot) -> None: -- cgit v1.2.3 From 99a0fccf221ae9e365a76d9b8c6c330de6264c90 Mon Sep 17 00:00:00 2001 From: Chris Date: Sun, 28 Mar 2021 23:30:32 +0100 Subject: Update phrasing of comments in bookmark command --- bot/exts/evergreen/bookmark.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index d26c4845..bfb1e700 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -125,12 +125,12 @@ class Bookmark(commands.Cog): _, user = await self.bot.wait_for("reaction_add", timeout=TIMEOUT, check=event_check) except asyncio.TimeoutError: log.debug("Timed out waiting for a reaction") - break # We're done, no reactions for the last 5 minutes + break # No reactions for the last `TIMEOUT` seconds log.trace(f"{user} has sucessfully bookmarked from a reaction, attempting to DM them.") await self.action_bookmark(ctx.channel, user, target_message, title) bookmarked_users.append(user.id) - # Delete the message now that we're done with it. + # Delete the message now that the bot isn't listening to it to save screen space await reaction_message.delete() -- cgit v1.2.3 From a308990d1432a1a29f54e74678630f374a5fac2c Mon Sep 17 00:00:00 2001 From: ChrisJL Date: Mon, 29 Mar 2021 12:28:40 +0100 Subject: Fix spelling and grammar errors in bookmark command Co-authored-by: Shivansh-007 <69356296+Shivansh-007@users.noreply.github.com> --- bot/exts/evergreen/bookmark.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index bfb1e700..9246825a 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -22,7 +22,7 @@ class Bookmark(commands.Cog): @staticmethod def build_bookmark_dm(target_message: WrappedMessageConverter, title: str) -> discord.Embed: - """Builds the embed to DM the bookmark requestor.""" + """Builds the embed to DM the bookmark requester.""" embed = discord.Embed( title=title, description=target_message.content, @@ -36,10 +36,10 @@ class Bookmark(commands.Cog): @staticmethod def build_error_embed(user: discord.Member) -> discord.Embed: - """Builds an error embed for when a bookmark requestor has DMs disabled.""" + """Builds an error embed for when a bookmark requester has DMs disabled.""" return discord.Embed( title=random.choice(ERROR_REPLIES), - description=f"{user.mention}, please enable your DMs to receive the bookmark", + description=f"{user.mention}, please enable your DMs to receive the bookmark.", colour=Colours.soft_red ) @@ -126,7 +126,7 @@ class Bookmark(commands.Cog): except asyncio.TimeoutError: log.debug("Timed out waiting for a reaction") break # No reactions for the last `TIMEOUT` seconds - log.trace(f"{user} has sucessfully bookmarked from a reaction, attempting to DM them.") + log.trace(f"{user} has successfully bookmarked from a reaction, attempting to DM them.") await self.action_bookmark(ctx.channel, user, target_message, title) bookmarked_users.append(user.id) -- cgit v1.2.3 From 6e71554c1604cb372415a505e4db7ca0f80f30fd Mon Sep 17 00:00:00 2001 From: ChrisJL Date: Mon, 29 Mar 2021 12:29:25 +0100 Subject: Split out an embed add field call for readability Co-authored-by: Shivansh-007 <69356296+Shivansh-007@users.noreply.github.com> --- bot/exts/evergreen/bookmark.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 9246825a..c4c238c3 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -28,7 +28,10 @@ class Bookmark(commands.Cog): description=target_message.content, colour=Colours.soft_green ) - embed.add_field(name="Wanna give it a visit?", value=f"[Visit original message]({target_message.jump_url})") + embed.add_field( + name="Wanna give it a visit?", + value=f"[Visit original message]({target_message.jump_url})" + ) embed.set_author(name=target_message.author, icon_url=target_message.author.avatar_url) embed.set_thumbnail(url=Icons.bookmark) -- cgit v1.2.3 From 22e062ab679afd5b6aa1790617097ed45ffee1f5 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 29 Mar 2021 12:31:10 +0100 Subject: Make bookmark emoji a constant --- bot/exts/evergreen/bookmark.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index c4c238c3..59e2c9d0 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -12,6 +12,7 @@ log = logging.getLogger(__name__) # Number of seconds to wait for other users to bookmark the same message TIMEOUT = 120 +BOOKMARK_EMOJI = "📌" class Bookmark(commands.Cog): @@ -29,7 +30,7 @@ class Bookmark(commands.Cog): colour=Colours.soft_green ) embed.add_field( - name="Wanna give it a visit?", + name="Wanna give it a visit?", value=f"[Visit original message]({target_message.jump_url})" ) embed.set_author(name=target_message.author, icon_url=target_message.author.avatar_url) @@ -72,13 +73,14 @@ class Bookmark(commands.Cog): message = await channel.send( embed=discord.Embed( description=( - f"React with 📌 to be sent your very own bookmark to [this message]({target_message.jump_url})." + f"React with {BOOKMARK_EMOJI} to be sent your very own bookmark to " + f"[this message]({target_message.jump_url})." ), colour=Colours.soft_green ) ) - await message.add_reaction("📌") + await message.add_reaction(BOOKMARK_EMOJI) return message @commands.command(name="bookmark", aliases=("bm", "pin")) @@ -111,8 +113,8 @@ class Bookmark(commands.Cog): reaction_.message.id == reaction_message.id, # User has not already bookmarked this message user_.id not in bookmarked_users, - # Reaction is the 📌 emoji - str(reaction_.emoji) == "📌", + # Reaction is the `BOOKMARK_EMOJI` emoji + str(reaction_.emoji) == BOOKMARK_EMOJI, # Reaction was not made by the Bot user_.id != self.bot.user.id )) -- cgit v1.2.3 From c082ab627c4a4ecf5e497f85b1424f78c73c2120 Mon Sep 17 00:00:00 2001 From: ChrisJL Date: Tue, 30 Mar 2021 21:22:06 +0100 Subject: Consistent comments in bookmark command Co-authored-by: Xithrius <15021300+Xithrius@users.noreply.github.com> --- bot/exts/evergreen/bookmark.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 59e2c9d0..2088c610 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -130,7 +130,8 @@ class Bookmark(commands.Cog): _, user = await self.bot.wait_for("reaction_add", timeout=TIMEOUT, check=event_check) except asyncio.TimeoutError: log.debug("Timed out waiting for a reaction") - break # No reactions for the last `TIMEOUT` seconds + # No reactions for the last `TIMEOUT` seconds + break log.trace(f"{user} has successfully bookmarked from a reaction, attempting to DM them.") await self.action_bookmark(ctx.channel, user, target_message, title) bookmarked_users.append(user.id) -- cgit v1.2.3 From fd57de601752db923f558b726e17af665a69df55 Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 30 Mar 2021 21:26:10 +0100 Subject: Remove unnecessary underscores from variables in the bm command --- bot/exts/evergreen/bookmark.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 2088c610..16919d8c 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -104,19 +104,19 @@ class Bookmark(commands.Cog): await ctx.send(embed=embed) return - def event_check(reaction_: discord.Reaction, user_: discord.Member) -> bool: + def event_check(reaction: discord.Reaction, user: discord.Member) -> bool: """Make sure that this reaction is what we want to operate on.""" return ( # Conditions for a successful pagination: all(( # Reaction is on this message - reaction_.message.id == reaction_message.id, + reaction.message.id == reaction_message.id, # User has not already bookmarked this message - user_.id not in bookmarked_users, + user.id not in bookmarked_users, # Reaction is the `BOOKMARK_EMOJI` emoji - str(reaction_.emoji) == BOOKMARK_EMOJI, + str(reaction.emoji) == BOOKMARK_EMOJI, # Reaction was not made by the Bot - user_.id != self.bot.user.id + user.id != self.bot.user.id )) ) await self.action_bookmark(ctx.channel, ctx.author, target_message, title) -- cgit v1.2.3 From 1ed857d9093481387720ac1dc4041a64a2c9c593 Mon Sep 17 00:00:00 2001 From: vcokltfre Date: Mon, 19 Apr 2021 20:20:48 +0100 Subject: chore: switch commands.Bot typehints to bot.bot's Bot --- bot/exts/evergreen/8bitify.py | 6 ++++-- bot/exts/evergreen/battleship.py | 7 ++++--- bot/exts/evergreen/bookmark.py | 5 +++-- bot/exts/evergreen/cheatsheet.py | 5 +++-- bot/exts/evergreen/connect_four.py | 9 +++++---- bot/exts/evergreen/conversationstarters.py | 5 +++-- bot/exts/evergreen/emoji.py | 5 +++-- bot/exts/evergreen/error_handler.py | 5 +++-- bot/exts/evergreen/fun.py | 5 +++-- bot/exts/evergreen/githubinfo.py | 5 +++-- bot/exts/evergreen/issues.py | 5 +++-- bot/exts/evergreen/latex.py | 4 +++- bot/exts/evergreen/magic_8ball.py | 6 ++++-- bot/exts/evergreen/minesweeper.py | 5 +++-- bot/exts/evergreen/movie.py | 3 ++- bot/exts/evergreen/ping.py | 5 +++-- bot/exts/evergreen/pythonfacts.py | 5 +++-- bot/exts/evergreen/recommend_game.py | 6 ++++-- bot/exts/evergreen/reddit.py | 5 +++-- bot/exts/evergreen/source.py | 5 +++-- bot/exts/evergreen/speedrun.py | 6 ++++-- bot/exts/evergreen/status_codes.py | 5 +++-- bot/exts/evergreen/timed.py | 4 +++- bot/exts/evergreen/trivia_quiz.py | 5 +++-- bot/exts/evergreen/uptime.py | 5 +++-- bot/exts/evergreen/wolfram.py | 7 ++++--- bot/exts/evergreen/wonder_twins.py | 4 +++- 27 files changed, 88 insertions(+), 54 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/8bitify.py b/bot/exts/evergreen/8bitify.py index 7eb4d313..621aa875 100644 --- a/bot/exts/evergreen/8bitify.py +++ b/bot/exts/evergreen/8bitify.py @@ -4,11 +4,13 @@ import discord from PIL import Image from discord.ext import commands +from bot.bot import Bot + class EightBitify(commands.Cog): """Make your avatar 8bit!""" - def __init__(self, bot: commands.Bot) -> None: + def __init__(self, bot: Bot) -> None: self.bot = bot @staticmethod @@ -50,6 +52,6 @@ class EightBitify(commands.Cog): await ctx.send(file=file, embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Cog load.""" bot.add_cog(EightBitify(bot)) diff --git a/bot/exts/evergreen/battleship.py b/bot/exts/evergreen/battleship.py index 1681434f..f255afb9 100644 --- a/bot/exts/evergreen/battleship.py +++ b/bot/exts/evergreen/battleship.py @@ -9,6 +9,7 @@ from functools import partial import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours log = logging.getLogger(__name__) @@ -95,7 +96,7 @@ class Game: def __init__( self, - bot: commands.Bot, + bot: Bot, channel: discord.TextChannel, player1: discord.Member, player2: discord.Member @@ -321,7 +322,7 @@ class Game: class Battleship(commands.Cog): """Play the classic game Battleship!""" - def __init__(self, bot: commands.Bot) -> None: + def __init__(self, bot: Bot) -> None: self.bot = bot self.games: typing.List[Game] = [] self.waiting: typing.List[discord.Member] = [] @@ -438,6 +439,6 @@ class Battleship(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Cog load.""" bot.add_cog(Battleship(bot)) diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 5fa05d2e..329838b9 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -4,6 +4,7 @@ import random import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours, ERROR_REPLIES, Emojis, Icons from bot.utils.converters import WrappedMessageConverter @@ -13,7 +14,7 @@ log = logging.getLogger(__name__) class Bookmark(commands.Cog): """Creates personal bookmarks by relaying a message link to the user's DMs.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.command(name="bookmark", aliases=("bm", "pin")) @@ -60,6 +61,6 @@ class Bookmark(commands.Cog): await ctx.message.add_reaction(Emojis.envelope) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the Bookmark cog.""" bot.add_cog(Bookmark(bot)) diff --git a/bot/exts/evergreen/cheatsheet.py b/bot/exts/evergreen/cheatsheet.py index 3fe709d5..57c6d0b0 100644 --- a/bot/exts/evergreen/cheatsheet.py +++ b/bot/exts/evergreen/cheatsheet.py @@ -8,6 +8,7 @@ from discord.ext import commands from discord.ext.commands import BucketType, Context from bot import constants +from bot.bot import Bot from bot.constants import Categories, Channels, Colours, ERROR_REPLIES from bot.utils.decorators import whitelist_override @@ -33,7 +34,7 @@ HEADERS = {'User-Agent': 'curl/7.68.0'} class CheatSheet(commands.Cog): """Commands that sends a result of a cht.sh search in code blocks.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @staticmethod @@ -102,6 +103,6 @@ class CheatSheet(commands.Cog): await ctx.send(content=description) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the CheatSheet cog.""" bot.add_cog(CheatSheet(bot)) diff --git a/bot/exts/evergreen/connect_four.py b/bot/exts/evergreen/connect_four.py index 7e3ec42b..fbb13780 100644 --- a/bot/exts/evergreen/connect_four.py +++ b/bot/exts/evergreen/connect_four.py @@ -8,6 +8,7 @@ import emojis from discord.ext import commands from discord.ext.commands import guild_only +from bot.bot import Bot from bot.constants import Emojis NUMBERS = list(Emojis.number_emojis.values()) @@ -22,7 +23,7 @@ class Game: def __init__( self, - bot: commands.Bot, + bot: Bot, channel: discord.TextChannel, player1: discord.Member, player2: typing.Optional[discord.Member], @@ -180,7 +181,7 @@ class Game: class AI: """The Computer Player for Single-Player games.""" - def __init__(self, bot: commands.Bot, game: Game) -> None: + def __init__(self, bot: Bot, game: Game) -> None: self.game = game self.mention = bot.user.mention @@ -255,7 +256,7 @@ class AI: class ConnectFour(commands.Cog): """Connect Four. The Classic Vertical Four-in-a-row Game!""" - def __init__(self, bot: commands.Bot) -> None: + def __init__(self, bot: Bot) -> None: self.bot = bot self.games: typing.List[Game] = [] self.waiting: typing.List[discord.Member] = [] @@ -445,6 +446,6 @@ class ConnectFour(commands.Cog): await self._play_game(ctx, None, board_size, str(emoji1), str(emoji2)) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load ConnectFour Cog.""" bot.add_cog(ConnectFour(bot)) diff --git a/bot/exts/evergreen/conversationstarters.py b/bot/exts/evergreen/conversationstarters.py index e7058961..aed76bcf 100644 --- a/bot/exts/evergreen/conversationstarters.py +++ b/bot/exts/evergreen/conversationstarters.py @@ -4,6 +4,7 @@ import yaml from discord import Color, Embed from discord.ext import commands +from bot.bot import Bot from bot.constants import WHITELISTED_CHANNELS from bot.utils.decorators import whitelist_override from bot.utils.randomization import RandomCycle @@ -34,7 +35,7 @@ TOPICS = { class ConvoStarters(commands.Cog): """Evergreen conversation topics.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.command() @@ -66,6 +67,6 @@ class ConvoStarters(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Conversation starters Cog load.""" bot.add_cog(ConvoStarters(bot)) diff --git a/bot/exts/evergreen/emoji.py b/bot/exts/evergreen/emoji.py index fa3044e3..58d9be03 100644 --- a/bot/exts/evergreen/emoji.py +++ b/bot/exts/evergreen/emoji.py @@ -8,6 +8,7 @@ from typing import List, Optional, Tuple from discord import Color, Embed, Emoji from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours, ERROR_REPLIES from bot.utils.extensions import invoke_help_command from bot.utils.pagination import LinePaginator @@ -19,7 +20,7 @@ log = logging.getLogger(__name__) class Emojis(commands.Cog): """A collection of commands related to emojis in the server.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @staticmethod @@ -120,6 +121,6 @@ class Emojis(commands.Cog): await ctx.send(embed=emoji_information) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Add the Emojis cog into the bot.""" bot.add_cog(Emojis(bot)) diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index 8db49748..053e3866 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -7,6 +7,7 @@ from discord import Embed, Message from discord.ext import commands from sentry_sdk import push_scope +from bot.bot import Bot from bot.constants import Channels, Colours, ERROR_REPLIES, NEGATIVE_REPLIES from bot.utils.decorators import InChannelCheckFailure, InMonthCheckFailure from bot.utils.exceptions import UserNotPlayingError @@ -17,7 +18,7 @@ log = logging.getLogger(__name__) class CommandErrorHandler(commands.Cog): """A error handler for the PythonDiscord server.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @staticmethod @@ -135,6 +136,6 @@ class CommandErrorHandler(commands.Cog): log.exception(f"Unhandled command error: {str(error)}", exc_info=error) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Error handler Cog load.""" bot.add_cog(CommandErrorHandler(bot)) diff --git a/bot/exts/evergreen/fun.py b/bot/exts/evergreen/fun.py index 101725da..cde37895 100644 --- a/bot/exts/evergreen/fun.py +++ b/bot/exts/evergreen/fun.py @@ -7,9 +7,10 @@ from typing import Callable, Iterable, Tuple, Union from discord import Embed, Message from discord.ext import commands -from discord.ext.commands import BadArgument, Bot, Cog, Context, MessageConverter, clean_content +from discord.ext.commands import BadArgument, Cog, Context, MessageConverter, clean_content from bot import utils +from bot.bot import Bot from bot.constants import Client, Colours, Emojis log = logging.getLogger(__name__) @@ -239,6 +240,6 @@ class Fun(Cog): return Embed.from_dict(embed_dict) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Fun Cog load.""" bot.add_cog(Fun(bot)) diff --git a/bot/exts/evergreen/githubinfo.py b/bot/exts/evergreen/githubinfo.py index c8a6b3f7..da6eba5c 100644 --- a/bot/exts/evergreen/githubinfo.py +++ b/bot/exts/evergreen/githubinfo.py @@ -7,6 +7,7 @@ import discord from discord.ext import commands from discord.ext.commands.cooldowns import BucketType +from bot.bot import Bot from bot.constants import Colours, NEGATIVE_REPLIES from bot.exts.utils.extensions import invoke_help_command @@ -18,7 +19,7 @@ GITHUB_API_URL = "https://api.github.com" class GithubInfo(commands.Cog): """Fetches info from GitHub.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot async def fetch_data(self, url: str) -> dict: @@ -170,6 +171,6 @@ class GithubInfo(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Adding the cog to the bot.""" bot.add_cog(GithubInfo(bot)) diff --git a/bot/exts/evergreen/issues.py b/bot/exts/evergreen/issues.py index a0316080..692e0b43 100644 --- a/bot/exts/evergreen/issues.py +++ b/bot/exts/evergreen/issues.py @@ -7,6 +7,7 @@ from dataclasses import dataclass import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import ( Categories, Channels, @@ -91,7 +92,7 @@ class IssueState: class Issues(commands.Cog): """Cog that allows users to retrieve issues from GitHub.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot self.repos = [] @@ -269,6 +270,6 @@ class Issues(commands.Cog): await message.channel.send(embed=resp) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Cog Retrieves Issues From Github.""" bot.add_cog(Issues(bot)) diff --git a/bot/exts/evergreen/latex.py b/bot/exts/evergreen/latex.py index c4a8597c..3a93907a 100644 --- a/bot/exts/evergreen/latex.py +++ b/bot/exts/evergreen/latex.py @@ -9,6 +9,8 @@ import discord import matplotlib.pyplot as plt from discord.ext import commands +from bot.bot import Bot + # configure fonts and colors for matplotlib plt.rcParams.update( { @@ -89,6 +91,6 @@ class Latex(commands.Cog): await ctx.send(file=discord.File(image, "latex.png")) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the Latex Cog.""" bot.add_cog(Latex(bot)) diff --git a/bot/exts/evergreen/magic_8ball.py b/bot/exts/evergreen/magic_8ball.py index f974e487..2dfe237a 100644 --- a/bot/exts/evergreen/magic_8ball.py +++ b/bot/exts/evergreen/magic_8ball.py @@ -5,13 +5,15 @@ from pathlib import Path from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) class Magic8ball(commands.Cog): """A Magic 8ball command to respond to a user's question.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot with open(Path("bot/resources/evergreen/magic8ball.json"), "r", encoding="utf8") as file: self.answers = json.load(file) @@ -26,6 +28,6 @@ class Magic8ball(commands.Cog): await ctx.send("Usage: .8ball (minimum length of 3 eg: `will I win?`)") -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Magic 8ball Cog load.""" bot.add_cog(Magic8ball(bot)) diff --git a/bot/exts/evergreen/minesweeper.py b/bot/exts/evergreen/minesweeper.py index 3031debc..7c1bac3b 100644 --- a/bot/exts/evergreen/minesweeper.py +++ b/bot/exts/evergreen/minesweeper.py @@ -6,6 +6,7 @@ from random import randint, random import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Client from bot.utils.exceptions import UserNotPlayingError from bot.utils.extensions import invoke_help_command @@ -78,7 +79,7 @@ GamesDict = typing.Dict[int, Game] class Minesweeper(commands.Cog): """Play a game of Minesweeper.""" - def __init__(self, bot: commands.Bot) -> None: + def __init__(self, bot: Bot) -> None: self.games: GamesDict = {} # Store the currently running games @commands.group(name='minesweeper', aliases=('ms',), invoke_without_command=True) @@ -292,6 +293,6 @@ class Minesweeper(commands.Cog): del self.games[ctx.author.id] -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the Minesweeper cog.""" bot.add_cog(Minesweeper(bot)) diff --git a/bot/exts/evergreen/movie.py b/bot/exts/evergreen/movie.py index b3bfe998..f4356f33 100644 --- a/bot/exts/evergreen/movie.py +++ b/bot/exts/evergreen/movie.py @@ -6,8 +6,9 @@ from urllib.parse import urlencode from aiohttp import ClientSession from discord import Embed -from discord.ext.commands import Bot, Cog, Context, group +from discord.ext.commands import Cog, Context, group +from bot.bot import Bot from bot.constants import Tokens from bot.utils.extensions import invoke_help_command from bot.utils.pagination import ImagePaginator diff --git a/bot/exts/evergreen/ping.py b/bot/exts/evergreen/ping.py index 97f8b34d..1332e3e6 100644 --- a/bot/exts/evergreen/ping.py +++ b/bot/exts/evergreen/ping.py @@ -1,13 +1,14 @@ from discord import Embed from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours class Ping(commands.Cog): """Ping the bot to see its latency and state.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.command(name="ping") @@ -22,6 +23,6 @@ class Ping(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Cog load.""" bot.add_cog(Ping(bot)) diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index 457c2fd3..bbc4eb17 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -3,6 +3,7 @@ import itertools import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours with open('bot/resources/evergreen/python_facts.txt') as file: @@ -14,7 +15,7 @@ COLORS = itertools.cycle([Colours.python_blue, Colours.python_yellow]) class PythonFacts(commands.Cog): """Sends a random fun fact about Python.""" - def __init__(self, bot: commands.Bot) -> None: + def __init__(self, bot: Bot) -> None: self.bot = bot @commands.command(name='pythonfact', aliases=['pyfact']) @@ -28,6 +29,6 @@ class PythonFacts(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load PythonFacts Cog.""" bot.add_cog(PythonFacts(bot)) diff --git a/bot/exts/evergreen/recommend_game.py b/bot/exts/evergreen/recommend_game.py index 5e262a5b..be329f44 100644 --- a/bot/exts/evergreen/recommend_game.py +++ b/bot/exts/evergreen/recommend_game.py @@ -6,6 +6,8 @@ from random import shuffle import discord from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) game_recs = [] @@ -20,7 +22,7 @@ shuffle(game_recs) class RecommendGame(commands.Cog): """Commands related to recommending games.""" - def __init__(self, bot: commands.Bot) -> None: + def __init__(self, bot: Bot) -> None: self.bot = bot self.index = 0 @@ -45,6 +47,6 @@ class RecommendGame(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Loads the RecommendGame cog.""" bot.add_cog(RecommendGame(bot)) diff --git a/bot/exts/evergreen/reddit.py b/bot/exts/evergreen/reddit.py index 49127bea..ea77123e 100644 --- a/bot/exts/evergreen/reddit.py +++ b/bot/exts/evergreen/reddit.py @@ -5,6 +5,7 @@ import discord from discord.ext import commands from discord.ext.commands.cooldowns import BucketType +from bot.bot import Bot from bot.utils.pagination import ImagePaginator log = logging.getLogger(__name__) @@ -13,7 +14,7 @@ log = logging.getLogger(__name__) class Reddit(commands.Cog): """Fetches reddit posts.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot async def fetch(self, url: str) -> dict: @@ -123,6 +124,6 @@ class Reddit(commands.Cog): await ImagePaginator.paginate(pages, ctx, embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the Cog.""" bot.add_cog(Reddit(bot)) diff --git a/bot/exts/evergreen/source.py b/bot/exts/evergreen/source.py index 45752bf9..3e6031a5 100644 --- a/bot/exts/evergreen/source.py +++ b/bot/exts/evergreen/source.py @@ -5,6 +5,7 @@ from typing import Optional, Tuple, Union from discord import Embed from discord.ext import commands +from bot.bot import Bot from bot.constants import Source SourceType = Union[commands.Command, commands.Cog, str, commands.ExtensionNotLoaded] @@ -31,7 +32,7 @@ class SourceConverter(commands.Converter): class BotSource(commands.Cog): """Displays information about the bot's source code.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.command(name="source", aliases=("src",)) @@ -104,6 +105,6 @@ class BotSource(commands.Cog): return embed -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the BotSource cog.""" bot.add_cog(BotSource(bot)) diff --git a/bot/exts/evergreen/speedrun.py b/bot/exts/evergreen/speedrun.py index 21aad5aa..27d944ca 100644 --- a/bot/exts/evergreen/speedrun.py +++ b/bot/exts/evergreen/speedrun.py @@ -5,6 +5,8 @@ from random import choice from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) with Path('bot/resources/evergreen/speedrun_links.json').open(encoding="utf8") as file: LINKS = json.load(file) @@ -13,7 +15,7 @@ with Path('bot/resources/evergreen/speedrun_links.json').open(encoding="utf8") a class Speedrun(commands.Cog): """Commands about the video game speedrunning community.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.command(name="speedrun") @@ -22,6 +24,6 @@ class Speedrun(commands.Cog): await ctx.send(choice(LINKS)) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the Speedrun cog.""" bot.add_cog(Speedrun(bot)) diff --git a/bot/exts/evergreen/status_codes.py b/bot/exts/evergreen/status_codes.py index 7c00fe20..635eef3d 100644 --- a/bot/exts/evergreen/status_codes.py +++ b/bot/exts/evergreen/status_codes.py @@ -3,6 +3,7 @@ from http import HTTPStatus import discord from discord.ext import commands +from bot.bot import Bot from bot.utils.extensions import invoke_help_command HTTP_DOG_URL = "https://httpstatusdogs.com/img/{code}.jpg" @@ -12,7 +13,7 @@ HTTP_CAT_URL = "https://http.cat/{code}.jpg" class HTTPStatusCodes(commands.Cog): """Commands that give HTTP statuses described and visualized by cats and dogs.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.group(name="http_status", aliases=("status", "httpstatus")) @@ -68,6 +69,6 @@ class HTTPStatusCodes(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the HTTPStatusCodes cog.""" bot.add_cog(HTTPStatusCodes(bot)) diff --git a/bot/exts/evergreen/timed.py b/bot/exts/evergreen/timed.py index 5f177fd6..35ca807c 100644 --- a/bot/exts/evergreen/timed.py +++ b/bot/exts/evergreen/timed.py @@ -4,6 +4,8 @@ from time import perf_counter from discord import Message from discord.ext import commands +from bot.bot import Bot + class TimedCommands(commands.Cog): """Time the command execution of a command.""" @@ -41,6 +43,6 @@ class TimedCommands(commands.Cog): await ctx.send(f"Command execution for `{new_ctx.command}` finished in {(t_end - t_start):.4f} seconds.") -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Cog load.""" bot.add_cog(TimedCommands(bot)) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index fe692c2a..080f5b6f 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -8,6 +8,7 @@ import discord from discord.ext import commands from fuzzywuzzy import fuzz +from bot.bot import Bot from bot.constants import Roles @@ -23,7 +24,7 @@ WRONG_ANS_RESPONSE = [ class TriviaQuiz(commands.Cog): """A cog for all quiz commands.""" - def __init__(self, bot: commands.Bot) -> None: + def __init__(self, bot: Bot) -> None: self.bot = bot self.questions = self.load_questions() self.game_status = {} # A variable to store the game status: either running or not running. @@ -299,6 +300,6 @@ class TriviaQuiz(commands.Cog): await channel.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the cog.""" bot.add_cog(TriviaQuiz(bot)) diff --git a/bot/exts/evergreen/uptime.py b/bot/exts/evergreen/uptime.py index a9ad9dfb..b8813bc7 100644 --- a/bot/exts/evergreen/uptime.py +++ b/bot/exts/evergreen/uptime.py @@ -5,6 +5,7 @@ from dateutil.relativedelta import relativedelta from discord.ext import commands from bot import start_time +from bot.bot import Bot log = logging.getLogger(__name__) @@ -12,7 +13,7 @@ log = logging.getLogger(__name__) class Uptime(commands.Cog): """A cog for posting the bot's uptime.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.command(name="uptime") @@ -28,6 +29,6 @@ class Uptime(commands.Cog): await ctx.send(f"I started up {uptime_string}.") -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Uptime Cog load.""" bot.add_cog(Uptime(bot)) diff --git a/bot/exts/evergreen/wolfram.py b/bot/exts/evergreen/wolfram.py index 14ec1041..c4c69070 100644 --- a/bot/exts/evergreen/wolfram.py +++ b/bot/exts/evergreen/wolfram.py @@ -9,6 +9,7 @@ from discord import Embed from discord.ext import commands from discord.ext.commands import BucketType, Cog, Context, check, group +from bot.bot import Bot from bot.constants import Colours, STAFF_ROLES, Wolfram from bot.utils.pagination import ImagePaginator @@ -102,7 +103,7 @@ def custom_cooldown(*ignore: List[int]) -> Callable: return check(predicate) -async def get_pod_pages(ctx: Context, bot: commands.Bot, query: str) -> Optional[List[Tuple]]: +async def get_pod_pages(ctx: Context, bot: Bot, query: str) -> Optional[List[Tuple]]: """Get the Wolfram API pod pages for the provided query.""" async with ctx.channel.typing(): url_str = parse.urlencode({ @@ -162,7 +163,7 @@ async def get_pod_pages(ctx: Context, bot: commands.Bot, query: str) -> Optional class Wolfram(Cog): """Commands for interacting with the Wolfram|Alpha API.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @group(name="wolfram", aliases=("wolf", "wa"), invoke_without_command=True) @@ -283,6 +284,6 @@ class Wolfram(Cog): await send_embed(ctx, message, color) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the Wolfram cog.""" bot.add_cog(Wolfram(bot)) diff --git a/bot/exts/evergreen/wonder_twins.py b/bot/exts/evergreen/wonder_twins.py index afc5346e..80b9bb4d 100644 --- a/bot/exts/evergreen/wonder_twins.py +++ b/bot/exts/evergreen/wonder_twins.py @@ -2,7 +2,9 @@ import random from pathlib import Path import yaml -from discord.ext.commands import Bot, Cog, Context, command +from discord.ext.commands import Cog, Context, command + +from bot.bot import Bot class WonderTwins(Cog): -- cgit v1.2.3 From 713396a91859d914478e417ee6ab9e0a26ee6cf5 Mon Sep 17 00:00:00 2001 From: vcokltfre Date: Mon, 19 Apr 2021 20:56:53 +0100 Subject: chore(evergreen): format each cog load docstring the same way --- bot/exts/evergreen/8bitify.py | 2 +- bot/exts/evergreen/battleship.py | 2 +- bot/exts/evergreen/conversationstarters.py | 2 +- bot/exts/evergreen/emoji.py | 2 +- bot/exts/evergreen/error_handler.py | 2 +- bot/exts/evergreen/fun.py | 2 +- bot/exts/evergreen/game.py | 2 +- bot/exts/evergreen/githubinfo.py | 2 +- bot/exts/evergreen/issues.py | 2 +- bot/exts/evergreen/magic_8ball.py | 2 +- bot/exts/evergreen/movie.py | 2 +- bot/exts/evergreen/ping.py | 2 +- bot/exts/evergreen/pythonfacts.py | 2 +- bot/exts/evergreen/reddit.py | 2 +- bot/exts/evergreen/space.py | 2 +- bot/exts/evergreen/tic_tac_toe.py | 2 +- bot/exts/evergreen/timed.py | 2 +- bot/exts/evergreen/trivia_quiz.py | 2 +- bot/exts/evergreen/uptime.py | 2 +- bot/exts/evergreen/wikipedia.py | 2 +- bot/exts/evergreen/xkcd.py | 2 +- 21 files changed, 21 insertions(+), 21 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/8bitify.py b/bot/exts/evergreen/8bitify.py index 621aa875..09a3eb5c 100644 --- a/bot/exts/evergreen/8bitify.py +++ b/bot/exts/evergreen/8bitify.py @@ -53,5 +53,5 @@ class EightBitify(commands.Cog): def setup(bot: Bot) -> None: - """Cog load.""" + """Cog the EightBitify load.""" bot.add_cog(EightBitify(bot)) diff --git a/bot/exts/evergreen/battleship.py b/bot/exts/evergreen/battleship.py index f255afb9..ca0e3881 100644 --- a/bot/exts/evergreen/battleship.py +++ b/bot/exts/evergreen/battleship.py @@ -440,5 +440,5 @@ class Battleship(commands.Cog): def setup(bot: Bot) -> None: - """Cog load.""" + """Load the Battleship cog""" bot.add_cog(Battleship(bot)) diff --git a/bot/exts/evergreen/conversationstarters.py b/bot/exts/evergreen/conversationstarters.py index aed76bcf..04194c01 100644 --- a/bot/exts/evergreen/conversationstarters.py +++ b/bot/exts/evergreen/conversationstarters.py @@ -68,5 +68,5 @@ class ConvoStarters(commands.Cog): def setup(bot: Bot) -> None: - """Conversation starters Cog load.""" + """Load the ConvoStarters cog.""" bot.add_cog(ConvoStarters(bot)) diff --git a/bot/exts/evergreen/emoji.py b/bot/exts/evergreen/emoji.py index 58d9be03..45b77e16 100644 --- a/bot/exts/evergreen/emoji.py +++ b/bot/exts/evergreen/emoji.py @@ -122,5 +122,5 @@ class Emojis(commands.Cog): def setup(bot: Bot) -> None: - """Add the Emojis cog into the bot.""" + """Load the Emojis cog.""" bot.add_cog(Emojis(bot)) diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index 053e3866..64460822 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -137,5 +137,5 @@ class CommandErrorHandler(commands.Cog): def setup(bot: Bot) -> None: - """Error handler Cog load.""" + """Load the ErrorHandler cog.""" bot.add_cog(CommandErrorHandler(bot)) diff --git a/bot/exts/evergreen/fun.py b/bot/exts/evergreen/fun.py index cde37895..c7b0d7d9 100644 --- a/bot/exts/evergreen/fun.py +++ b/bot/exts/evergreen/fun.py @@ -241,5 +241,5 @@ class Fun(Cog): def setup(bot: Bot) -> None: - """Fun Cog load.""" + """Load the Fun cog.""" bot.add_cog(Fun(bot)) diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 068d3f68..24872e76 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -471,7 +471,7 @@ class Games(Cog): def setup(bot: Bot) -> None: - """Add/Load Games cog.""" + """Load the Games cog.""" # Check does IGDB API key exist, if not, log warning and don't load cog if not Tokens.igdb_client_id: logger.warning("No IGDB client ID. Not loading Games cog.") diff --git a/bot/exts/evergreen/githubinfo.py b/bot/exts/evergreen/githubinfo.py index da6eba5c..65fcc7cf 100644 --- a/bot/exts/evergreen/githubinfo.py +++ b/bot/exts/evergreen/githubinfo.py @@ -172,5 +172,5 @@ class GithubInfo(commands.Cog): def setup(bot: Bot) -> None: - """Adding the cog to the bot.""" + """Load the GithubInfo cog.""" bot.add_cog(GithubInfo(bot)) diff --git a/bot/exts/evergreen/issues.py b/bot/exts/evergreen/issues.py index 692e0b43..d7ee99c0 100644 --- a/bot/exts/evergreen/issues.py +++ b/bot/exts/evergreen/issues.py @@ -271,5 +271,5 @@ class Issues(commands.Cog): def setup(bot: Bot) -> None: - """Cog Retrieves Issues From Github.""" + """Load the Issues cog.""" bot.add_cog(Issues(bot)) diff --git a/bot/exts/evergreen/magic_8ball.py b/bot/exts/evergreen/magic_8ball.py index 2dfe237a..61c68693 100644 --- a/bot/exts/evergreen/magic_8ball.py +++ b/bot/exts/evergreen/magic_8ball.py @@ -29,5 +29,5 @@ class Magic8ball(commands.Cog): def setup(bot: Bot) -> None: - """Magic 8ball Cog load.""" + """Load the Magic8Ball cog.""" bot.add_cog(Magic8ball(bot)) diff --git a/bot/exts/evergreen/movie.py b/bot/exts/evergreen/movie.py index f4356f33..0d535b03 100644 --- a/bot/exts/evergreen/movie.py +++ b/bot/exts/evergreen/movie.py @@ -199,5 +199,5 @@ class Movie(Cog): def setup(bot: Bot) -> None: - """Load Movie Cog.""" + """Load the Movie Cog.""" bot.add_cog(Movie(bot)) diff --git a/bot/exts/evergreen/ping.py b/bot/exts/evergreen/ping.py index 1332e3e6..71152d15 100644 --- a/bot/exts/evergreen/ping.py +++ b/bot/exts/evergreen/ping.py @@ -24,5 +24,5 @@ class Ping(commands.Cog): def setup(bot: Bot) -> None: - """Cog load.""" + """Load the Ping cog.""" bot.add_cog(Ping(bot)) diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index bbc4eb17..1dd9b40d 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -30,5 +30,5 @@ class PythonFacts(commands.Cog): def setup(bot: Bot) -> None: - """Load PythonFacts Cog.""" + """Load the PythonFacts Cog.""" bot.add_cog(PythonFacts(bot)) diff --git a/bot/exts/evergreen/reddit.py b/bot/exts/evergreen/reddit.py index ea77123e..ce22a864 100644 --- a/bot/exts/evergreen/reddit.py +++ b/bot/exts/evergreen/reddit.py @@ -125,5 +125,5 @@ class Reddit(commands.Cog): def setup(bot: Bot) -> None: - """Load the Cog.""" + """Load the Reddit cog.""" bot.add_cog(Reddit(bot)) diff --git a/bot/exts/evergreen/space.py b/bot/exts/evergreen/space.py index 323ff659..b3f0016b 100644 --- a/bot/exts/evergreen/space.py +++ b/bot/exts/evergreen/space.py @@ -242,7 +242,7 @@ class Space(Cog): def setup(bot: Bot) -> None: - """Load Space Cog.""" + """Load the Space cog.""" if not Tokens.nasa: logger.warning("Can't find NASA API key. Not loading Space Cog.") return diff --git a/bot/exts/evergreen/tic_tac_toe.py b/bot/exts/evergreen/tic_tac_toe.py index 6e21528e..15cc1ef3 100644 --- a/bot/exts/evergreen/tic_tac_toe.py +++ b/bot/exts/evergreen/tic_tac_toe.py @@ -323,5 +323,5 @@ class TicTacToe(Cog): def setup(bot: Bot) -> None: - """Load TicTacToe Cog.""" + """Load the TicTacToe cog.""" bot.add_cog(TicTacToe(bot)) diff --git a/bot/exts/evergreen/timed.py b/bot/exts/evergreen/timed.py index 35ca807c..42a77346 100644 --- a/bot/exts/evergreen/timed.py +++ b/bot/exts/evergreen/timed.py @@ -44,5 +44,5 @@ class TimedCommands(commands.Cog): def setup(bot: Bot) -> None: - """Cog load.""" + """Load the Timed cog.""" bot.add_cog(TimedCommands(bot)) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 080f5b6f..f40375a6 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -301,5 +301,5 @@ class TriviaQuiz(commands.Cog): def setup(bot: Bot) -> None: - """Load the cog.""" + """Load the TriviaQuiz cog.""" bot.add_cog(TriviaQuiz(bot)) diff --git a/bot/exts/evergreen/uptime.py b/bot/exts/evergreen/uptime.py index b8813bc7..c22af2c9 100644 --- a/bot/exts/evergreen/uptime.py +++ b/bot/exts/evergreen/uptime.py @@ -30,5 +30,5 @@ class Uptime(commands.Cog): def setup(bot: Bot) -> None: - """Uptime Cog load.""" + """Load the Uptime cog.""" bot.add_cog(Uptime(bot)) diff --git a/bot/exts/evergreen/wikipedia.py b/bot/exts/evergreen/wikipedia.py index 068c4f43..e2172fc3 100644 --- a/bot/exts/evergreen/wikipedia.py +++ b/bot/exts/evergreen/wikipedia.py @@ -90,5 +90,5 @@ class WikipediaSearch(commands.Cog): def setup(bot: Bot) -> None: - """Wikipedia Cog load.""" + """Load the WikipediaSearch cog.""" bot.add_cog(WikipediaSearch(bot)) diff --git a/bot/exts/evergreen/xkcd.py b/bot/exts/evergreen/xkcd.py index 1ff98ca2..ba9e46e0 100644 --- a/bot/exts/evergreen/xkcd.py +++ b/bot/exts/evergreen/xkcd.py @@ -87,5 +87,5 @@ class XKCD(Cog): def setup(bot: Bot) -> None: - """Loading the XKCD cog.""" + """Load the XKCD cog.""" bot.add_cog(XKCD(bot)) -- cgit v1.2.3 From 227d0a7705e08b74deb9b95ec4f643b1d0a0fcdd Mon Sep 17 00:00:00 2001 From: vcokltfre Date: Mon, 19 Apr 2021 21:09:10 +0100 Subject: chore(evergreen): make usage of . at sentence ends consistent --- bot/exts/evergreen/battleship.py | 6 +++--- bot/exts/evergreen/bookmark.py | 4 ++-- bot/exts/evergreen/connect_four.py | 2 +- bot/exts/evergreen/emoji.py | 2 +- bot/exts/evergreen/githubinfo.py | 2 +- bot/exts/evergreen/minesweeper.py | 10 +++++----- bot/exts/evergreen/wolfram.py | 12 ++++++------ 7 files changed, 19 insertions(+), 19 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/battleship.py b/bot/exts/evergreen/battleship.py index ca0e3881..813f998e 100644 --- a/bot/exts/evergreen/battleship.py +++ b/bot/exts/evergreen/battleship.py @@ -238,7 +238,7 @@ class Game: square = None turn_message = await self.turn.user.send( "It's your turn! Type the square you want to fire at. Format it like this: A1\n" - "Type `surrender` to give up" + "Type `surrender` to give up." ) await self.next.user.send("Their turn", delete_after=3.0) while True: @@ -382,7 +382,7 @@ class Battleship(commands.Cog): return await ctx.send("You're already playing a game!") if ctx.author in self.waiting: - return await ctx.send("You've already sent out a request for a player 2") + return await ctx.send("You've already sent out a request for a player 2.") announcement = await ctx.send( "**Battleship**: A new game is about to start!\n" @@ -426,7 +426,7 @@ class Battleship(commands.Cog): self.games.remove(game) except Exception: # End the game in the event of an unforseen error so the players aren't stuck in a game - await ctx.send(f"{ctx.author.mention} {user.mention} An error occurred. Game failed") + await ctx.send(f"{ctx.author.mention} {user.mention} An error occurred. Game failed.") self.games.remove(game) raise diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 329838b9..ec25e7a7 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -29,7 +29,7 @@ class Bookmark(commands.Cog): # Prevent users from bookmarking a message in a channel they don't have access to permissions = ctx.author.permissions_in(target_message.channel) if not permissions.read_messages: - log.info(f"{ctx.author} tried to bookmark a message in #{target_message.channel} but has no permissions") + log.info(f"{ctx.author} tried to bookmark a message in #{target_message.channel} but has no permissions.") embed = discord.Embed( title=random.choice(ERROR_REPLIES), color=Colours.soft_red, @@ -52,7 +52,7 @@ class Bookmark(commands.Cog): except discord.Forbidden: error_embed = discord.Embed( title=random.choice(ERROR_REPLIES), - description=f"{ctx.author.mention}, please enable your DMs to receive the bookmark", + description=f"{ctx.author.mention}, please enable your DMs to receive the bookmark.", colour=Colours.soft_red ) await ctx.send(embed=error_embed) diff --git a/bot/exts/evergreen/connect_four.py b/bot/exts/evergreen/connect_four.py index fbb13780..df2a913a 100644 --- a/bot/exts/evergreen/connect_four.py +++ b/bot/exts/evergreen/connect_four.py @@ -355,7 +355,7 @@ class ConnectFour(commands.Cog): self.games.remove(game) except Exception: # End the game in the event of an unforeseen error so the players aren't stuck in a game - await ctx.send(f"{ctx.author.mention} {user.mention if user else ''} An error occurred. Game failed") + await ctx.send(f"{ctx.author.mention} {user.mention if user else ''} An error occurred. Game failed.") if game in self.games: self.games.remove(game) raise diff --git a/bot/exts/evergreen/emoji.py b/bot/exts/evergreen/emoji.py index 45b77e16..7ceb6c8d 100644 --- a/bot/exts/evergreen/emoji.py +++ b/bot/exts/evergreen/emoji.py @@ -87,7 +87,7 @@ class Emojis(commands.Cog): if not ctx.guild.emojis: await ctx.send("No emojis found.") return - log.trace(f"Emoji Category {'' if category_query else 'not '}provided by the user") + log.trace(f"Emoji Category {'' if category_query else 'not '}provided by the user.") for emoji in ctx.guild.emojis: emoji_category = emoji.name.split("_")[0] diff --git a/bot/exts/evergreen/githubinfo.py b/bot/exts/evergreen/githubinfo.py index 65fcc7cf..fd100a7c 100644 --- a/bot/exts/evergreen/githubinfo.py +++ b/bot/exts/evergreen/githubinfo.py @@ -96,7 +96,7 @@ class GithubInfo(commands.Cog): embed.add_field( name=f"Organization{'s' if len(orgs)!=1 else ''}", - value=orgs_to_add if orgs else "No organizations" + value=orgs_to_add if orgs else "No organizations." ) embed.add_field(name="Website", value=blog) diff --git a/bot/exts/evergreen/minesweeper.py b/bot/exts/evergreen/minesweeper.py index 7c1bac3b..bba349fa 100644 --- a/bot/exts/evergreen/minesweeper.py +++ b/bot/exts/evergreen/minesweeper.py @@ -38,7 +38,7 @@ class CoordinateConverter(commands.Converter): async def convert(self, ctx: commands.Context, coordinate: str) -> typing.Tuple[int, int]: """Take in a coordinate string and turn it into an (x, y) tuple.""" if not 2 <= len(coordinate) <= 3: - raise commands.BadArgument('Invalid co-ordinate provided') + raise commands.BadArgument('Invalid co-ordinate provided.') coordinate = coordinate.lower() if coordinate[0].isalpha(): @@ -149,7 +149,7 @@ class Minesweeper(commands.Cog): f"Close the game with `{Client.prefix}ms end`\n" ) except discord.errors.Forbidden: - log.debug(f"{ctx.author.name} ({ctx.author.id}) has disabled DMs from server members") + log.debug(f"{ctx.author.name} ({ctx.author.id}) has disabled DMs from server members.") await ctx.send(f":x: {ctx.author.mention}, please enable DMs to play minesweeper.") return @@ -159,7 +159,7 @@ class Minesweeper(commands.Cog): dm_msg = await ctx.author.send(f"Here's your board!\n{self.format_for_discord(revealed_board)}") if ctx.guild: - await ctx.send(f"{ctx.author.mention} is playing Minesweeper") + await ctx.send(f"{ctx.author.mention} is playing Minesweeper.") chat_msg = await ctx.send(f"Here's their board!\n{self.format_for_discord(revealed_board)}") else: chat_msg = None @@ -248,7 +248,7 @@ class Minesweeper(commands.Cog): """ Reveal one square. - return is True if the game ended, breaking the loop in `reveal_command` and deleting the game + return is True if the game ended, breaking the loop in `reveal_command` and deleting the game. """ revealed[y][x] = board[y][x] if board[y][x] == "bomb": @@ -286,7 +286,7 @@ class Minesweeper(commands.Cog): game = self.games[ctx.author.id] game.revealed = game.board await self.update_boards(ctx) - new_msg = f":no_entry: Game canceled :no_entry:\n{game.dm_msg.content}" + new_msg = f":no_entry: Game canceled. :no_entry:\n{game.dm_msg.content}" await game.dm_msg.edit(content=new_msg) if game.activated_on_server: await game.chat_msg.edit(content=new_msg) diff --git a/bot/exts/evergreen/wolfram.py b/bot/exts/evergreen/wolfram.py index c4c69070..c57a8d7a 100644 --- a/bot/exts/evergreen/wolfram.py +++ b/bot/exts/evergreen/wolfram.py @@ -56,7 +56,7 @@ def custom_cooldown(*ignore: List[int]) -> Callable: """ Implement per-user and per-guild cooldowns for requests to the Wolfram API. - A list of roles may be provided to ignore the per-user cooldown + A list of roles may be provided to ignore the per-user cooldown. """ async def predicate(ctx: Context) -> bool: if ctx.invoked_with == 'help': @@ -189,11 +189,11 @@ class Wolfram(Cog): image_url = "attachment://image.png" if status == 501: - message = "Failed to get response" + message = "Failed to get response." footer = "" color = Colours.soft_red elif status == 400: - message = "No input found" + message = "No input found." footer = "" color = Colours.soft_red elif status == 403: @@ -269,12 +269,12 @@ class Wolfram(Cog): response_text = await response.text() if status == 501: - message = "Failed to get response" + message = "Failed to get response." color = Colours.soft_red elif status == 400: - message = "No input found" + message = "No input found." color = Colours.soft_red - elif response_text == "Error 1: Invalid appid": + elif response_text == "Error 1: Invalid appid.": message = "Wolfram API key is invalid or missing." color = Colours.soft_red else: -- cgit v1.2.3 From f919e0cdb9cff71c187f55ea4447ef4934c5b9ab Mon Sep 17 00:00:00 2001 From: vcokltfre Date: Mon, 19 Apr 2021 21:17:10 +0100 Subject: chore(evergreen): remove unneeded cog constructors --- bot/exts/evergreen/bookmark.py | 3 --- bot/exts/evergreen/conversationstarters.py | 3 --- bot/exts/evergreen/emoji.py | 3 --- bot/exts/evergreen/error_handler.py | 3 --- bot/exts/evergreen/magic_8ball.py | 3 +-- bot/exts/evergreen/minesweeper.py | 2 +- bot/exts/evergreen/movie.py | 1 - bot/exts/evergreen/pythonfacts.py | 3 --- bot/exts/evergreen/source.py | 3 --- bot/exts/evergreen/space.py | 1 - bot/exts/evergreen/speedrun.py | 3 --- bot/exts/evergreen/tic_tac_toe.py | 3 +-- bot/exts/evergreen/uptime.py | 3 --- bot/exts/evergreen/wonder_twins.py | 4 +--- 14 files changed, 4 insertions(+), 34 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index ec25e7a7..6a272784 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -14,9 +14,6 @@ log = logging.getLogger(__name__) class Bookmark(commands.Cog): """Creates personal bookmarks by relaying a message link to the user's DMs.""" - def __init__(self, bot: Bot): - self.bot = bot - @commands.command(name="bookmark", aliases=("bm", "pin")) async def bookmark( self, diff --git a/bot/exts/evergreen/conversationstarters.py b/bot/exts/evergreen/conversationstarters.py index 04194c01..54fea0b3 100644 --- a/bot/exts/evergreen/conversationstarters.py +++ b/bot/exts/evergreen/conversationstarters.py @@ -35,9 +35,6 @@ TOPICS = { class ConvoStarters(commands.Cog): """Evergreen conversation topics.""" - def __init__(self, bot: Bot): - self.bot = bot - @commands.command() @whitelist_override(channels=ALL_ALLOWED_CHANNELS) async def topic(self, ctx: commands.Context) -> None: diff --git a/bot/exts/evergreen/emoji.py b/bot/exts/evergreen/emoji.py index 7ceb6c8d..8e540712 100644 --- a/bot/exts/evergreen/emoji.py +++ b/bot/exts/evergreen/emoji.py @@ -20,9 +20,6 @@ log = logging.getLogger(__name__) class Emojis(commands.Cog): """A collection of commands related to emojis in the server.""" - def __init__(self, bot: Bot): - self.bot = bot - @staticmethod def embed_builder(emoji: dict) -> Tuple[Embed, List[str]]: """Generates an embed with the emoji names and count.""" diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index 64460822..dabd0ab5 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -18,9 +18,6 @@ log = logging.getLogger(__name__) class CommandErrorHandler(commands.Cog): """A error handler for the PythonDiscord server.""" - def __init__(self, bot: Bot): - self.bot = bot - @staticmethod def revert_cooldown_counter(command: commands.Command, message: Message) -> None: """Undoes the last cooldown counter for user-error cases.""" diff --git a/bot/exts/evergreen/magic_8ball.py b/bot/exts/evergreen/magic_8ball.py index 61c68693..708aa6d2 100644 --- a/bot/exts/evergreen/magic_8ball.py +++ b/bot/exts/evergreen/magic_8ball.py @@ -13,8 +13,7 @@ log = logging.getLogger(__name__) class Magic8ball(commands.Cog): """A Magic 8ball command to respond to a user's question.""" - def __init__(self, bot: Bot): - self.bot = bot + def __init__(self, _bot: Bot): with open(Path("bot/resources/evergreen/magic8ball.json"), "r", encoding="utf8") as file: self.answers = json.load(file) diff --git a/bot/exts/evergreen/minesweeper.py b/bot/exts/evergreen/minesweeper.py index bba349fa..d0cc28c5 100644 --- a/bot/exts/evergreen/minesweeper.py +++ b/bot/exts/evergreen/minesweeper.py @@ -79,7 +79,7 @@ GamesDict = typing.Dict[int, Game] class Minesweeper(commands.Cog): """Play a game of Minesweeper.""" - def __init__(self, bot: Bot) -> None: + def __init__(self, _bot: Bot) -> None: self.games: GamesDict = {} # Store the currently running games @commands.group(name='minesweeper', aliases=('ms',), invoke_without_command=True) diff --git a/bot/exts/evergreen/movie.py b/bot/exts/evergreen/movie.py index 0d535b03..488e5142 100644 --- a/bot/exts/evergreen/movie.py +++ b/bot/exts/evergreen/movie.py @@ -51,7 +51,6 @@ class Movie(Cog): """Movie Cog contains movies command that grab random movies from TMDB.""" def __init__(self, bot: Bot): - self.bot = bot self.http_session: ClientSession = bot.http_session @group(name='movies', aliases=['movie'], invoke_without_command=True) diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index 1dd9b40d..73234d55 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -15,9 +15,6 @@ COLORS = itertools.cycle([Colours.python_blue, Colours.python_yellow]) class PythonFacts(commands.Cog): """Sends a random fun fact about Python.""" - def __init__(self, bot: Bot) -> None: - self.bot = bot - @commands.command(name='pythonfact', aliases=['pyfact']) async def get_python_fact(self, ctx: commands.Context) -> None: """Sends a Random fun fact about Python.""" diff --git a/bot/exts/evergreen/source.py b/bot/exts/evergreen/source.py index 3e6031a5..14fd02f3 100644 --- a/bot/exts/evergreen/source.py +++ b/bot/exts/evergreen/source.py @@ -32,9 +32,6 @@ class SourceConverter(commands.Converter): class BotSource(commands.Cog): """Displays information about the bot's source code.""" - def __init__(self, bot: Bot): - self.bot = bot - @commands.command(name="source", aliases=("src",)) async def source_command(self, ctx: commands.Context, *, source_item: SourceConverter = None) -> None: """Display information and a GitHub link to the source code of a command, tag, or cog.""" diff --git a/bot/exts/evergreen/space.py b/bot/exts/evergreen/space.py index b3f0016b..ee9ad38c 100644 --- a/bot/exts/evergreen/space.py +++ b/bot/exts/evergreen/space.py @@ -39,7 +39,6 @@ class Space(Cog): """Space Cog contains commands, that show images, facts or other information about space.""" def __init__(self, bot: Bot): - self.bot = bot self.http_session = bot.http_session self.rovers = {} diff --git a/bot/exts/evergreen/speedrun.py b/bot/exts/evergreen/speedrun.py index 27d944ca..bf6f2117 100644 --- a/bot/exts/evergreen/speedrun.py +++ b/bot/exts/evergreen/speedrun.py @@ -15,9 +15,6 @@ with Path('bot/resources/evergreen/speedrun_links.json').open(encoding="utf8") a class Speedrun(commands.Cog): """Commands about the video game speedrunning community.""" - def __init__(self, bot: Bot): - self.bot = bot - @commands.command(name="speedrun") async def get_speedrun(self, ctx: commands.Context) -> None: """Sends a link to a video of a random speedrun.""" diff --git a/bot/exts/evergreen/tic_tac_toe.py b/bot/exts/evergreen/tic_tac_toe.py index 15cc1ef3..1fef427a 100644 --- a/bot/exts/evergreen/tic_tac_toe.py +++ b/bot/exts/evergreen/tic_tac_toe.py @@ -246,8 +246,7 @@ def is_requester_free() -> t.Callable: class TicTacToe(Cog): """TicTacToe cog contains tic-tac-toe game commands.""" - def __init__(self, bot: Bot): - self.bot = bot + def __init__(self, _bot: Bot): self.games: t.List[Game] = [] @guild_only() diff --git a/bot/exts/evergreen/uptime.py b/bot/exts/evergreen/uptime.py index c22af2c9..d2509e6f 100644 --- a/bot/exts/evergreen/uptime.py +++ b/bot/exts/evergreen/uptime.py @@ -13,9 +13,6 @@ log = logging.getLogger(__name__) class Uptime(commands.Cog): """A cog for posting the bot's uptime.""" - def __init__(self, bot: Bot): - self.bot = bot - @commands.command(name="uptime") async def uptime(self, ctx: commands.Context) -> None: """Responds with the uptime of the bot.""" diff --git a/bot/exts/evergreen/wonder_twins.py b/bot/exts/evergreen/wonder_twins.py index 80b9bb4d..9fa2d7f8 100644 --- a/bot/exts/evergreen/wonder_twins.py +++ b/bot/exts/evergreen/wonder_twins.py @@ -10,9 +10,7 @@ from bot.bot import Bot class WonderTwins(Cog): """Cog for a Wonder Twins inspired command.""" - def __init__(self, bot: Bot): - self.bot = bot - + def __init__(self, _bot: Bot): with open(Path.cwd() / "bot" / "resources" / "evergreen" / "wonder_twins.yaml", "r", encoding="utf-8") as f: info = yaml.load(f, Loader=yaml.FullLoader) self.water_types = info["water_types"] -- cgit v1.2.3 From ae64ddd3e7d731a44a1684c93d67ea6334b120d2 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Mon, 19 Apr 2021 17:04:11 -0400 Subject: Clean Up the Halloween Season - Change commands.Bot type hints to bot.Bot - Remove the setting of Cog.bot if it isn't being used - Use Bot.http_session instead of creating new ones - Keep string quotes and Doc-Strings consistant - Remove redundant/outdated code Ignored spookyavatar.py as it is being moved in another PR. --- bot/exts/halloween/8ball.py | 17 ++--- bot/exts/halloween/candy_collection.py | 35 +++++---- bot/exts/halloween/hacktober-issue-finder.py | 73 +++++++++--------- bot/exts/halloween/hacktoberstats.py | 108 ++++++++++++--------------- bot/exts/halloween/halloween_facts.py | 15 ++-- bot/exts/halloween/halloweenify.py | 13 ++-- bot/exts/halloween/monsterbio.py | 10 +-- bot/exts/halloween/monstersurvey.py | 6 +- bot/exts/halloween/scarymovie.py | 74 +++++++++--------- bot/exts/halloween/spookygif.py | 23 +++--- bot/exts/halloween/spookynamerate.py | 21 +++--- bot/exts/halloween/spookyrating.py | 14 ++-- bot/exts/halloween/spookyreact.py | 29 +++---- bot/exts/halloween/timeleft.py | 8 +- 14 files changed, 216 insertions(+), 230 deletions(-) (limited to 'bot') diff --git a/bot/exts/halloween/8ball.py b/bot/exts/halloween/8ball.py index 1df48fbf..59d4acc5 100644 --- a/bot/exts/halloween/8ball.py +++ b/bot/exts/halloween/8ball.py @@ -6,28 +6,27 @@ from pathlib import Path from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) -with open(Path("bot/resources/halloween/responses.json"), "r", encoding="utf8") as f: - responses = json.load(f) +with Path("bot/resources/halloween/responses.json").open("r", encoding="utf8") as f: + RESPONSES = json.load(f) class SpookyEightBall(commands.Cog): """Spooky Eightball answers.""" - def __init__(self, bot: commands.Bot): - self.bot = bot - @commands.command(aliases=('spooky8ball',)) async def spookyeightball(self, ctx: commands.Context, *, question: str) -> None: """Responds with a random response to a question.""" - choice = random.choice(responses['responses']) + choice = random.choice(RESPONSES["responses"]) msg = await ctx.send(choice[0]) if len(choice) > 1: await asyncio.sleep(random.randint(2, 5)) await msg.edit(content=f"{choice[0]} \n{choice[1]}") -def setup(bot: commands.Bot) -> None: - """Spooky Eight Ball Cog Load.""" - bot.add_cog(SpookyEightBall(bot)) +def setup(bot: Bot) -> None: + """Load the Spooky Eight Ball Cog.""" + bot.add_cog(SpookyEightBall()) diff --git a/bot/exts/halloween/candy_collection.py b/bot/exts/halloween/candy_collection.py index 40e21f40..5441d8a5 100644 --- a/bot/exts/halloween/candy_collection.py +++ b/bot/exts/halloween/candy_collection.py @@ -6,6 +6,7 @@ import discord from async_rediscache import RedisCache from discord.ext import commands +from bot.bot import Bot from bot.constants import Channels, Month from bot.utils.decorators import in_month @@ -40,7 +41,7 @@ class CandyCollection(commands.Cog): candy_messages = RedisCache() skull_messages = RedisCache() - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @in_month(Month.OCTOBER) @@ -60,15 +61,15 @@ class CandyCollection(commands.Cog): # do random check for skull first as it has the lower chance if random.randint(1, ADD_SKULL_REACTION_CHANCE) == 1: await self.skull_messages.set(message.id, "skull") - return await message.add_reaction(EMOJIS['SKULL']) + await message.add_reaction(EMOJIS["SKULL"]) # check for the candy chance next - if random.randint(1, ADD_CANDY_REACTION_CHANCE) == 1: + elif random.randint(1, ADD_CANDY_REACTION_CHANCE) == 1: await self.candy_messages.set(message.id, "candy") - return await message.add_reaction(EMOJIS['CANDY']) + await message.add_reaction(EMOJIS["CANDY"]) @in_month(Month.OCTOBER) @commands.Cog.listener() - async def on_reaction_add(self, reaction: discord.Reaction, user: discord.Member) -> None: + async def on_reaction_add(self, reaction: discord.Reaction, user: Union[discord.User, discord.Member]) -> None: """Add/remove candies from a person if the reaction satisfies criteria.""" message = reaction.message # check to ensure the reactor is human @@ -81,7 +82,7 @@ class CandyCollection(commands.Cog): # if its not a candy or skull, and it is one of 10 most recent messages, # proceed to add a skull/candy with higher chance - if str(reaction.emoji) not in (EMOJIS['SKULL'], EMOJIS['CANDY']): + if str(reaction.emoji) not in (EMOJIS["SKULL"], EMOJIS["CANDY"]): recent_message_ids = map( lambda m: m.id, await self.hacktober_channel.history(limit=10).flatten() @@ -90,14 +91,14 @@ class CandyCollection(commands.Cog): await self.reacted_msg_chance(message) return - if await self.candy_messages.get(message.id) == "candy" and str(reaction.emoji) == EMOJIS['CANDY']: + if await self.candy_messages.get(message.id) == "candy" and str(reaction.emoji) == EMOJIS["CANDY"]: await self.candy_messages.delete(message.id) if await self.candy_records.contains(user.id): await self.candy_records.increment(user.id) else: await self.candy_records.set(user.id, 1) - elif await self.skull_messages.get(message.id) == "skull" and str(reaction.emoji) == EMOJIS['SKULL']: + elif await self.skull_messages.get(message.id) == "skull" and str(reaction.emoji) == EMOJIS["SKULL"]: await self.skull_messages.delete(message.id) if prev_record := await self.candy_records.get(user.id): @@ -124,11 +125,11 @@ class CandyCollection(commands.Cog): """ if random.randint(1, ADD_SKULL_EXISTING_REACTION_CHANCE) == 1: await self.skull_messages.set(message.id, "skull") - return await message.add_reaction(EMOJIS['SKULL']) + await message.add_reaction(EMOJIS['SKULL']) - if random.randint(1, ADD_CANDY_EXISTING_REACTION_CHANCE) == 1: + elif random.randint(1, ADD_CANDY_EXISTING_REACTION_CHANCE) == 1: await self.candy_messages.set(message.id, "candy") - return await message.add_reaction(EMOJIS['CANDY']) + await message.add_reaction(EMOJIS["CANDY"]) @property def hacktober_channel(self) -> discord.TextChannel: @@ -141,8 +142,10 @@ class CandyCollection(commands.Cog): ) -> None: """Send a spooky message.""" e = discord.Embed(colour=author.colour) - e.set_author(name="Ghosts and Ghouls and Jack o' lanterns at night; " - f"I took {candies} candies and quickly took flight.") + e.set_author( + name="Ghosts and Ghouls and Jack o' lanterns at night; " + f"I took {candies} candies and quickly took flight." + ) await channel.send(embed=e) @staticmethod @@ -173,7 +176,7 @@ class CandyCollection(commands.Cog): return '\n'.join( f"{EMOJIS['MEDALS'][index]} <@{record[0]}>: {record[1]}" for index, record in enumerate(top_five) - ) if top_five else 'No Candies' + ) if top_five else "No Candies" e = discord.Embed(colour=discord.Colour.blurple()) e.add_field( @@ -191,6 +194,6 @@ class CandyCollection(commands.Cog): await ctx.send(embed=e) -def setup(bot: commands.Bot) -> None: - """Candy Collection game Cog load.""" +def setup(bot: Bot) -> None: + """Load the Candy Collection Cog.""" bot.add_cog(CandyCollection(bot)) diff --git a/bot/exts/halloween/hacktober-issue-finder.py b/bot/exts/halloween/hacktober-issue-finder.py index 9deadde9..c88e2b6f 100644 --- a/bot/exts/halloween/hacktober-issue-finder.py +++ b/bot/exts/halloween/hacktober-issue-finder.py @@ -3,10 +3,10 @@ import logging import random from typing import Dict, Optional -import aiohttp import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Month, Tokens from bot.utils.decorators import in_month @@ -25,7 +25,7 @@ if GITHUB_TOKEN := Tokens.github: class HacktoberIssues(commands.Cog): """Find a random hacktober python issue on GitHub.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot self.cache_normal = None self.cache_timer_normal = datetime.datetime(1, 1, 1) @@ -41,7 +41,7 @@ class HacktoberIssues(commands.Cog): If the command is run with beginner (`.hacktoberissues beginner`): It will also narrow it down to the "first good issue" label. """ - with ctx.typing(): + async with ctx.typing(): issues = await self.get_issues(ctx, option) if issues is None: return @@ -59,40 +59,39 @@ class HacktoberIssues(commands.Cog): log.debug("using cache") return self.cache_normal - async with aiohttp.ClientSession() as session: + if option == "beginner": + url = URL + '+label:"good first issue"' + if self.cache_beginner is not None: + page = random.randint(1, min(1000, self.cache_beginner["total_count"]) // 100) + url += f"&page={page}" + else: + url = URL + if self.cache_normal is not None: + page = random.randint(1, min(1000, self.cache_normal["total_count"]) // 100) + url += f"&page={page}" + + log.debug(f"making api request to url: {url}") + async with self.bot.http_session.get(url, headers=REQUEST_HEADERS) as response: + if response.status != 200: + log.error(f"expected 200 status (got {response.status}) from the GitHub api.") + await ctx.send(f"ERROR: expected 200 status (got {response.status}) from the GitHub api.") + await ctx.send(await response.text()) + return None + data = await response.json() + + if len(data["items"]) == 0: + log.error(f"no issues returned from GitHub api. with url: {response.url}") + await ctx.send(f"ERROR: no issues returned from GitHub api. with url: {response.url}") + return None + if option == "beginner": - url = URL + '+label:"good first issue"' - if self.cache_beginner is not None: - page = random.randint(1, min(1000, self.cache_beginner["total_count"]) // 100) - url += f"&page={page}" + self.cache_beginner = data + self.cache_timer_beginner = ctx.message.created_at else: - url = URL - if self.cache_normal is not None: - page = random.randint(1, min(1000, self.cache_normal["total_count"]) // 100) - url += f"&page={page}" - - log.debug(f"making api request to url: {url}") - async with session.get(url, headers=REQUEST_HEADERS) as response: - if response.status != 200: - log.error(f"expected 200 status (got {response.status}) from the GitHub api.") - await ctx.send(f"ERROR: expected 200 status (got {response.status}) from the GitHub api.") - await ctx.send(await response.text()) - return None - data = await response.json() - - if len(data["items"]) == 0: - log.error(f"no issues returned from GitHub api. with url: {response.url}") - await ctx.send(f"ERROR: no issues returned from GitHub api. with url: {response.url}") - return None - - if option == "beginner": - self.cache_beginner = data - self.cache_timer_beginner = ctx.message.created_at - else: - self.cache_normal = data - self.cache_timer_normal = ctx.message.created_at - - return data + self.cache_normal = data + self.cache_timer_normal = ctx.message.created_at + + return data @staticmethod def format_embed(issue: Dict) -> discord.Embed: @@ -111,6 +110,6 @@ class HacktoberIssues(commands.Cog): return embed -def setup(bot: commands.Bot) -> None: - """Hacktober issue finder Cog Load.""" +def setup(bot: Bot) -> None: + """Load the HacktoberIssue finder.""" bot.add_cog(HacktoberIssues(bot)) diff --git a/bot/exts/halloween/hacktoberstats.py b/bot/exts/halloween/hacktoberstats.py index d9fc0e8a..9695ba2a 100644 --- a/bot/exts/halloween/hacktoberstats.py +++ b/bot/exts/halloween/hacktoberstats.py @@ -5,11 +5,11 @@ from collections import Counter from datetime import datetime, timedelta from typing import List, Optional, Tuple, Union -import aiohttp import discord from async_rediscache import RedisCache from discord.ext import commands +from bot.bot import Bot from bot.constants import Channels, Month, NEGATIVE_REPLIES, Tokens, WHITELISTED_CHANNELS from bot.utils.decorators import in_month, whitelist_override @@ -39,7 +39,7 @@ class HacktoberStats(commands.Cog): # Stores mapping of user IDs and GitHub usernames linked_accounts = RedisCache() - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @in_month(Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER) @@ -83,15 +83,15 @@ class HacktoberStats(commands.Cog): if github_username: if await self.linked_accounts.contains(author_id): old_username = await self.linked_accounts.get(author_id) - logging.info(f"{author_id} has changed their github link from '{old_username}' to '{github_username}'") + log.info(f"{author_id} has changed their github link from '{old_username}' to '{github_username}'") await ctx.send(f"{author_mention}, your GitHub username has been updated to: '{github_username}'") else: - logging.info(f"{author_id} has added a github link to '{github_username}'") + log.info(f"{author_id} has added a github link to '{github_username}'") await ctx.send(f"{author_mention}, your GitHub username has been added") await self.linked_accounts.set(author_id, github_username) else: - logging.info(f"{author_id} tried to link a GitHub account but didn't provide a username") + log.info(f"{author_id} tried to link a GitHub account but didn't provide a username") await ctx.send(f"{author_mention}, a GitHub username is required to link your account") @in_month(Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER) @@ -157,7 +157,7 @@ class HacktoberStats(commands.Cog): stats_embed = discord.Embed( title=f"{github_username}'s Hacktoberfest", - color=discord.Color(0x9c4af7), + color=0x9c4af7, description=( f"{github_username} has made {n} valid " f"{self._contributionator(n)} in " @@ -188,8 +188,7 @@ class HacktoberStats(commands.Cog): logging.info(f"Hacktoberfest PR built for GitHub user '{github_username}'") return stats_embed - @staticmethod - async def get_october_prs(github_username: str) -> Optional[List[dict]]: + async def get_october_prs(self, github_username: str) -> Optional[List[dict]]: """ Query GitHub's API for PRs created during the month of October by github_username. @@ -212,7 +211,7 @@ class HacktoberStats(commands.Cog): Otherwise, return empty list. None will be returned when the GitHub user was not found. """ - logging.info(f"Fetching Hacktoberfest Stats for GitHub user: '{github_username}'") + log.info(f"Fetching Hacktoberfest Stats for GitHub user: '{github_username}'") base_url = "https://api.github.com/search/issues?q=" action_type = "pr" is_query = "public" @@ -228,24 +227,24 @@ class HacktoberStats(commands.Cog): f"+created:{date_range}" f"&per_page={per_page}" ) - logging.debug(f"GitHub query URL generated: {query_url}") + log.logProcesses.debug(f"GitHub query URL generated: {query_url}") - jsonresp = await HacktoberStats._fetch_url(query_url, REQUEST_HEADERS) - if "message" in jsonresp.keys(): + jsonresp = await self._fetch_url(query_url, REQUEST_HEADERS) + if "message" in jsonresp: # One of the parameters is invalid, short circuit for now api_message = jsonresp["errors"][0]["message"] # Ignore logging non-existent users or users we do not have permission to see if api_message == GITHUB_NONEXISTENT_USER_MESSAGE: - logging.debug(f"No GitHub user found named '{github_username}'") + log.debug(f"No GitHub user found named '{github_username}'") return else: - logging.error(f"GitHub API request for '{github_username}' failed with message: {api_message}") + log.error(f"GitHub API request for '{github_username}' failed with message: {api_message}") return [] # No October PRs were found due to error if jsonresp["total_count"] == 0: # Short circuit if there aren't any PRs - logging.info(f"No October PRs found for GitHub user: '{github_username}'") + log.info(f"No October PRs found for GitHub user: '{github_username}'") return [] logging.info(f"Found {len(jsonresp['items'])} Hacktoberfest PRs for GitHub user: '{github_username}'") @@ -253,20 +252,20 @@ class HacktoberStats(commands.Cog): oct3 = datetime(int(CURRENT_YEAR), 10, 3, 23, 59, 59, tzinfo=None) hackto_topics = {} # cache whether each repo has the appropriate topic (bool values) for item in jsonresp["items"]: - shortname = HacktoberStats._get_shortname(item["repository_url"]) + shortname = self._get_shortname(item["repository_url"]) itemdict = { "repo_url": f"https://www.github.com/{shortname}", "repo_shortname": shortname, "created_at": datetime.strptime( - item["created_at"], r"%Y-%m-%dT%H:%M:%SZ" + item["created_at"], "%Y-%m-%dT%H:%M:%SZ" ), "number": item["number"] } # If the PR has 'invalid' or 'spam' labels, the PR must be # either merged or approved for it to be included - if HacktoberStats._has_label(item, ["invalid", "spam"]): - if not await HacktoberStats._is_accepted(itemdict): + if self._has_label(item, ["invalid", "spam"]): + if not await self._is_accepted(itemdict): continue # PRs before oct 3 no need to check for topics @@ -277,21 +276,20 @@ class HacktoberStats(commands.Cog): continue # Checking PR's labels for "hacktoberfest-accepted" - if HacktoberStats._has_label(item, "hacktoberfest-accepted"): + if self._has_label(item, "hacktoberfest-accepted"): outlist.append(itemdict) continue # No need to query GitHub if repo topics are fetched before already - if shortname in hackto_topics.keys(): - if hackto_topics[shortname]: - outlist.append(itemdict) - continue + if hackto_topics.get(shortname): + outlist.append(itemdict) + continue # Fetch topics for the PR's repo topics_query_url = f"https://api.github.com/repos/{shortname}/topics" - logging.debug(f"Fetching repo topics for {shortname} with url: {topics_query_url}") - jsonresp2 = await HacktoberStats._fetch_url(topics_query_url, GITHUB_TOPICS_ACCEPT_HEADER) + log.debug(f"Fetching repo topics for {shortname} with url: {topics_query_url}") + jsonresp2 = await self._fetch_url(topics_query_url, GITHUB_TOPICS_ACCEPT_HEADER) if jsonresp2.get("names") is None: - logging.error(f"Error fetching topics for {shortname}: {jsonresp2['message']}") + log.error(f"Error fetching topics for {shortname}: {jsonresp2['message']}") continue # Assume the repo doesn't have the `hacktoberfest` topic if API request errored # PRs after oct 3 that doesn't have 'hacktoberfest-accepted' label @@ -301,12 +299,10 @@ class HacktoberStats(commands.Cog): outlist.append(itemdict) return outlist - @staticmethod - async def _fetch_url(url: str, headers: dict) -> dict: + async def _fetch_url(self, url: str, headers: dict) -> dict: """Retrieve API response from URL.""" - async with aiohttp.ClientSession() as session: - async with session.get(url, headers=headers) as resp: - jsonresp = await resp.json() + async with self.bot.http_session.get(url, headers=headers) as resp: + jsonresp = await resp.json() return jsonresp @staticmethod @@ -319,40 +315,36 @@ class HacktoberStats(commands.Cog): """ if not pr.get("labels"): # if PR has no labels return False - if (isinstance(labels, str)) and (any(label["name"].casefold() == labels for label in pr["labels"])): + if isinstance(labels, str) and any(label["name"].casefold() == labels for label in pr["labels"]): return True for item in labels: if any(label["name"].casefold() == item for label in pr["labels"]): return True return False - @staticmethod - async def _is_accepted(pr: dict) -> bool: + async def _is_accepted(self, pr: dict) -> bool: """Check if a PR is merged, approved, or labelled hacktoberfest-accepted.""" # checking for merge status - query_url = f"https://api.github.com/repos/{pr['repo_shortname']}/pulls/" - query_url += str(pr["number"]) - jsonresp = await HacktoberStats._fetch_url(query_url, REQUEST_HEADERS) - - if "message" in jsonresp.keys(): - logging.error( - f"Error fetching PR stats for #{pr['number']} in repo {pr['repo_shortname']}:\n" - f"{jsonresp['message']}" - ) + query_url = f"https://api.github.com/repos/{pr['repo_shortname']}/pulls/{pr['number']}" + jsonresp = await self._fetch_url(query_url, REQUEST_HEADERS) + + if message := jsonresp.get("message"): + log.error(f"Error fetching PR stats for #{pr['number']} in repo {pr['repo_shortname']}:\n{message}") return False - if ("merged" in jsonresp.keys()) and jsonresp["merged"]: + + if jsonresp.get("merged"): return True # checking for the label, using `jsonresp` which has the label information - if HacktoberStats._has_label(jsonresp, "hacktoberfest-accepted"): + if self._has_label(jsonresp, "hacktoberfest-accepted"): return True # checking approval query_url += "/reviews" - jsonresp2 = await HacktoberStats._fetch_url(query_url, REQUEST_HEADERS) + jsonresp2 = await self._fetch_url(query_url, REQUEST_HEADERS) if isinstance(jsonresp2, dict): # if API request is unsuccessful it will be a dict with the error in 'message' - logging.error( + log.error( f"Error fetching PR reviews for #{pr['number']} in repo {pr['repo_shortname']}:\n" f"{jsonresp2['message']}" ) @@ -363,9 +355,8 @@ class HacktoberStats(commands.Cog): # loop through reviews and check for approval for item in jsonresp2: - if "status" in item.keys(): - if item['status'] == "APPROVED": - return True + if item.get('status') == "APPROVED": + return True return False @staticmethod @@ -381,8 +372,7 @@ class HacktoberStats(commands.Cog): exp = r"https?:\/\/api.github.com\/repos\/([/\-\_\.\w]+)" return re.findall(exp, in_url)[0] - @staticmethod - async def _categorize_prs(prs: List[dict]) -> tuple: + async def _categorize_prs(self, prs: List[dict]) -> tuple: """ Categorize PRs into 'in_review' and 'accepted' and returns as a tuple. @@ -399,7 +389,7 @@ class HacktoberStats(commands.Cog): for pr in prs: if (pr['created_at'] + timedelta(REVIEW_DAYS)) > now: in_review.append(pr) - elif (pr['created_at'] <= oct3) or await HacktoberStats._is_accepted(pr): + elif (pr['created_at'] <= oct3) or await self._is_accepted(pr): accepted.append(pr) return in_review, accepted @@ -438,14 +428,14 @@ class HacktoberStats(commands.Cog): return "contributions" @staticmethod - def _author_mention_from_context(ctx: commands.Context) -> Tuple: + def _author_mention_from_context(ctx: commands.Context) -> Tuple[str, str]: """Return stringified Message author ID and mentionable string from commands.Context.""" - author_id = str(ctx.message.author.id) - author_mention = ctx.message.author.mention + author_id = str(ctx.author.id) + author_mention = ctx.author.mention return author_id, author_mention -def setup(bot: commands.Bot) -> None: - """Hacktoberstats Cog load.""" +def setup(bot: Bot) -> None: + """Load the Hacktober Stats Cog.""" bot.add_cog(HacktoberStats(bot)) diff --git a/bot/exts/halloween/halloween_facts.py b/bot/exts/halloween/halloween_facts.py index 7eb6d56f..139e0810 100644 --- a/bot/exts/halloween/halloween_facts.py +++ b/bot/exts/halloween/halloween_facts.py @@ -8,6 +8,8 @@ from typing import Tuple import discord from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) SPOOKY_EMOJIS = [ @@ -20,16 +22,15 @@ SPOOKY_EMOJIS = [ "\N{SKULL AND CROSSBONES}", "\N{SPIDER WEB}", ] -PUMPKIN_ORANGE = discord.Color(0xFF7518) +PUMPKIN_ORANGE = 0xFF7518 INTERVAL = timedelta(hours=6).total_seconds() class HalloweenFacts(commands.Cog): """A Cog for displaying interesting facts about Halloween.""" - def __init__(self, bot: commands.Bot): - self.bot = bot - with open(Path("bot/resources/halloween/halloween_facts.json"), "r", encoding="utf8") as file: + def __init__(self): + with Path("bot/resources/halloween/halloween_facts.json").open("r", encoding="utf8") as file: self.halloween_facts = json.load(file) self.facts = list(enumerate(self.halloween_facts)) random.shuffle(self.facts) @@ -53,6 +54,6 @@ class HalloweenFacts(commands.Cog): return discord.Embed(title=title, description=fact, color=PUMPKIN_ORANGE) -def setup(bot: commands.Bot) -> None: - """Halloween facts Cog load.""" - bot.add_cog(HalloweenFacts(bot)) +def setup(bot: Bot) -> None: + """Load the Halloween Facts Cog.""" + bot.add_cog(HalloweenFacts()) diff --git a/bot/exts/halloween/halloweenify.py b/bot/exts/halloween/halloweenify.py index 596c6682..5a8f4ecc 100644 --- a/bot/exts/halloween/halloweenify.py +++ b/bot/exts/halloween/halloweenify.py @@ -6,7 +6,9 @@ from random import choice import discord from discord.errors import Forbidden from discord.ext import commands -from discord.ext.commands.cooldowns import BucketType +from discord.ext.commands import BucketType + +from bot.bot import Bot log = logging.getLogger(__name__) @@ -14,9 +16,6 @@ log = logging.getLogger(__name__) class Halloweenify(commands.Cog): """A cog to change a invokers nickname to a spooky one!""" - def __init__(self, bot: commands.Bot): - self.bot = bot - @commands.cooldown(1, 300, BucketType.user) @commands.command() async def halloweenify(self, ctx: commands.Context) -> None: @@ -61,6 +60,6 @@ class Halloweenify(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: - """Halloweenify Cog load.""" - bot.add_cog(Halloweenify(bot)) +def setup(bot: Bot) -> None: + """Load the Halloweenify Cog.""" + bot.add_cog(Halloweenify()) diff --git a/bot/exts/halloween/monsterbio.py b/bot/exts/halloween/monsterbio.py index 016a66d1..f484305d 100644 --- a/bot/exts/halloween/monsterbio.py +++ b/bot/exts/halloween/monsterbio.py @@ -6,6 +6,7 @@ from pathlib import Path import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours log = logging.getLogger(__name__) @@ -17,9 +18,6 @@ with open(Path("bot/resources/halloween/monster.json"), "r", encoding="utf8") as class MonsterBio(commands.Cog): """A cog that generates a spooky monster biography.""" - def __init__(self, bot: commands.Bot): - self.bot = bot - def generate_name(self, seeded_random: random.Random) -> str: """Generates a name (for either monster species or monster name).""" n_candidate_strings = seeded_random.randint(2, len(TEXT_OPTIONS["monster_type"])) @@ -50,6 +48,6 @@ class MonsterBio(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: - """Monster bio Cog load.""" - bot.add_cog(MonsterBio(bot)) +def setup(bot: Bot) -> None: + """Load the Monster Bio Cog.""" + bot.add_cog(MonsterBio()) diff --git a/bot/exts/halloween/monstersurvey.py b/bot/exts/halloween/monstersurvey.py index 80196825..0610503d 100644 --- a/bot/exts/halloween/monstersurvey.py +++ b/bot/exts/halloween/monstersurvey.py @@ -23,9 +23,8 @@ class MonsterSurvey(Cog): Users may change their vote, but only their current vote will be counted. """ - def __init__(self, bot: Bot): + def __init__(self): """Initializes values for the bot to use within the voting commands.""" - self.bot = bot self.registry_location = os.path.join(os.getcwd(), 'bot', 'resources', 'halloween', 'monstersurvey.json') with open(self.registry_location, 'r', encoding="utf8") as jason: self.voter_registry = json.load(jason) @@ -201,4 +200,5 @@ class MonsterSurvey(Cog): def setup(bot: Bot) -> None: - """Monster survey Cog load.""" + """Load the Monster Survey Cog.""" + bot.add_cog(MonsterSurvey()) diff --git a/bot/exts/halloween/scarymovie.py b/bot/exts/halloween/scarymovie.py index 0807eca6..48c9f53d 100644 --- a/bot/exts/halloween/scarymovie.py +++ b/bot/exts/halloween/scarymovie.py @@ -2,24 +2,25 @@ import logging import random from os import environ -import aiohttp from discord import Embed from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) -TMDB_API_KEY = environ.get('TMDB_API_KEY') -TMDB_TOKEN = environ.get('TMDB_TOKEN') +TMDB_API_KEY = environ.get("TMDB_API_KEY") +TMDB_TOKEN = environ.get("TMDB_TOKEN") class ScaryMovie(commands.Cog): """Selects a random scary movie and embeds info into Discord chat.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot - @commands.command(name='scarymovie', alias=['smovie']) + @commands.command(name="scarymovie", alias=["smovie"]) async def random_movie(self, ctx: commands.Context) -> None: """Randomly select a scary movie and display information about it.""" async with ctx.typing(): @@ -28,36 +29,34 @@ class ScaryMovie(commands.Cog): await ctx.send(embed=movie_details) - @staticmethod - async def select_movie() -> dict: + async def select_movie(self) -> dict: """Selects a random movie and returns a JSON of movie details from TMDb.""" - url = 'https://api.themoviedb.org/4/discover/movie' + url = "https://api.themoviedb.org/4/discover/movie" params = { - 'with_genres': '27', - 'vote_count.gte': '5' + "with_genres": "27", + "vote_count.gte": "5" } headers = { - 'Authorization': 'Bearer ' + TMDB_TOKEN, - 'Content-Type': 'application/json;charset=utf-8' + "Authorization": "Bearer " + TMDB_TOKEN, + "Content-Type": "application/json;charset=utf-8" } # Get total page count of horror movies - async with aiohttp.ClientSession() as session: - response = await session.get(url=url, params=params, headers=headers) - total_pages = await response.json() - total_pages = total_pages.get('total_pages') - - # Get movie details from one random result on a random page - params['page'] = random.randint(1, total_pages) - response = await session.get(url=url, params=params, headers=headers) - response = await response.json() - selection_id = random.choice(response.get('results')).get('id') - - # Get full details and credits - selection = await session.get( - url='https://api.themoviedb.org/3/movie/' + str(selection_id), - params={'api_key': TMDB_API_KEY, 'append_to_response': 'credits'} - ) + async with self.bot.http_session.get(url=url, params=params, headers=headers) as response: + data = await response.json() + total_pages = data.get("total_pages") + + # Get movie details from one random result on a random page + params['page'] = random.randint(1, total_pages) + async with self.bot.http_session.get(url=url, params=params, headers=headers) as response: + data = await response.json() + selection_id = random.choice(data.get("results")).get("id") + + # Get full details and credits + async with self.bot.http_session.get( + url=f"https://api.themoviedb.org/3/movie/{selection_id}", + params={"api_key": TMDB_API_KEY, "append_to_response": "credits"} + ) as selection: return await selection.json() @@ -67,8 +66,8 @@ class ScaryMovie(commands.Cog): # Build the relevant URLs. movie_id = movie.get("id") poster_path = movie.get("poster_path") - tmdb_url = f'https://www.themoviedb.org/movie/{movie_id}' if movie_id else None - poster = f'https://image.tmdb.org/t/p/original{poster_path}' if poster_path else None + tmdb_url = f"https://www.themoviedb.org/movie/{movie_id}" if movie_id else None + poster = f"https://image.tmdb.org/t/p/original{poster_path}" if poster_path else None # Get cast names cast = [] @@ -82,10 +81,7 @@ class ScaryMovie(commands.Cog): # Determine the spookiness rating rating = '' - rating_count = movie.get('vote_average', 0) - - if rating_count: - rating_count /= 2 + rating_count = movie.get('vote_average', 0) / 2 for _ in range(int(rating_count)): rating += ':skull:' @@ -100,7 +96,7 @@ class ScaryMovie(commands.Cog): # Not all these attributes will always be present movie_attributes = { "Directed by": director, - "Starring": ', '.join(cast), + "Starring": ", ".join(cast), "Running time": runtime, "Release year": year, "Spookiness rating": rating, @@ -108,9 +104,9 @@ class ScaryMovie(commands.Cog): embed = Embed( colour=0x01d277, - title='**' + movie.get('title') + '**', + title=f"**{movie.get('title')}**", url=tmdb_url, - description=movie.get('overview') + description=movie.get("overview") ) if poster: @@ -127,6 +123,6 @@ class ScaryMovie(commands.Cog): return embed -def setup(bot: commands.Bot) -> None: - """Scary movie Cog load.""" +def setup(bot: Bot) -> None: + """Load the Scary Movie Cog.""" bot.add_cog(ScaryMovie(bot)) diff --git a/bot/exts/halloween/spookygif.py b/bot/exts/halloween/spookygif.py index f402437f..bfdf2128 100644 --- a/bot/exts/halloween/spookygif.py +++ b/bot/exts/halloween/spookygif.py @@ -1,9 +1,9 @@ import logging -import aiohttp import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Tokens log = logging.getLogger(__name__) @@ -12,27 +12,26 @@ log = logging.getLogger(__name__) class SpookyGif(commands.Cog): """A cog to fetch a random spooky gif from the web!""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.command(name="spookygif", aliases=("sgif", "scarygif")) async def spookygif(self, ctx: commands.Context) -> None: """Fetches a random gif from the GIPHY API and responds with it.""" async with ctx.typing(): - async with aiohttp.ClientSession() as session: - params = {'api_key': Tokens.giphy, 'tag': 'halloween', 'rating': 'g'} - # Make a GET request to the Giphy API to get a random halloween gif. - async with session.get('http://api.giphy.com/v1/gifs/random', params=params) as resp: - data = await resp.json() - url = data['data']['image_url'] + params = {'api_key': Tokens.giphy, 'tag': 'halloween', 'rating': 'g'} + # Make a GET request to the Giphy API to get a random halloween gif. + async with self.bot.http_session.get('http://api.giphy.com/v1/gifs/random', params=params) as resp: + data = await resp.json() + url = data['data']['image_url'] - embed = discord.Embed(colour=0x9b59b6) - embed.title = "A spooooky gif!" - embed.set_image(url=url) + embed = discord.Embed(colour=0x9b59b6) + embed.title = "A spooooky gif!" + embed.set_image(url=url) await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Spooky GIF Cog load.""" bot.add_cog(SpookyGif(bot)) diff --git a/bot/exts/halloween/spookynamerate.py b/bot/exts/halloween/spookynamerate.py index e2950343..9191f5f6 100644 --- a/bot/exts/halloween/spookynamerate.py +++ b/bot/exts/halloween/spookynamerate.py @@ -12,8 +12,9 @@ from async_rediscache import RedisCache from discord import Embed, Reaction, TextChannel, User from discord.colour import Colour from discord.ext import tasks -from discord.ext.commands import Bot, Cog, Context, group +from discord.ext.commands import Cog, Context, group +from bot.bot import Bot from bot.constants import Channels, Client, Colours, Month from bot.utils.decorators import InMonthCheckFailure @@ -34,7 +35,7 @@ ADDED_MESSAGES = [ ] PING = "<@{id}>" -EMOJI_MESSAGE = "\n".join([f"- {emoji} {val}" for emoji, val in EMOJIS_VAL.items()]) +EMOJI_MESSAGE = "\n".join(f"- {emoji} {val}" for emoji, val in EMOJIS_VAL.items()) HELP_MESSAGE_DICT = { "title": "Spooky Name Rate", "description": f"Help for the `{Client.prefix}spookynamerate` command", @@ -137,14 +138,12 @@ class SpookyNameRate(Cog): async def add_name(self, ctx: Context, *, name: str) -> None: """Use this command to add/register your spookified name.""" if self.poll: - logger.info(f"{ctx.message.author} tried to add a name, but the poll had already started.") + logger.info(f"{ctx.author} tried to add a name, but the poll had already started.") await ctx.send("Sorry, the poll has started! You can try and participate in the next round though!") return - message = ctx.message - for data in (json.loads(user_data) for _, user_data in await self.messages.items()): - if data["author"] == message.author.id: + if data["author"] == ctx.author.id: await ctx.send( "But you have already added an entry! Type " f"`{self.bot.command_prefix}spookynamerate " @@ -156,14 +155,14 @@ class SpookyNameRate(Cog): await ctx.send("TOO LATE. Someone has already added this name.") return - msg = await (await self.get_channel()).send(f"{message.author.mention} added the name {name!r}!") + msg = await (await self.get_channel()).send(f"{ctx.author.mention} added the name {name!r}!") await self.messages.set( msg.id, json.dumps( { "name": name, - "author": message.author.id, + "author": ctx.author.id, "score": 0, } ), @@ -172,7 +171,7 @@ class SpookyNameRate(Cog): for emoji in EMOJIS_VAL: await msg.add_reaction(emoji) - logger.info(f"{message.author} added the name {name!r}") + logger.info(f"{ctx.author} added the name {name!r}") @spooky_name_rate.command(name="delete") async def delete_name(self, ctx: Context) -> None: @@ -185,7 +184,7 @@ class SpookyNameRate(Cog): if ctx.author.id == data["author"]: await self.messages.delete(message_id) - await ctx.send(f'Name deleted successfully ({data["name"]!r})!') + await ctx.send(f"Name deleted successfully ({data['name']!r})!") return await ctx.send( @@ -397,5 +396,5 @@ class SpookyNameRate(Cog): def setup(bot: Bot) -> None: - """Loads the SpookyNameRate Cog.""" + """Load the SpookyNameRate Cog.""" bot.add_cog(SpookyNameRate(bot)) diff --git a/bot/exts/halloween/spookyrating.py b/bot/exts/halloween/spookyrating.py index 6f069f8c..dc398e2e 100644 --- a/bot/exts/halloween/spookyrating.py +++ b/bot/exts/halloween/spookyrating.py @@ -7,20 +7,20 @@ from pathlib import Path import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours log = logging.getLogger(__name__) with Path("bot/resources/halloween/spooky_rating.json").open(encoding="utf8") as file: - SPOOKY_DATA = json.load(file) - SPOOKY_DATA = sorted((int(key), value) for key, value in SPOOKY_DATA.items()) + data = json.load(file) + SPOOKY_DATA = sorted((int(key), value) for key, value in data.items()) class SpookyRating(commands.Cog): """A cog for calculating one's spooky rating.""" - def __init__(self, bot: commands.Bot): - self.bot = bot + def __init__(self): self.local_random = random.Random() @commands.command() @@ -61,6 +61,6 @@ class SpookyRating(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: - """Spooky Rating Cog load.""" - bot.add_cog(SpookyRating(bot)) +def setup(bot: Bot) -> None: + """Load the Spooky Rating Cog.""" + bot.add_cog(SpookyRating()) diff --git a/bot/exts/halloween/spookyreact.py b/bot/exts/halloween/spookyreact.py index b335df75..dabc3c1f 100644 --- a/bot/exts/halloween/spookyreact.py +++ b/bot/exts/halloween/spookyreact.py @@ -2,8 +2,9 @@ import logging import re import discord -from discord.ext.commands import Bot, Cog +from discord.ext.commands import Cog +from bot.bot import Bot from bot.constants import Month from bot.utils.decorators import in_month @@ -28,20 +29,20 @@ class SpookyReact(Cog): @in_month(Month.OCTOBER) @Cog.listener() - async def on_message(self, ctx: discord.Message) -> None: + async def on_message(self, message: discord.Message) -> None: """Triggered when the bot sees a message in October.""" - for trigger in SPOOKY_TRIGGERS.keys(): - trigger_test = re.search(SPOOKY_TRIGGERS[trigger][0], ctx.content.lower()) + for name, trigger in SPOOKY_TRIGGERS.items(): + trigger_test = re.search(trigger[0], message.content.lower()) if trigger_test: # Check message for bot replies and/or command invocations # Short circuit if they're found, logging is handled in _short_circuit_check - if await self._short_circuit_check(ctx): + if await self._short_circuit_check(message): return else: - await ctx.add_reaction(SPOOKY_TRIGGERS[trigger][1]) - logging.info(f"Added '{trigger}' reaction to message ID: {ctx.id}") + await message.add_reaction(trigger[1]) + log.info(f"Added {name!r} reaction to message ID: {message.id}") - async def _short_circuit_check(self, ctx: discord.Message) -> bool: + async def _short_circuit_check(self, message: discord.Message) -> bool: """ Short-circuit helper check. @@ -50,20 +51,20 @@ class SpookyReact(Cog): * prefix is not None """ # Check for self reaction - if ctx.author == self.bot.user: - logging.debug(f"Ignoring reactions on self message. Message ID: {ctx.id}") + if message.author == self.bot.user: + log.debug(f"Ignoring reactions on self message. Message ID: {message.id}") return True # Check for command invocation # Because on_message doesn't give a full Context object, generate one first - tmp_ctx = await self.bot.get_context(ctx) - if tmp_ctx.prefix: - logging.debug(f"Ignoring reactions on command invocation. Message ID: {ctx.id}") + ctx = await self.bot.get_context(message) + if ctx.prefix: + log.debug(f"Ignoring reactions on command invocation. Message ID: {message.id}") return True return False def setup(bot: Bot) -> None: - """Spooky reaction Cog load.""" + """Load the Spooky Reaction Cog.""" bot.add_cog(SpookyReact(bot)) diff --git a/bot/exts/halloween/timeleft.py b/bot/exts/halloween/timeleft.py index 47adb09b..f4ab9284 100644 --- a/bot/exts/halloween/timeleft.py +++ b/bot/exts/halloween/timeleft.py @@ -4,13 +4,15 @@ from typing import Tuple from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) class TimeLeft(commands.Cog): """A Cog that tells you how long left until Hacktober is over!""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot def in_hacktober(self) -> bool: @@ -64,6 +66,6 @@ class TimeLeft(commands.Cog): ) -def setup(bot: commands.Bot) -> None: - """Cog load.""" +def setup(bot: Bot) -> None: + """Load the Time Left Cog.""" bot.add_cog(TimeLeft(bot)) -- cgit v1.2.3 From 8662541fc08037558f68e15dcc3fd72ef491dced Mon Sep 17 00:00:00 2001 From: vcokltfre Date: Tue, 20 Apr 2021 17:01:02 +0100 Subject: chore: ctx.channel.send -> ctx.send --- bot/exts/evergreen/snakes/_snakes_cog.py | 22 +++++++++++----------- bot/exts/valentines/myvalenstate.py | 2 +- bot/exts/valentines/whoisvalentine.py | 4 ++-- 3 files changed, 14 insertions(+), 14 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index 3732b559..70093912 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -423,7 +423,7 @@ class Snakes(Cog): try: reaction, user = await ctx.bot.wait_for("reaction_add", timeout=45.0, check=predicate) except asyncio.TimeoutError: - await ctx.channel.send(f"You took too long. The correct answer was **{options[answer]}**.") + await ctx.send(f"You took too long. The correct answer was **{options[answer]}**.") await message.clear_reactions() return @@ -720,7 +720,7 @@ class Snakes(Cog): snake_image = utils.snakes[snake_name] # Hatch the snake - message = await ctx.channel.send(embed=Embed(description="Hatching your snake :snake:...")) + message = await ctx.send(embed=Embed(description="Hatching your snake :snake:...")) await asyncio.sleep(1) for stage in utils.stages: @@ -737,7 +737,7 @@ class Snakes(Cog): text=" Owner: {0}#{1}".format(ctx.message.author.name, ctx.message.author.discriminator) ) - await ctx.channel.send(embed=my_snake_embed) + await ctx.send(embed=my_snake_embed) @snakes_group.command(name='movie') async def movie_command(self, ctx: Context) -> None: @@ -800,9 +800,9 @@ class Snakes(Cog): embed.set_thumbnail(url="https://i.imgur.com/LtFtC8H.png") try: - await ctx.channel.send(embed=embed) + await ctx.send(embed=embed) except HTTPException as err: - await ctx.channel.send("An error occurred while fetching a snake-related movie!") + await ctx.send("An error occurred while fetching a snake-related movie!") raise err from None @snakes_group.command(name='quiz') @@ -828,7 +828,7 @@ class Snakes(Cog): ) ) - quiz = await ctx.channel.send("", embed=embed) + quiz = await ctx.send("", embed=embed) await self._validate_answer(ctx, quiz, answer, options) @snakes_group.command(name='name', aliases=('name_gen',)) @@ -964,7 +964,7 @@ class Snakes(Cog): ) ) - await ctx.channel.send(embed=embed) + await ctx.send(embed=embed) @snakes_group.command(name='card') async def card_command(self, ctx: Context, *, name: Snake = None) -> None: @@ -1018,7 +1018,7 @@ class Snakes(Cog): color=SNAKE_COLOR, description=question ) - await ctx.channel.send(embed=embed) + await ctx.send(embed=embed) @snakes_group.command(name='snakify') async def snakify_command(self, ctx: Context, *, message: str = None) -> None: @@ -1059,7 +1059,7 @@ class Snakes(Cog): ) embed.description = f"*{self._snakify(message)}*" - await ctx.channel.send(embed=embed) + await ctx.send(embed=embed) @snakes_group.command(name='video', aliases=('get_video',)) async def video_command(self, ctx: Context, *, search: str = None) -> None: @@ -1095,7 +1095,7 @@ class Snakes(Cog): if len(data) > 0: num = random.randint(0, len(data) - 1) youtube_base_url = 'https://www.youtube.com/watch?v=' - await ctx.channel.send( + await ctx.send( content=f"{youtube_base_url}{data[num]['id']['videoId']}" ) else: @@ -1120,7 +1120,7 @@ class Snakes(Cog): # Embed and send embed.description = zen_quote - await ctx.channel.send( + await ctx.send( embed=embed ) # endregion diff --git a/bot/exts/valentines/myvalenstate.py b/bot/exts/valentines/myvalenstate.py index 01801847..041af7af 100644 --- a/bot/exts/valentines/myvalenstate.py +++ b/bot/exts/valentines/myvalenstate.py @@ -78,7 +78,7 @@ class MyValenstate(commands.Cog): ) embed.add_field(name=embed_title, value=embed_text) embed.set_image(url=STATES[valenstate]["flag"]) - await ctx.channel.send(embed=embed) + await ctx.send(embed=embed) def setup(bot: commands.Bot) -> None: diff --git a/bot/exts/valentines/whoisvalentine.py b/bot/exts/valentines/whoisvalentine.py index 0ff9186c..ab6b1ca1 100644 --- a/bot/exts/valentines/whoisvalentine.py +++ b/bot/exts/valentines/whoisvalentine.py @@ -33,7 +33,7 @@ class ValentineFacts(commands.Cog): 'facial_reconstruction.jpg/1024px-Saint_Valentine_-_facial_reconstruction.jpg' ) - await ctx.channel.send(embed=embed) + await ctx.send(embed=embed) @commands.command() async def valentine_fact(self, ctx: commands.Context) -> None: @@ -44,7 +44,7 @@ class ValentineFacts(commands.Cog): color=Colours.pink ) - await ctx.channel.send(embed=embed) + await ctx.send(embed=embed) def setup(bot: commands.Bot) -> None: -- cgit v1.2.3 From 97048ce3634875e875f4a66e786b49d39bfdb17f Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Tue, 20 Apr 2021 12:22:41 -0400 Subject: Clean Up Christmas Season --- bot/exts/christmas/advent_of_code/_cog.py | 4 ++-- bot/exts/christmas/hanukkah_embed.py | 16 +++++++++------- bot/exts/pride/drag_queen_name.py | 9 +++++---- bot/exts/pride/pride_anthem.py | 14 ++++++++------ bot/exts/pride/pride_facts.py | 18 ++++++++---------- 5 files changed, 32 insertions(+), 29 deletions(-) (limited to 'bot') diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index 8376987d..da1cf28d 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -124,7 +124,7 @@ class AdventOfCode(commands.Cog): @whitelist_override(channels=AOC_WHITELIST) async def about_aoc(self, ctx: commands.Context) -> None: """Respond with an explanation of all things Advent of Code.""" - await ctx.send("", embed=self.cached_about_aoc) + await ctx.send(embed=self.cached_about_aoc) @adventofcode_group.command(name="join", aliases=("j",), brief="Learn how to join the leaderboard (via DM)") @whitelist_override(channels=AOC_WHITELIST) @@ -135,7 +135,7 @@ class AdventOfCode(commands.Cog): await ctx.send(f"The Python Discord leaderboard for {current_year} is not yet available!") return - author = ctx.message.author + author = ctx.author log.info(f"{author.name} ({author.id}) has requested a PyDis AoC leaderboard code") if AocConfig.staff_leaderboard_id and any(r.id == Roles.helpers for r in author.roles): diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index 4f470a34..cd8a9192 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -5,6 +5,7 @@ from typing import List from discord import Embed from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours, Month from bot.utils.decorators import in_month @@ -14,7 +15,7 @@ log = logging.getLogger(__name__) class HanukkahEmbed(commands.Cog): """A cog that returns information about Hanukkah festival.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot self.url = ("https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&" "year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3448439&m=50&s=on") @@ -60,17 +61,18 @@ class HanukkahEmbed(commands.Cog): if day in self.hanukkah_days and month in self.hanukkah_months and year in self.hanukkah_years: if int(day) == hanukkah_start_day: now = datetime.datetime.utcnow() - now = str(now) - hours = int(now[11:13]) + 4 # using only hours + hours = now.hour + 4 # using only hours hanukkah_start_hour = 18 if hours < hanukkah_start_hour: embed.description = (f"Hanukkah hasnt started yet, " f"it will start in about {hanukkah_start_hour-hours} hour/s.") - return await ctx.send(embed=embed) + await ctx.send(embed=embed) + return elif hours > hanukkah_start_hour: embed.description = (f'It is the starting day of Hanukkah ! ' f'Its been {hours-hanukkah_start_hour} hours hanukkah started !') - return await ctx.send(embed=embed) + await ctx.send(embed=embed) + return festival_day = self.hanukkah_days.index(day) number_suffixes = ['st', 'nd', 'rd', 'th'] suffix = '' @@ -108,6 +110,6 @@ class HanukkahEmbed(commands.Cog): self.hanukkah_years.append(date[0:4]) -def setup(bot: commands.Bot) -> None: - """Cog load.""" +def setup(bot: Bot) -> None: + """Load the Hanukkah Embed Cog.""" bot.add_cog(HanukkahEmbed(bot)) diff --git a/bot/exts/pride/drag_queen_name.py b/bot/exts/pride/drag_queen_name.py index fca9750f..32ead1bc 100644 --- a/bot/exts/pride/drag_queen_name.py +++ b/bot/exts/pride/drag_queen_name.py @@ -5,14 +5,15 @@ from pathlib import Path from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) class DragNames(commands.Cog): """Gives a random drag queen name!""" - def __init__(self, bot: commands.Bot): - self.bot = bot + def __init__(self): self.names = self.load_names() @staticmethod @@ -27,6 +28,6 @@ class DragNames(commands.Cog): await ctx.send(random.choice(self.names)) -def setup(bot: commands.Bot) -> None: - """Cog loader for drag queen name generator.""" +def setup(bot: Bot) -> None: + """Load the Drag Queen Cog.""" bot.add_cog(DragNames(bot)) diff --git a/bot/exts/pride/pride_anthem.py b/bot/exts/pride/pride_anthem.py index 33cb2a9d..a7f8d7ef 100644 --- a/bot/exts/pride/pride_anthem.py +++ b/bot/exts/pride/pride_anthem.py @@ -2,20 +2,22 @@ import json import logging import random from pathlib import Path +from typing import Optional from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) class PrideAnthem(commands.Cog): """Embed a random youtube video for a gay anthem!""" - def __init__(self, bot: commands.Bot): - self.bot = bot + def __init__(self): self.anthems = self.load_vids() - def get_video(self, genre: str = None) -> dict: + def get_video(self, genre: Optional[str] = None) -> dict: """ Picks a random anthem from the list. @@ -52,6 +54,6 @@ class PrideAnthem(commands.Cog): await ctx.send("I couldn't find a video, sorry!") -def setup(bot: commands.Bot) -> None: - """Cog loader for pride anthem.""" - bot.add_cog(PrideAnthem(bot)) +def setup(bot: Bot) -> None: + """Load the Pride Anthem Cog.""" + bot.add_cog(PrideAnthem()) diff --git a/bot/exts/pride/pride_facts.py b/bot/exts/pride/pride_facts.py index 5bd5d0ce..b2daaab7 100644 --- a/bot/exts/pride/pride_facts.py +++ b/bot/exts/pride/pride_facts.py @@ -15,8 +15,6 @@ from bot.utils.decorators import seasonal_task log = logging.getLogger(__name__) -Sendable = Union[commands.Context, discord.TextChannel] - class PrideFacts(commands.Cog): """Provides a new fact every day during the Pride season!""" @@ -44,7 +42,7 @@ class PrideFacts(commands.Cog): async def send_random_fact(self, ctx: commands.Context) -> None: """Provides a fact from any previous day, or today.""" now = datetime.utcnow() - previous_years_facts = (self.facts[x] for x in self.facts.keys() if int(x) < now.year) + previous_years_facts = (y for x, y in self.facts.items() if int(x) < now.year) current_year_facts = self.facts.get(str(now.year), [])[:now.day] previous_facts = current_year_facts + [x for y in previous_years_facts for x in y] try: @@ -52,7 +50,7 @@ class PrideFacts(commands.Cog): except IndexError: await ctx.send("No facts available") - async def send_select_fact(self, target: Sendable, _date: Union[str, datetime]) -> None: + async def send_select_fact(self, target: discord.abc.Messageable, _date: Union[str, datetime]) -> None: """Provides the fact for the specified day, if the day is today, or is in the past.""" now = datetime.utcnow() if isinstance(_date, str): @@ -76,7 +74,7 @@ class PrideFacts(commands.Cog): await target.send("The fact for the selected day is not yet available.") @commands.command(name="pridefact", aliases=["pridefacts"]) - async def pridefact(self, ctx: commands.Context) -> None: + async def pridefact(self, ctx: commands.Context, option: str = None) -> None: """ Sends a message with a pride fact of the day. @@ -85,15 +83,15 @@ class PrideFacts(commands.Cog): If a date is given as an argument, and the date is in the past, the fact from that day will be provided. """ - message_body = ctx.message.content[len(ctx.invoked_with) + 2:] - if message_body == "": + if not option: await self.send_select_fact(ctx, datetime.utcnow()) - elif message_body.lower().startswith("rand"): + elif option.lower().startswith("rand"): await self.send_random_fact(ctx) else: - await self.send_select_fact(ctx, message_body) + await self.send_select_fact(ctx, option) - def make_embed(self, fact: str) -> discord.Embed: + @staticmethod + def make_embed(fact: str) -> discord.Embed: """Makes a nice embed for the fact to be sent.""" return discord.Embed( colour=Colours.pink, -- cgit v1.2.3 From c837894af55deafff478bf8aa3b115d4589b6e07 Mon Sep 17 00:00:00 2001 From: Chris Date: Thu, 22 Apr 2021 21:59:29 +0100 Subject: Only use WrappedMessageConverter in the actual command signature --- bot/exts/evergreen/bookmark.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 16919d8c..f0b828f8 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -22,7 +22,7 @@ class Bookmark(commands.Cog): self.bot = bot @staticmethod - def build_bookmark_dm(target_message: WrappedMessageConverter, title: str) -> discord.Embed: + def build_bookmark_dm(target_message: discord.Message, title: str) -> discord.Embed: """Builds the embed to DM the bookmark requester.""" embed = discord.Embed( title=title, @@ -51,7 +51,7 @@ class Bookmark(commands.Cog): self, channel: discord.TextChannel, user: discord.Member, - target_message: WrappedMessageConverter, + target_message: discord.Message, title: str ) -> None: """Sends the bookmark DM, or sends an error embed when a user bookmarks a message.""" @@ -67,7 +67,7 @@ class Bookmark(commands.Cog): @staticmethod async def send_reaction_embed( channel: discord.TextChannel, - target_message: WrappedMessageConverter + target_message: discord.Message ) -> discord.Message: """Sends an embed, with a reaction, so users can react to bookmark the message too.""" message = await channel.send( -- cgit v1.2.3 From a1aa1a8ff0e9970cbb492282d10b6cb73aa17b28 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Mon, 3 May 2021 12:28:47 -0400 Subject: fix: Don't pass bot to __init__ --- bot/exts/pride/drag_queen_name.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/pride/drag_queen_name.py b/bot/exts/pride/drag_queen_name.py index 32ead1bc..9839f089 100644 --- a/bot/exts/pride/drag_queen_name.py +++ b/bot/exts/pride/drag_queen_name.py @@ -30,4 +30,4 @@ class DragNames(commands.Cog): def setup(bot: Bot) -> None: """Load the Drag Queen Cog.""" - bot.add_cog(DragNames(bot)) + bot.add_cog(DragNames()) -- cgit v1.2.3 From 5838d291ff56bac0aaf7a0cfc669c065ddda50b1 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Mon, 3 May 2021 13:18:25 -0400 Subject: chore: Clean Up the Valentines Season - Change commands.Bot type hints to bot.Bot - Remove the setting of Cog.bot if it isn't being used - Change ctx.author -> ctx.message.author --- bot/exts/valentines/be_my_valentine.py | 11 ++++++----- bot/exts/valentines/lovecalculator.py | 9 ++++----- bot/exts/valentines/movie_generator.py | 4 +++- bot/exts/valentines/myvalenstate.py | 7 ++++--- bot/exts/valentines/pickuplines.py | 8 +++----- bot/exts/valentines/savethedate.py | 8 +++----- bot/exts/valentines/valentine_zodiac.py | 8 ++++---- bot/exts/valentines/whoisvalentine.py | 8 +++----- 8 files changed, 30 insertions(+), 33 deletions(-) (limited to 'bot') diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index 09591cf8..051f09b8 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -8,6 +8,7 @@ import discord from discord.ext import commands from discord.ext.commands.cooldowns import BucketType +from bot.bot import Bot from bot.constants import Channels, Colours, Lovefest, Month from bot.utils.decorators import in_month from bot.utils.extensions import invoke_help_command @@ -50,7 +51,7 @@ class BeMyValentine(commands.Cog): async def add_role(self, ctx: commands.Context) -> None: """Adds the lovefest role.""" user = ctx.author - role = discord.utils.get(ctx.guild.roles, id=Lovefest.role_id) + role = ctx.guild.get_role(Lovefest.role_id) if Lovefest.role_id not in [role.id for role in ctx.message.author.roles]: await user.add_roles(role) await ctx.send("The Lovefest role has been added !") @@ -61,12 +62,12 @@ class BeMyValentine(commands.Cog): async def remove_role(self, ctx: commands.Context) -> None: """Removes the lovefest role.""" user = ctx.author - role = discord.utils.get(ctx.guild.roles, id=Lovefest.role_id) - if Lovefest.role_id not in [role.id for role in ctx.message.author.roles]: + role = ctx.guild.get_role(Lovefest.role_id) + if role not in ctx.author.roles: await ctx.send("You dont have the lovefest role.") else: await user.remove_roles(role) - await ctx.send("The lovefest role has been successfully removed !") + await ctx.send("The lovefest role has been successfully removed!") @commands.cooldown(1, 1800, BucketType.user) @commands.group(name='bemyvalentine', invoke_without_command=True) @@ -196,6 +197,6 @@ class BeMyValentine(commands.Cog): return valentine_compliment -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Be my Valentine Cog load.""" bot.add_cog(BeMyValentine(bot)) diff --git a/bot/exts/valentines/lovecalculator.py b/bot/exts/valentines/lovecalculator.py index 966acc82..c2a5da26 100644 --- a/bot/exts/valentines/lovecalculator.py +++ b/bot/exts/valentines/lovecalculator.py @@ -11,6 +11,8 @@ from discord import Member from discord.ext import commands from discord.ext.commands import BadArgument, Cog, clean_content +from bot.bot import Bot + log = logging.getLogger(__name__) with Path("bot/resources/valentines/love_matches.json").open(encoding="utf8") as file: @@ -21,9 +23,6 @@ with Path("bot/resources/valentines/love_matches.json").open(encoding="utf8") as class LoveCalculator(Cog): """A cog for calculating the love between two people.""" - def __init__(self, bot: commands.Bot): - self.bot = bot - @commands.command(aliases=('love_calculator', 'love_calc')) @commands.cooldown(rate=1, per=5, type=commands.BucketType.user) async def love(self, ctx: commands.Context, who: Union[Member, str], whom: Union[Member, str] = None) -> None: @@ -93,6 +92,6 @@ class LoveCalculator(Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Love calculator Cog load.""" - bot.add_cog(LoveCalculator(bot)) + bot.add_cog(LoveCalculator()) diff --git a/bot/exts/valentines/movie_generator.py b/bot/exts/valentines/movie_generator.py index 4df9e0d5..461255ff 100644 --- a/bot/exts/valentines/movie_generator.py +++ b/bot/exts/valentines/movie_generator.py @@ -6,6 +6,8 @@ from urllib import parse import discord from discord.ext import commands +from bot.bot import Bot + TMDB_API_KEY = environ.get("TMDB_API_KEY") log = logging.getLogger(__name__) @@ -59,6 +61,6 @@ class RomanceMovieFinder(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Romance movie Cog load.""" bot.add_cog(RomanceMovieFinder(bot)) diff --git a/bot/exts/valentines/myvalenstate.py b/bot/exts/valentines/myvalenstate.py index 041af7af..19e6b57f 100644 --- a/bot/exts/valentines/myvalenstate.py +++ b/bot/exts/valentines/myvalenstate.py @@ -7,6 +7,7 @@ from random import choice import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours log = logging.getLogger(__name__) @@ -46,7 +47,7 @@ class MyValenstate(commands.Cog): """Find the vacation spot(s) with the most matching characters to the invoking user.""" eq_chars = collections.defaultdict(int) if name is None: - author = ctx.message.author.name.lower().replace(' ', '') + author = ctx.author.name.lower().replace(' ', '') else: author = name.lower().replace(' ', '') @@ -60,7 +61,7 @@ class MyValenstate(commands.Cog): embed_title = "But there are more!" if len(matches) > 1: - leftovers = f"{', '.join(matches[:len(matches)-2])}, and {matches[len(matches)-1]}" + leftovers = f"{', '.join(matches[:-2])}, and {matches[-1]}" embed_text = f"You have {len(matches)} more matches, these being {leftovers}." elif len(matches) == 1: embed_title = "But there's another one!" @@ -81,6 +82,6 @@ class MyValenstate(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Valenstate Cog load.""" bot.add_cog(MyValenstate(bot)) diff --git a/bot/exts/valentines/pickuplines.py b/bot/exts/valentines/pickuplines.py index 74c7e68b..bb322016 100644 --- a/bot/exts/valentines/pickuplines.py +++ b/bot/exts/valentines/pickuplines.py @@ -6,6 +6,7 @@ from pathlib import Path import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours log = logging.getLogger(__name__) @@ -17,9 +18,6 @@ with open(Path("bot/resources/valentines/pickup_lines.json"), "r", encoding="utf class PickupLine(commands.Cog): """A cog that gives random cheesy pickup lines.""" - def __init__(self, bot: commands.Bot): - self.bot = bot - @commands.command() async def pickupline(self, ctx: commands.Context) -> None: """ @@ -39,6 +37,6 @@ class PickupLine(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Pickup lines Cog load.""" - bot.add_cog(PickupLine(bot)) + bot.add_cog(PickupLine()) diff --git a/bot/exts/valentines/savethedate.py b/bot/exts/valentines/savethedate.py index ac38d279..bda5d8c6 100644 --- a/bot/exts/valentines/savethedate.py +++ b/bot/exts/valentines/savethedate.py @@ -6,6 +6,7 @@ from pathlib import Path import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours log = logging.getLogger(__name__) @@ -19,9 +20,6 @@ with open(Path("bot/resources/valentines/date_ideas.json"), "r", encoding="utf8" class SaveTheDate(commands.Cog): """A cog that gives random suggestion for a Valentine's date.""" - def __init__(self, bot: commands.Bot): - self.bot = bot - @commands.command() async def savethedate(self, ctx: commands.Context) -> None: """Gives you ideas for what to do on a date with your valentine.""" @@ -36,6 +34,6 @@ class SaveTheDate(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Save the date Cog Load.""" - bot.add_cog(SaveTheDate(bot)) + bot.add_cog(SaveTheDate()) diff --git a/bot/exts/valentines/valentine_zodiac.py b/bot/exts/valentines/valentine_zodiac.py index 2696999f..237fe5db 100644 --- a/bot/exts/valentines/valentine_zodiac.py +++ b/bot/exts/valentines/valentine_zodiac.py @@ -9,6 +9,7 @@ from typing import Tuple, Union import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours log = logging.getLogger(__name__) @@ -20,8 +21,7 @@ HEART_EMOJIS = [":heart:", ":gift_heart:", ":revolving_hearts:", ":sparkling_hea class ValentineZodiac(commands.Cog): """A Cog that returns a counter compatible zodiac sign to the given user's zodiac sign.""" - def __init__(self, bot: commands.Bot): - self.bot = bot + def __init__(self): self.zodiacs, self.zodiac_fact = self.load_comp_json() @staticmethod @@ -141,6 +141,6 @@ class ValentineZodiac(commands.Cog): log.trace("Embed from date successfully sent.") -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Valentine zodiac Cog load.""" - bot.add_cog(ValentineZodiac(bot)) + bot.add_cog(ValentineZodiac()) diff --git a/bot/exts/valentines/whoisvalentine.py b/bot/exts/valentines/whoisvalentine.py index ab6b1ca1..73cdcf52 100644 --- a/bot/exts/valentines/whoisvalentine.py +++ b/bot/exts/valentines/whoisvalentine.py @@ -6,6 +6,7 @@ from random import choice import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours log = logging.getLogger(__name__) @@ -17,9 +18,6 @@ with open(Path("bot/resources/valentines/valentine_facts.json"), "r", encoding=" class ValentineFacts(commands.Cog): """A Cog for displaying facts about Saint Valentine.""" - def __init__(self, bot: commands.Bot): - self.bot = bot - @commands.command(aliases=('whoisvalentine', 'saint_valentine')) async def who_is_valentine(self, ctx: commands.Context) -> None: """Displays info about Saint Valentine.""" @@ -47,6 +45,6 @@ class ValentineFacts(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Who is Valentine Cog load.""" - bot.add_cog(ValentineFacts(bot)) + bot.add_cog(ValentineFacts()) -- cgit v1.2.3 From e9f33306b5344c5d7e0877b0bf63ff9c914e6f85 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Mon, 3 May 2021 13:36:26 -0400 Subject: Clean Up the Easter Season - Keep Consistent setup docstrings - Type hint to bot.Bot instead of commands.Bot - Don't set Cog.bot if it isn't used --- bot/exts/easter/april_fools_vids.py | 8 +++++--- bot/exts/easter/bunny_name_generator.py | 9 ++++----- bot/exts/easter/earth_photos.py | 5 +++-- bot/exts/easter/easter_riddle.py | 5 +++-- bot/exts/easter/egg_decorating.py | 8 +++----- bot/exts/easter/egg_facts.py | 2 +- bot/exts/easter/egghead_quiz.py | 10 +++++----- bot/exts/easter/save_the_planet.py | 10 ++++------ bot/exts/easter/traditions.py | 11 +++++------ 9 files changed, 33 insertions(+), 35 deletions(-) (limited to 'bot') diff --git a/bot/exts/easter/april_fools_vids.py b/bot/exts/easter/april_fools_vids.py index c7a3c014..84aa2913 100644 --- a/bot/exts/easter/april_fools_vids.py +++ b/bot/exts/easter/april_fools_vids.py @@ -4,6 +4,8 @@ from json import load from discord.ext import commands +from bot.bot import Bot + log = logging.getLogger(__name__) with open("bot/resources/easter/april_fools_vids.json", encoding="utf-8") as f: @@ -23,6 +25,6 @@ class AprilFoolVideos(commands.Cog): 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/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index 3ecf9be9..6d9e2a57 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -7,6 +7,8 @@ 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: @@ -16,9 +18,6 @@ with Path("bot/resources/easter/bunny_names.json").open("r", encoding="utf8") as 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]: """Check if Discord name contains spaces so we can bunnify an individual word in the name.""" new_name = re.split(r'[_.\s]', displayname) @@ -87,6 +86,6 @@ class BunnyNameGenerator(commands.Cog): await ctx.send(bunnified_name) -def setup(bot: commands.Bot) -> None: - """Bunny Name Generator Cog load.""" +def setup(bot: Bot) -> None: + """Load the Bunny Name Generator Cog.""" bot.add_cog(BunnyNameGenerator(bot)) diff --git a/bot/exts/easter/earth_photos.py b/bot/exts/easter/earth_photos.py index bf658391..d7e7ccc3 100644 --- a/bot/exts/easter/earth_photos.py +++ b/bot/exts/easter/earth_photos.py @@ -3,6 +3,7 @@ import logging import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours from bot.constants import Tokens @@ -12,7 +13,7 @@ log = logging.getLogger(__name__) class EarthPhotos(commands.Cog): """This cog contains the command for earth photos.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.command(aliases=["earth"]) @@ -55,7 +56,7 @@ class EarthPhotos(commands.Cog): await ctx.send(embed=embed) -def setup(bot: commands.Bot) -> None: +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.") diff --git a/bot/exts/easter/easter_riddle.py b/bot/exts/easter/easter_riddle.py index a93b3745..da66edf5 100644 --- a/bot/exts/easter/easter_riddle.py +++ b/bot/exts/easter/easter_riddle.py @@ -7,6 +7,7 @@ from pathlib import Path import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours, NEGATIVE_REPLIES log = logging.getLogger(__name__) @@ -20,7 +21,7 @@ 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 = "" @@ -106,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 a847388d..b8a8c6a7 100644 --- a/bot/exts/easter/egg_decorating.py +++ b/bot/exts/easter/egg_decorating.py @@ -10,6 +10,7 @@ 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__) @@ -33,9 +34,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.""" @@ -115,6 +113,6 @@ class EggDecorating(commands.Cog): return new_im -def setup(bot: commands.bot) -> None: - """Egg decorating Cog load.""" +def setup(bot: Bot) -> None: + """Load the Egg decorating Cog.""" bot.add_cog(EggDecorating(bot)) diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index 761e9059..78a5e592 100644 --- a/bot/exts/easter/egg_facts.py +++ b/bot/exts/easter/egg_facts.py @@ -57,5 +57,5 @@ class EasterFacts(commands.Cog): 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..e950bc2e 100644 --- a/bot/exts/easter/egghead_quiz.py +++ b/bot/exts/easter/egghead_quiz.py @@ -8,6 +8,7 @@ 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__) @@ -31,8 +32,7 @@ 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"]) @@ -114,6 +114,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..db9d3498 100644 --- a/bot/exts/easter/save_the_planet.py +++ b/bot/exts/easter/save_the_planet.py @@ -4,6 +4,7 @@ from pathlib import Path from discord import Embed from discord.ext import commands +from bot.bot import Bot from bot.utils.randomization import RandomCycle @@ -14,9 +15,6 @@ with Path("bot/resources/easter/save_the_planet.json").open('r', encoding='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')) async def savetheplanet(self, ctx: commands.Context) -> None: """Responds with a random tip on how to be eco-friendly and help our planet.""" @@ -24,6 +22,6 @@ class SaveThePlanet(commands.Cog): 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..19e69b98 100644 --- a/bot/exts/easter/traditions.py +++ b/bot/exts/easter/traditions.py @@ -5,6 +5,8 @@ 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: @@ -14,9 +16,6 @@ with open(Path("bot/resources/easter/traditions.json"), "r", encoding="utf8") as 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',)) async def easter_tradition(self, ctx: commands.Context) -> None: """Responds with a random tradition or custom.""" @@ -25,6 +24,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()) -- cgit v1.2.3 From 5189259ea3332bffa61863452f7f07bec0f4b533 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Mon, 3 May 2021 14:06:05 -0400 Subject: chore: End the sentence with a period --- bot/exts/evergreen/battleship.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/battleship.py b/bot/exts/evergreen/battleship.py index 813f998e..78fb0937 100644 --- a/bot/exts/evergreen/battleship.py +++ b/bot/exts/evergreen/battleship.py @@ -440,5 +440,5 @@ class Battleship(commands.Cog): def setup(bot: Bot) -> None: - """Load the Battleship cog""" + """Load the Battleship Cog.""" bot.add_cog(Battleship(bot)) -- cgit v1.2.3 From a7279c624b093ffe826edadbc999103083710953 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Mon, 3 May 2021 19:23:52 -0400 Subject: chore: Don't return a Message object when the return annotation is None --- bot/exts/easter/easter_riddle.py | 3 ++- bot/exts/easter/egg_decorating.py | 9 ++++++--- bot/exts/evergreen/battleship.py | 12 ++++++++---- bot/exts/evergreen/reddit.py | 9 ++++++--- bot/exts/evergreen/snakes/_snakes_cog.py | 6 ++++-- bot/exts/evergreen/trivia_quiz.py | 3 ++- bot/utils/pagination.py | 10 ++++++---- 7 files changed, 34 insertions(+), 18 deletions(-) (limited to 'bot') diff --git a/bot/exts/easter/easter_riddle.py b/bot/exts/easter/easter_riddle.py index da66edf5..9a253a6a 100644 --- a/bot/exts/easter/easter_riddle.py +++ b/bot/exts/easter/easter_riddle.py @@ -35,7 +35,8 @@ 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: diff --git a/bot/exts/easter/egg_decorating.py b/bot/exts/easter/egg_decorating.py index b8a8c6a7..1432fa31 100644 --- a/bot/exts/easter/egg_decorating.py +++ b/bot/exts/easter/egg_decorating.py @@ -54,7 +54,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) @@ -68,9 +69,11 @@ class EggDecorating(commands.Cog): 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 diff --git a/bot/exts/evergreen/battleship.py b/bot/exts/evergreen/battleship.py index 78fb0937..d4584ae8 100644 --- a/bot/exts/evergreen/battleship.py +++ b/bot/exts/evergreen/battleship.py @@ -379,10 +379,12 @@ class Battleship(commands.Cog): Make sure you have your DMs open so that the bot can message you. """ if self.already_playing(ctx.author): - return await ctx.send("You're already playing a game!") + await ctx.send("You're already playing a game!") + return if ctx.author in self.waiting: - return await ctx.send("You've already sent out a request for a player 2.") + await ctx.send("You've already sent out a request for a player 2.") + return announcement = await ctx.send( "**Battleship**: A new game is about to start!\n" @@ -402,12 +404,14 @@ class Battleship(commands.Cog): except asyncio.TimeoutError: self.waiting.remove(ctx.author) await announcement.delete() - return await ctx.send(f"{ctx.author.mention} Seems like there's no one here to play...") + await ctx.send(f"{ctx.author.mention} Seems like there's no one here to play...") + return if str(reaction.emoji) == CROSS_EMOJI: self.waiting.remove(ctx.author) await announcement.delete() - return await ctx.send(f"{ctx.author.mention} Game cancelled.") + await ctx.send(f"{ctx.author.mention} Game cancelled.") + return await announcement.delete() self.waiting.remove(ctx.author) diff --git a/bot/exts/evergreen/reddit.py b/bot/exts/evergreen/reddit.py index 518ffeb7..51a360b3 100644 --- a/bot/exts/evergreen/reddit.py +++ b/bot/exts/evergreen/reddit.py @@ -51,15 +51,18 @@ class Reddit(commands.Cog): try: posts = data["data"]["children"] except KeyError: - return await ctx.send('Subreddit not found!') + await ctx.send('Subreddit not found!') + return if not posts: - return await ctx.send('No posts available!') + await ctx.send('No posts available!') + return if posts[0]["data"]["over_18"] is True: - return await ctx.send( + await ctx.send( "You cannot access this Subreddit as it is meant for those who " "are 18 years or older." ) + return embed_titles = "" diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index 70093912..c8633ce7 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -643,7 +643,8 @@ class Snakes(Cog): data = await self._get_snek(name) if data.get('error'): - return await ctx.send('Could not fetch data from Wikipedia.') + await ctx.send('Could not fetch data from Wikipedia.') + return description = data["info"] @@ -900,7 +901,8 @@ class Snakes(Cog): color=SNAKE_COLOR ) - return await ctx.send(embed=embed) + await ctx.send(embed=embed) + return @snakes_group.command(name='sal') @locked() diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index f40375a6..bfd7d357 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -62,10 +62,11 @@ class TriviaQuiz(commands.Cog): # Stop game if running. if self.game_status[ctx.channel.id] is True: - return await ctx.send( + await ctx.send( f"Game is already running..." f"do `{self.bot.command_prefix}quiz stop`" ) + return # Send embed showing available categories if inputted category is invalid. if category is None: diff --git a/bot/utils/pagination.py b/bot/utils/pagination.py index a4d0cc56..a97dd023 100644 --- a/bot/utils/pagination.py +++ b/bot/utils/pagination.py @@ -79,7 +79,7 @@ class LinePaginator(Paginator): prefix: str = "", suffix: str = "", max_lines: Optional[int] = None, max_size: int = 500, empty: bool = True, restrict_to_user: User = None, timeout: int = 300, footer_text: str = None, url: str = None, - exception_on_empty_embed: bool = False): + exception_on_empty_embed: bool = False) -> None: """ Use a paginator and set of reactions to provide pagination over a set of lines. @@ -157,7 +157,8 @@ class LinePaginator(Paginator): log.trace(f"Setting embed url to '{url}'") log.debug("There's less than two pages, so we won't paginate - sending single page on its own") - return await ctx.send(embed=embed) + await ctx.send(embed=embed) + return else: if footer_text: embed.set_footer(text=f"{footer_text} (Page {current_page + 1}/{len(paginator.pages)})") @@ -302,7 +303,7 @@ class ImagePaginator(Paginator): @classmethod async def paginate(cls, pages: List[Tuple[str, str]], ctx: Context, embed: Embed, prefix: str = "", suffix: str = "", timeout: int = 300, - exception_on_empty_embed: bool = False): + exception_on_empty_embed: bool = False) -> None: """ Use a paginator and set of reactions to provide pagination over a set of title/image pairs. @@ -352,7 +353,8 @@ class ImagePaginator(Paginator): embed.set_image(url=image) if len(paginator.pages) <= 1: - return await ctx.send(embed=embed) + await ctx.send(embed=embed) + return embed.set_footer(text=f"Page {current_page + 1}/{len(paginator.pages)}") message = await ctx.send(embed=embed) -- cgit v1.2.3 From 8769624eac7e86e634fcef39c8fb81c4abc2f48e Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Tue, 4 May 2021 11:30:19 -0400 Subject: chore: Don't make content an empty string Co-authored-by: Matteo Bertucci --- bot/exts/evergreen/snakes/_snakes_cog.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index c8633ce7..e75f958c 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -829,7 +829,7 @@ class Snakes(Cog): ) ) - quiz = await ctx.send("", embed=embed) + quiz = await ctx.send(embed=embed) await self._validate_answer(ctx, quiz, answer, options) @snakes_group.command(name='name', aliases=('name_gen',)) -- cgit v1.2.3 From a6cc40ff3b323dff112d7f8c339e124f3a6d9980 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Tue, 4 May 2021 12:57:03 -0400 Subject: chore: Prefer double quotes over single quotes --- bot/bot.py | 2 +- bot/exts/christmas/advent_of_code/_helpers.py | 8 +- bot/exts/christmas/hanukkah_embed.py | 28 ++--- bot/exts/easter/april_fools_vids.py | 2 +- bot/exts/easter/bunny_name_generator.py | 16 +-- bot/exts/easter/earth_photos.py | 2 +- bot/exts/easter/egg_facts.py | 2 +- bot/exts/easter/egghead_quiz.py | 12 +- bot/exts/easter/save_the_planet.py | 4 +- bot/exts/easter/traditions.py | 2 +- bot/exts/evergreen/cheatsheet.py | 4 +- bot/exts/evergreen/connect_four.py | 6 +- bot/exts/evergreen/conversationstarters.py | 12 +- bot/exts/evergreen/emoji.py | 6 +- bot/exts/evergreen/error_handler.py | 4 +- bot/exts/evergreen/game.py | 4 +- bot/exts/evergreen/githubinfo.py | 42 +++---- bot/exts/evergreen/help.py | 74 ++++++------- bot/exts/evergreen/issues.py | 4 +- bot/exts/evergreen/minesweeper.py | 6 +- bot/exts/evergreen/movie.py | 20 ++-- bot/exts/evergreen/pythonfacts.py | 8 +- bot/exts/evergreen/recommend_game.py | 10 +- bot/exts/evergreen/reddit.py | 20 ++-- bot/exts/evergreen/snakes/_converter.py | 12 +- bot/exts/evergreen/snakes/_snakes_cog.py | 152 +++++++++++++------------- bot/exts/evergreen/snakes/_utils.py | 34 +++--- bot/exts/evergreen/source.py | 2 +- bot/exts/evergreen/speedrun.py | 2 +- bot/exts/evergreen/status_codes.py | 16 +-- bot/exts/evergreen/tic_tac_toe.py | 2 +- bot/exts/evergreen/trivia_quiz.py | 2 +- bot/exts/evergreen/wikipedia.py | 10 +- bot/exts/evergreen/wolfram.py | 4 +- bot/exts/evergreen/xkcd.py | 4 +- bot/exts/halloween/8ball.py | 2 +- bot/exts/halloween/candy_collection.py | 18 +-- bot/exts/halloween/hacktober-issue-finder.py | 2 +- bot/exts/halloween/hacktoberstats.py | 8 +- bot/exts/halloween/halloweenify.py | 4 +- bot/exts/halloween/monsterbio.py | 2 +- bot/exts/halloween/monstersurvey.py | 84 +++++++------- bot/exts/halloween/scarymovie.py | 22 ++-- bot/exts/halloween/spookygif.py | 6 +- bot/exts/halloween/spookynamerate.py | 2 +- bot/exts/halloween/spookyrating.py | 10 +- bot/exts/halloween/spookyreact.py | 14 +-- bot/exts/internal_eval/_internal_eval.py | 8 +- bot/exts/valentines/be_my_valentine.py | 34 +++--- bot/exts/valentines/myvalenstate.py | 10 +- bot/exts/valentines/pickuplines.py | 8 +- bot/exts/valentines/savethedate.py | 2 +- bot/exts/valentines/valentine_zodiac.py | 32 +++--- bot/exts/valentines/whoisvalentine.py | 12 +- bot/utils/__init__.py | 14 +-- bot/utils/checks.py | 4 +- bot/utils/decorators.py | 2 +- bot/utils/extensions.py | 4 +- bot/utils/halloween/spookifications.py | 10 +- bot/utils/pagination.py | 8 +- 60 files changed, 430 insertions(+), 430 deletions(-) (limited to 'bot') diff --git a/bot/bot.py b/bot/bot.py index 7e495940..b8de97aa 100644 --- a/bot/bot.py +++ b/bot/bot.py @@ -101,7 +101,7 @@ class Bot(commands.Bot): all_channels_ids = [channel.id for channel in self.get_all_channels()] for name, channel_id in vars(constants.Channels).items(): - if name.startswith('_'): + if name.startswith("_"): continue if channel_id not in all_channels_ids: log.error(f'Channel "{name}" with ID {channel_id} missing') diff --git a/bot/exts/christmas/advent_of_code/_helpers.py b/bot/exts/christmas/advent_of_code/_helpers.py index a16a4871..f4a258c0 100644 --- a/bot/exts/christmas/advent_of_code/_helpers.py +++ b/bot/exts/christmas/advent_of_code/_helpers.py @@ -108,7 +108,7 @@ def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict: # star view. We need that per star view to compute rank scores per star. for member in raw_leaderboard_data.values(): name = member["name"] if member["name"] else f"Anonymous #{member['id']}" - member_id = member['id'] + member_id = member["id"] leaderboard[member_id] = {"name": name, "score": 0, "star_1": 0, "star_2": 0} # Iterate over all days for this participant @@ -119,7 +119,7 @@ def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict: leaderboard[member_id][f"star_{star}"] += 1 # Record completion datetime for this participant for this day/star - completion_time = datetime.datetime.fromtimestamp(int(data['get_star_ts'])) + completion_time = datetime.datetime.fromtimestamp(int(data["get_star_ts"])) star_results[(day, star)].append( StarResult(member_id=member_id, completion_time=completion_time) ) @@ -133,7 +133,7 @@ def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict: if day in AdventOfCode.ignored_days: continue - sorted_result = sorted(results, key=operator.attrgetter('completion_time')) + sorted_result = sorted(results, key=operator.attrgetter("completion_time")) for rank, star_result in enumerate(sorted_result): leaderboard[star_result.member_id]["score"] += max_score - rank @@ -307,7 +307,7 @@ async def fetch_leaderboard(invalidate_cache: bool = False) -> dict: def get_summary_embed(leaderboard: dict) -> discord.Embed: """Get an embed with the current summary stats of the leaderboard.""" - leaderboard_url = leaderboard['full_leaderboard_url'] + leaderboard_url = leaderboard["full_leaderboard_url"] refresh_minutes = AdventOfCode.leaderboard_cache_expiry_seconds // 60 aoc_embed = discord.Embed( diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index cd8a9192..32002f76 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -28,15 +28,15 @@ class HanukkahEmbed(commands.Cog): hanukkah_dates = [] async with self.bot.http_session.get(self.url) as response: json_data = await response.json() - festivals = json_data['items'] + festivals = json_data["items"] for festival in festivals: - if festival['title'].startswith('Chanukah'): - date = festival['date'] + if festival["title"].startswith("Chanukah"): + date = festival["date"] hanukkah_dates.append(date) return hanukkah_dates @in_month(Month.DECEMBER) - @commands.command(name='hanukkah', aliases=['chanukah']) + @commands.command(name="hanukkah", aliases=["chanukah"]) async def hanukkah_festival(self, ctx: commands.Context) -> None: """Tells you about the Hanukkah Festivaltime of festival, festival day, etc).""" hanukkah_dates = await self.get_hanukkah_dates() @@ -56,7 +56,7 @@ class HanukkahEmbed(commands.Cog): month = str(today.month) year = str(today.year) embed = Embed() - embed.title = 'Hanukkah' + embed.title = "Hanukkah" embed.colour = Colours.blue if day in self.hanukkah_days and month in self.hanukkah_months and year in self.hanukkah_years: if int(day) == hanukkah_start_day: @@ -69,13 +69,13 @@ class HanukkahEmbed(commands.Cog): await ctx.send(embed=embed) return elif hours > hanukkah_start_hour: - embed.description = (f'It is the starting day of Hanukkah ! ' - f'Its been {hours-hanukkah_start_hour} hours hanukkah started !') + embed.description = (f"It is the starting day of Hanukkah ! " + f"Its been {hours-hanukkah_start_hour} hours hanukkah started !") await ctx.send(embed=embed) return festival_day = self.hanukkah_days.index(day) - number_suffixes = ['st', 'nd', 'rd', 'th'] - suffix = '' + number_suffixes = ["st", "nd", "rd", "th"] + suffix = "" if int(festival_day) == 1: suffix = number_suffixes[0] if int(festival_day) == 2: @@ -84,19 +84,19 @@ class HanukkahEmbed(commands.Cog): suffix = number_suffixes[2] if int(festival_day) > 3: suffix = number_suffixes[3] - message = '' + message = "" for _ in range(1, festival_day + 1): - message += ':menorah:' - embed.description = f'It is the {festival_day}{suffix} day of Hanukkah ! \n {message}' + message += ":menorah:" + embed.description = f"It is the {festival_day}{suffix} day of Hanukkah ! \n {message}" await ctx.send(embed=embed) else: if today < hanukkah_start: - festival_starting_month = hanukkah_start.strftime('%B') + festival_starting_month = hanukkah_start.strftime("%B") embed.description = (f"Hanukkah has not started yet. " f"Hanukkah will start at sundown on {hanukkah_start_day}th " f"of {festival_starting_month}.") else: - festival_end_month = hanukkah_end.strftime('%B') + festival_end_month = hanukkah_end.strftime("%B") embed.description = (f"Looks like you missed Hanukkah !" f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}.") diff --git a/bot/exts/easter/april_fools_vids.py b/bot/exts/easter/april_fools_vids.py index 84aa2913..3ce1f72a 100644 --- a/bot/exts/easter/april_fools_vids.py +++ b/bot/exts/easter/april_fools_vids.py @@ -15,7 +15,7 @@ with open("bot/resources/easter/april_fools_vids.json", encoding="utf-8") as f: class AprilFoolVideos(commands.Cog): """A cog for April Fools' that gets a random April Fools' video from Youtube.""" - @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.""" video = random.choice(ALL_VIDS) diff --git a/bot/exts/easter/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index 6d9e2a57..23f85226 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -20,7 +20,7 @@ class BunnyNameGenerator(commands.Cog): def find_separators(self, 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 @@ -33,11 +33,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: @@ -47,7 +47,7 @@ class BunnyNameGenerator(commands.Cog): def append_name(self, 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 @@ -74,7 +74,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) diff --git a/bot/exts/easter/earth_photos.py b/bot/exts/easter/earth_photos.py index d7e7ccc3..0e82e99a 100644 --- a/bot/exts/easter/earth_photos.py +++ b/bot/exts/easter/earth_photos.py @@ -21,7 +21,7 @@ class EarthPhotos(commands.Cog): """Returns a random photo of earth, sourced from Unsplash.""" async with ctx.typing(): async with self.bot.http_session.get( - 'https://api.unsplash.com/photos/random', + "https://api.unsplash.com/photos/random", params={"query": "planet_earth", "client_id": Tokens.unsplash_access_key} ) as r: jsondata = await r.json() diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index 78a5e592..8c93ca7b 100644 --- a/bot/exts/easter/egg_facts.py +++ b/bot/exts/easter/egg_facts.py @@ -41,7 +41,7 @@ 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() diff --git a/bot/exts/easter/egghead_quiz.py b/bot/exts/easter/egghead_quiz.py index e950bc2e..59c1f6f8 100644 --- a/bot/exts/easter/egghead_quiz.py +++ b/bot/exts/easter/egghead_quiz.py @@ -18,12 +18,12 @@ with open(Path("bot/resources/easter/egghead_questions.json"), "r", encoding="ut 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 diff --git a/bot/exts/easter/save_the_planet.py b/bot/exts/easter/save_the_planet.py index db9d3498..444bb030 100644 --- a/bot/exts/easter/save_the_planet.py +++ b/bot/exts/easter/save_the_planet.py @@ -8,14 +8,14 @@ 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: +with Path("bot/resources/easter/save_the_planet.json").open("r", encoding="utf8") as f: EMBED_DATA = RandomCycle(json.load(f)) class SaveThePlanet(commands.Cog): """A cog that teaches users how they can help our planet.""" - @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)) diff --git a/bot/exts/easter/traditions.py b/bot/exts/easter/traditions.py index 19e69b98..cb70f2d0 100644 --- a/bot/exts/easter/traditions.py +++ b/bot/exts/easter/traditions.py @@ -16,7 +16,7 @@ with open(Path("bot/resources/easter/traditions.json"), "r", encoding="utf8") as class Traditions(commands.Cog): """A cog which allows users to get a random easter tradition or custom from a random country.""" - @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)) diff --git a/bot/exts/evergreen/cheatsheet.py b/bot/exts/evergreen/cheatsheet.py index 57c6d0b0..86fae167 100644 --- a/bot/exts/evergreen/cheatsheet.py +++ b/bot/exts/evergreen/cheatsheet.py @@ -24,11 +24,11 @@ Unknown cheat sheet. Please try to reformulate your query. If the problem persists send a message in <#{Channels.dev_contrib}> """ -URL = 'https://cheat.sh/python/{search}' +URL = "https://cheat.sh/python/{search}" ESCAPE_TT = str.maketrans({"`": "\\`"}) ANSI_RE = re.compile(r"\x1b\[.*?m") # We need to pass headers as curl otherwise it would default to aiohttp which would return raw html. -HEADERS = {'User-Agent': 'curl/7.68.0'} +HEADERS = {"User-Agent": "curl/7.68.0"} class CheatSheet(commands.Cog): diff --git a/bot/exts/evergreen/connect_four.py b/bot/exts/evergreen/connect_four.py index df2a913a..929a15d8 100644 --- a/bot/exts/evergreen/connect_four.py +++ b/bot/exts/evergreen/connect_four.py @@ -55,8 +55,8 @@ class Game: async def print_grid(self) -> None: """Formats and outputs the Connect Four grid to the channel.""" title = ( - f'Connect 4: {self.player1.display_name}' - f' VS {self.bot.user.display_name if isinstance(self.player2, AI) else self.player2.display_name}' + f"Connect 4: {self.player1.display_name}" + f" VS {self.bot.user.display_name if isinstance(self.player2, AI) else self.player2.display_name}" ) rows = [" ".join(self.tokens[s] for s in row) for row in self.grid] @@ -67,7 +67,7 @@ class Game: if self.message: await self.message.edit(embed=embed) else: - self.message = await self.channel.send(content='Loading...') + self.message = await self.channel.send(content="Loading...") for emoji in self.unicode_numbers: await self.message.add_reaction(emoji) await self.message.add_reaction(CROSS_EMOJI) diff --git a/bot/exts/evergreen/conversationstarters.py b/bot/exts/evergreen/conversationstarters.py index 54fea0b3..4fe8c47c 100644 --- a/bot/exts/evergreen/conversationstarters.py +++ b/bot/exts/evergreen/conversationstarters.py @@ -9,7 +9,7 @@ from bot.constants import WHITELISTED_CHANNELS from bot.utils.decorators import whitelist_override from bot.utils.randomization import RandomCycle -SUGGESTION_FORM = 'https://forms.gle/zw6kkJqv8U43Nfjg9' +SUGGESTION_FORM = "https://forms.gle/zw6kkJqv8U43Nfjg9" with Path("bot/resources/evergreen/starter.yaml").open("r", encoding="utf8") as f: STARTERS = yaml.load(f, Loader=yaml.FullLoader) @@ -25,9 +25,9 @@ with Path("bot/resources/evergreen/py_topics.yaml").open("r", encoding="utf8") a ALL_ALLOWED_CHANNELS = list(PY_TOPICS.keys()) + list(WHITELISTED_CHANNELS) # Putting all topics into one dictionary and shuffling lists to reduce same-topic repetitions. -ALL_TOPICS = {'default': STARTERS, **PY_TOPICS} +ALL_TOPICS = {"default": STARTERS, **PY_TOPICS} TOPICS = { - channel: RandomCycle(topics or ['No topics found for this channel.']) + channel: RandomCycle(topics or ["No topics found for this channel."]) for channel, topics in ALL_TOPICS.items() } @@ -46,7 +46,7 @@ class ConvoStarters(commands.Cog): Otherwise, a random conversation topic will be received by the user. """ # No matter what, the form will be shown. - embed = Embed(description=f'Suggest more topics [here]({SUGGESTION_FORM})!', color=Color.blurple()) + embed = Embed(description=f"Suggest more topics [here]({SUGGESTION_FORM})!", color=Color.blurple()) try: # Fetching topics. @@ -54,11 +54,11 @@ class ConvoStarters(commands.Cog): # If the channel isn't Python-related. except KeyError: - embed.title = f'**{next(TOPICS["default"])}**' + embed.title = f"**{next(TOPICS['default'])}**" # If the channel ID doesn't have any topics. else: - embed.title = f'**{next(channel_topics)}**' + embed.title = f"**{next(channel_topics)}**" finally: await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/emoji.py b/bot/exts/evergreen/emoji.py index 8e540712..e7452a15 100644 --- a/bot/exts/evergreen/emoji.py +++ b/bot/exts/evergreen/emoji.py @@ -46,9 +46,9 @@ class Emojis(commands.Cog): else: emoji_info = f"There is **{len(category_emojis)}** emoji in the **{category_name}** category." if emoji_choice.animated: - msg.append(f' {emoji_info}') + msg.append(f" {emoji_info}") else: - msg.append(f'<:{emoji_choice.name}:{emoji_choice.id}> {emoji_info}') + msg.append(f"<:{emoji_choice.name}:{emoji_choice.id}> {emoji_info}") return embed, msg @staticmethod @@ -64,7 +64,7 @@ class Emojis(commands.Cog): for emoji in emojis: emoji_dict[emoji.name.split("_")[0]].append(emoji) - error_comp = ', '.join(emoji_dict) + error_comp = ", ".join(emoji_dict) msg.append(f"These are the valid emoji categories:\n```{error_comp}```") return embed, msg diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index dabd0ab5..5cd8d28d 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -40,7 +40,7 @@ class CommandErrorHandler(commands.Cog): @commands.Cog.listener() async def on_command_error(self, ctx: commands.Context, error: commands.CommandError) -> None: """Activates when a command opens an error.""" - if getattr(error, 'handled', False): + if getattr(error, "handled", False): logging.debug(f"Command {ctx.command} had its error already handled locally; ignoring.") return @@ -49,7 +49,7 @@ class CommandErrorHandler(commands.Cog): parent_command = f"{ctx.command} " ctx = subctx - error = getattr(error, 'original', error) + error = getattr(error, "original", error) logging.debug( f"Error Encountered: {type(error).__name__} - {str(error)}, " f"Command: {ctx.command}, " diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 24872e76..7abbadcd 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -176,7 +176,7 @@ class Games(Cog): "Invalid OAuth credentials. Unloading Games cog. " f"OAuth response message: {result['message']}" ) - self.bot.remove_cog('Games') + self.bot.remove_cog("Games") return @@ -260,7 +260,7 @@ class Games(Cog): display_possibilities = "`, `".join(p[1] for p in possibilities) await ctx.send( f"Invalid genre `{genre}`. " - f"{f'Maybe you meant `{display_possibilities}`?' if display_possibilities else ''}" + f"Maybe you meant `{display_possibilities}`?" if display_possibilities else '' ) return elif len(possibilities) == 1: diff --git a/bot/exts/evergreen/githubinfo.py b/bot/exts/evergreen/githubinfo.py index fd100a7c..24479c79 100644 --- a/bot/exts/evergreen/githubinfo.py +++ b/bot/exts/evergreen/githubinfo.py @@ -27,14 +27,14 @@ class GithubInfo(commands.Cog): async with self.bot.http_session.get(url) as r: return await r.json() - @commands.group(name='github', aliases=('gh', 'git')) + @commands.group(name="github", aliases=("gh", "git")) @commands.cooldown(1, 10, BucketType.user) async def github_group(self, ctx: commands.Context) -> None: """Commands for finding information related to GitHub.""" if ctx.invoked_subcommand is None: await invoke_help_command(ctx) - @github_group.command(name='user', aliases=('userinfo',)) + @github_group.command(name="user", aliases=("userinfo",)) async def github_user_info(self, ctx: commands.Context, username: str) -> None: """Fetches a user's GitHub information.""" async with ctx.typing(): @@ -51,31 +51,31 @@ class GithubInfo(commands.Cog): await ctx.send(embed=embed) return - org_data = await self.fetch_data(user_data['organizations_url']) + org_data = await self.fetch_data(user_data["organizations_url"]) orgs = [f"[{org['login']}](https://github.com/{org['login']})" for org in org_data] - orgs_to_add = ' | '.join(orgs) + orgs_to_add = " | ".join(orgs) - gists = user_data['public_gists'] + gists = user_data["public_gists"] # Forming blog link - if user_data['blog'].startswith("http"): # Blog link is complete - blog = user_data['blog'] - elif user_data['blog']: # Blog exists but the link is not complete + if user_data["blog"].startswith("http"): # Blog link is complete + blog = user_data["blog"] + elif user_data["blog"]: # Blog exists but the link is not complete blog = f"https://{user_data['blog']}" else: blog = "No website link available" embed = discord.Embed( title=f"`{user_data['login']}`'s GitHub profile info", - description=f"```{user_data['bio']}```\n" if user_data['bio'] is not None else "", + description=f"```{user_data['bio']}```\n" if user_data["bio"] is not None else "", colour=discord.Colour.blurple(), - url=user_data['html_url'], - timestamp=datetime.strptime(user_data['created_at'], "%Y-%m-%dT%H:%M:%SZ") + url=user_data["html_url"], + timestamp=datetime.strptime(user_data["created_at"], "%Y-%m-%dT%H:%M:%SZ") ) - embed.set_thumbnail(url=user_data['avatar_url']) + embed.set_thumbnail(url=user_data["avatar_url"]) embed.set_footer(text="Account created at") - if user_data['type'] == "User": + if user_data["type"] == "User": embed.add_field( name="Followers", @@ -91,7 +91,7 @@ class GithubInfo(commands.Cog): value=f"[{user_data['public_repos']}]({user_data['html_url']}?tab=repositories)" ) - if user_data['type'] == "User": + if user_data["type"] == "User": embed.add_field(name="Gists", value=f"[{gists}](https://gist.github.com/{quote(username, safe='')})") embed.add_field( @@ -109,8 +109,8 @@ class GithubInfo(commands.Cog): The repository should look like `user/reponame` or `user reponame`. """ - repo = '/'.join(repo) - if repo.count('/') != 1: + repo = "/".join(repo) + if repo.count("/") != 1: embed = discord.Embed( title=random.choice(NEGATIVE_REPLIES), description="The repository should look like `user/reponame` or `user reponame`.", @@ -135,10 +135,10 @@ class GithubInfo(commands.Cog): return embed = discord.Embed( - title=repo_data['name'], + title=repo_data["name"], description=repo_data["description"], colour=discord.Colour.blurple(), - url=repo_data['html_url'] + url=repo_data["html_url"] ) # If it's a fork, then it will have a parent key @@ -148,7 +148,7 @@ class GithubInfo(commands.Cog): except KeyError: log.debug("Repository is not a fork.") - repo_owner = repo_data['owner'] + repo_owner = repo_data["owner"] embed.set_author( name=repo_owner["login"], @@ -156,8 +156,8 @@ class GithubInfo(commands.Cog): icon_url=repo_owner["avatar_url"] ) - repo_created_at = datetime.strptime(repo_data['created_at'], "%Y-%m-%dT%H:%M:%SZ").strftime("%d/%m/%Y") - last_pushed = datetime.strptime(repo_data['pushed_at'], "%Y-%m-%dT%H:%M:%SZ").strftime("%d/%m/%Y at %H:%M") + repo_created_at = datetime.strptime(repo_data["created_at"], "%Y-%m-%dT%H:%M:%SZ").strftime("%d/%m/%Y") + last_pushed = datetime.strptime(repo_data["pushed_at"], "%Y-%m-%dT%H:%M:%SZ").strftime("%d/%m/%Y at %H:%M") embed.set_footer( text=( diff --git a/bot/exts/evergreen/help.py b/bot/exts/evergreen/help.py index f557e42e..bfaf25f1 100644 --- a/bot/exts/evergreen/help.py +++ b/bot/exts/evergreen/help.py @@ -22,14 +22,14 @@ from bot.utils.pagination import ( DELETE_EMOJI = Emojis.trashcan REACTIONS = { - FIRST_EMOJI: 'first', - LEFT_EMOJI: 'back', - RIGHT_EMOJI: 'next', - LAST_EMOJI: 'end', - DELETE_EMOJI: 'stop', + FIRST_EMOJI: "first", + LEFT_EMOJI: "back", + RIGHT_EMOJI: "next", + LAST_EMOJI: "end", + DELETE_EMOJI: "stop", } -Cog = namedtuple('Cog', ['name', 'description', 'commands']) +Cog = namedtuple("Cog", ["name", "description", "commands"]) log = logging.getLogger(__name__) @@ -87,7 +87,7 @@ class HelpSession: # set the query details for the session if command: - query_str = ' '.join(command) + query_str = " ".join(command) self.query = self._get_query(query_str) self.description = self.query.description or self.query.help else: @@ -191,7 +191,7 @@ class HelpSession: self.reset_timeout() # Run relevant action method - action = getattr(self, f'do_{REACTIONS[emoji]}', None) + action = getattr(self, f"do_{REACTIONS[emoji]}", None) if action: await action() @@ -234,11 +234,11 @@ class HelpSession: if cmd.cog: try: if cmd.cog.category: - return f'**{cmd.cog.category}**' + return f"**{cmd.cog.category}**" except AttributeError: pass - return f'**{cmd.cog_name}**' + return f"**{cmd.cog_name}**" else: return "**\u200bNo Category:**" @@ -262,47 +262,47 @@ class HelpSession: # if default is not an empty string or None if show_default: - results.append(f'[{name}={param.default}]') + results.append(f"[{name}={param.default}]") else: - results.append(f'[{name}]') + results.append(f"[{name}]") # if variable length argument elif param.kind == param.VAR_POSITIONAL: - results.append(f'[{name}...]') + results.append(f"[{name}...]") # if required else: - results.append(f'<{name}>') + results.append(f"<{name}>") return f"{cmd.name} {' '.join(results)}" async def build_pages(self) -> None: """Builds the list of content pages to be paginated through in the help message, as a list of str.""" # Use LinePaginator to restrict embed line height - paginator = LinePaginator(prefix='', suffix='', max_lines=self._max_lines) + paginator = LinePaginator(prefix="", suffix="", max_lines=self._max_lines) prefix = constants.Client.prefix # show signature if query is a command if isinstance(self.query, commands.Command): signature = self._get_command_params(self.query) - parent = self.query.full_parent_name + ' ' if self.query.parent else '' - paginator.add_line(f'**```{prefix}{parent}{signature}```**') + parent = self.query.full_parent_name + " " if self.query.parent else "" + paginator.add_line(f"**```{prefix}{parent}{signature}```**") aliases = [f"`{alias}`" if not parent else f"`{parent} {alias}`" for alias in self.query.aliases] aliases += [f"`{alias}`" for alias in getattr(self.query, "root_aliases", ())] aliases = ", ".join(sorted(aliases)) if aliases: - paginator.add_line(f'**Can also use:** {aliases}\n') + paginator.add_line(f"**Can also use:** {aliases}\n") if not await self.query.can_run(self._ctx): - paginator.add_line('***You cannot run this command.***\n') + paginator.add_line("***You cannot run this command.***\n") if isinstance(self.query, Cog): - paginator.add_line(f'**{self.query.name}**') + paginator.add_line(f"**{self.query.name}**") if self.description: - paginator.add_line(f'*{self.description}*') + paginator.add_line(f"*{self.description}*") # list all children commands of the queried object if isinstance(self.query, (commands.GroupMixin, Cog)): @@ -319,13 +319,13 @@ class HelpSession: return if isinstance(self.query, Cog): - grouped = (('**Commands:**', self.query.commands),) + grouped = (("**Commands:**", self.query.commands),) elif isinstance(self.query, commands.Command): - grouped = (('**Subcommands:**', self.query.commands),) + grouped = (("**Subcommands:**", self.query.commands),) # don't show prefix for subcommands - prefix = '' + prefix = "" # otherwise sort and organise all commands into categories else: @@ -347,7 +347,7 @@ class HelpSession: continue # see if the user can run the command - strikeout = '' + strikeout = "" # Patch to make the !help command work outside of #bot-commands again # This probably needs a proper rewrite, but this will make it work in @@ -361,16 +361,16 @@ class HelpSession: # skip if we don't show commands they can't run if self._only_can_run: continue - strikeout = '~~' + strikeout = "~~" signature = self._get_command_params(command) info = f"{strikeout}**`{prefix}{signature}`**{strikeout}" # handle if the command has no docstring if command.short_doc: - cat_cmds.append(f'{info}\n*{command.short_doc}*') + cat_cmds.append(f"{info}\n*{command.short_doc}*") else: - cat_cmds.append(f'{info}\n*No details provided.*') + cat_cmds.append(f"{info}\n*No details provided.*") # state var for if the category should be added next print_cat = 1 @@ -379,7 +379,7 @@ class HelpSession: for details in cat_cmds: # keep details together, paginating early if it won't fit - lines_adding = len(details.split('\n')) + print_cat + lines_adding = len(details.split("\n")) + print_cat if paginator._linecount + lines_adding > self._max_lines: paginator._linecount = 0 new_page = True @@ -390,7 +390,7 @@ class HelpSession: if print_cat: if new_page: - paginator.add_line('') + paginator.add_line("") paginator.add_line(category) print_cat = 0 @@ -412,7 +412,7 @@ class HelpSession: page_count = len(self._pages) if page_count > 1: - embed.set_footer(text=f'Page {self._current_page+1} / {page_count}') + embed.set_footer(text=f"Page {self._current_page+1} / {page_count}") return embed @@ -496,7 +496,7 @@ class HelpSession: class Help(DiscordCog): """Custom Embed Pagination Help feature.""" - @commands.command('help') + @commands.command("help") async def new_help(self, ctx: Context, *commands) -> None: """Shows Command Help.""" try: @@ -507,8 +507,8 @@ class Help(DiscordCog): embed.title = str(error) if error.possible_matches: - matches = '\n'.join(error.possible_matches.keys()) - embed.description = f'**Did you mean:**\n`{matches}`' + matches = "\n".join(error.possible_matches.keys()) + embed.description = f"**Did you mean:**\n`{matches}`" await ctx.send(embed=embed) @@ -519,7 +519,7 @@ def unload(bot: Bot) -> None: This is run if the cog raises an exception on load, or if the extension is unloaded. """ - bot.remove_command('help') + bot.remove_command("help") bot.add_command(bot._old_help) @@ -534,8 +534,8 @@ def setup(bot: Bot) -> None: If an exception is raised during the loading of the cog, `unload` will be called in order to reinstate the original help command. """ - bot._old_help = bot.get_command('help') - bot.remove_command('help') + bot._old_help = bot.get_command("help") + bot.remove_command("help") try: bot.add_cog(Help()) diff --git a/bot/exts/evergreen/issues.py b/bot/exts/evergreen/issues.py index d7ee99c0..5bbc57c6 100644 --- a/bot/exts/evergreen/issues.py +++ b/bot/exts/evergreen/issues.py @@ -158,7 +158,7 @@ class Issues(commands.Cog): issue_url = json_data.get("html_url") - return IssueState(repository, number, issue_url, json_data.get('title', ''), emoji) + return IssueState(repository, number, issue_url, json_data.get("title", ""), emoji) @staticmethod def format_embed( @@ -177,7 +177,7 @@ class Issues(commands.Cog): resp = discord.Embed( colour=Colours.bright_green, - description='\n'.join(description_list) + description="\n".join(description_list) ) embed_url = f"https://github.com/{user}/{repository}" if repository else f"https://github.com/{user}" diff --git a/bot/exts/evergreen/minesweeper.py b/bot/exts/evergreen/minesweeper.py index d0cc28c5..f2c5e656 100644 --- a/bot/exts/evergreen/minesweeper.py +++ b/bot/exts/evergreen/minesweeper.py @@ -38,7 +38,7 @@ class CoordinateConverter(commands.Converter): async def convert(self, ctx: commands.Context, coordinate: str) -> typing.Tuple[int, int]: """Take in a coordinate string and turn it into an (x, y) tuple.""" if not 2 <= len(coordinate) <= 3: - raise commands.BadArgument('Invalid co-ordinate provided.') + raise commands.BadArgument("Invalid co-ordinate provided.") coordinate = coordinate.lower() if coordinate[0].isalpha(): @@ -51,7 +51,7 @@ class CoordinateConverter(commands.Converter): if not digit.isdigit(): raise commands.BadArgument - x = ord(letter) - ord('a') + x = ord(letter) - ord("a") y = int(digit) - 1 if (not 0 <= x <= 9) or (not 0 <= y <= 9): @@ -82,7 +82,7 @@ class Minesweeper(commands.Cog): def __init__(self, _bot: Bot) -> None: self.games: GamesDict = {} # Store the currently running games - @commands.group(name='minesweeper', aliases=('ms',), invoke_without_command=True) + @commands.group(name="minesweeper", aliases=("ms",), invoke_without_command=True) async def minesweeper_group(self, ctx: commands.Context) -> None: """Commands for Playing Minesweeper.""" await invoke_help_command(ctx) diff --git a/bot/exts/evergreen/movie.py b/bot/exts/evergreen/movie.py index 488e5142..e67f8d04 100644 --- a/bot/exts/evergreen/movie.py +++ b/bot/exts/evergreen/movie.py @@ -53,7 +53,7 @@ class Movie(Cog): def __init__(self, bot: Bot): self.http_session: ClientSession = bot.http_session - @group(name='movies', aliases=['movie'], invoke_without_command=True) + @group(name="movies", aliases=["movie"], invoke_without_command=True) async def movies(self, ctx: Context, genre: str = "", amount: int = 5) -> None: """ Get random movies by specifying genre. Also support amount parameter, that define how much movies will be shown. @@ -89,7 +89,7 @@ class Movie(Cog): # Get movies list from TMDB, check if results key in result. When not, raise error. movies = await self.get_movies_list(self.http_session, MovieGenres[genre].value, page) - if 'results' not in movies.keys(): + if "results" not in movies.keys(): err_msg = f"There is problem while making TMDB API request. Response Code: {result['status_code']}, " \ f"{result['status_message']}." await ctx.send(err_msg) @@ -101,7 +101,7 @@ class Movie(Cog): await ImagePaginator.paginate(pages, ctx, embed) - @movies.command(name='genres', aliases=['genre', 'g']) + @movies.command(name="genres", aliases=["genre", "g"]) async def genres(self, ctx: Context) -> None: """Show all currently available genres for .movies command.""" await ctx.send(f"Current available genres: {', '.join('`' + genre.name + '`' for genre in MovieGenres)}") @@ -130,7 +130,7 @@ class Movie(Cog): pages = [] for i in range(amount): - movie_id = movies['results'][i]['id'] + movie_id = movies["results"][i]["id"] movie = await self.get_movie(client, movie_id) page, img = await self.create_page(movie) @@ -151,7 +151,7 @@ class Movie(Cog): # Add title + tagline (if not empty) text += f"**{movie['title']}**\n" - if movie['tagline']: + if movie["tagline"]: text += f"{movie['tagline']}\n\n" else: text += "\n" @@ -162,8 +162,8 @@ class Movie(Cog): text += "__**Production Information**__\n" - companies = movie['production_companies'] - countries = movie['production_countries'] + companies = movie["production_companies"] + countries = movie["production_countries"] text += f"**Made by:** {', '.join(company['name'] for company in companies)}\n" text += f"**Made in:** {', '.join(country['name'] for country in countries)}\n\n" @@ -173,8 +173,8 @@ class Movie(Cog): budget = f"{movie['budget']:,d}" if movie['budget'] else "?" revenue = f"{movie['revenue']:,d}" if movie['revenue'] else "?" - if movie['runtime'] is not None: - duration = divmod(movie['runtime'], 60) + if movie["runtime"] is not None: + duration = divmod(movie["runtime"], 60) else: duration = ("?", "?") @@ -182,7 +182,7 @@ class Movie(Cog): text += f"**Revenue:** ${revenue}\n" text += f"**Duration:** {f'{duration[0]} hour(s) {duration[1]} minute(s)'}\n\n" - text += movie['overview'] + text += movie["overview"] img = f"http://image.tmdb.org/t/p/w200{movie['poster_path']}" diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index 73234d55..2dc4996f 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -6,7 +6,7 @@ from discord.ext import commands from bot.bot import Bot from bot.constants import Colours -with open('bot/resources/evergreen/python_facts.txt') as file: +with open("bot/resources/evergreen/python_facts.txt") as file: FACTS = itertools.cycle(list(file)) COLORS = itertools.cycle([Colours.python_blue, Colours.python_yellow]) @@ -15,13 +15,13 @@ COLORS = itertools.cycle([Colours.python_blue, Colours.python_yellow]) class PythonFacts(commands.Cog): """Sends a random fun fact about Python.""" - @commands.command(name='pythonfact', aliases=['pyfact']) + @commands.command(name="pythonfact", aliases=["pyfact"]) async def get_python_fact(self, ctx: commands.Context) -> None: """Sends a Random fun fact about Python.""" - embed = discord.Embed(title='Python Facts', + embed = discord.Embed(title="Python Facts", description=next(FACTS), colour=next(COLORS)) - embed.add_field(name='Suggestions', + embed.add_field(name="Suggestions", value="Suggest more facts [here!](https://github.com/python-discord/meta/discussions/93)") await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/recommend_game.py b/bot/exts/evergreen/recommend_game.py index be329f44..340a42d3 100644 --- a/bot/exts/evergreen/recommend_game.py +++ b/bot/exts/evergreen/recommend_game.py @@ -13,7 +13,7 @@ game_recs = [] # Populate the list `game_recs` with resource files for rec_path in Path("bot/resources/evergreen/game_recs").glob("*.json"): - with rec_path.open(encoding='utf8') as file: + with rec_path.open(encoding="utf8") as file: data = json.load(file) game_recs.append(data) shuffle(game_recs) @@ -26,7 +26,7 @@ class RecommendGame(commands.Cog): self.bot = bot self.index = 0 - @commands.command(name="recommendgame", aliases=['gamerec']) + @commands.command(name="recommendgame", aliases=["gamerec"]) async def recommend_game(self, ctx: commands.Context) -> None: """Sends an Embed of a random game recommendation.""" if self.index >= len(game_recs): @@ -35,14 +35,14 @@ class RecommendGame(commands.Cog): game = game_recs[self.index] self.index += 1 - author = self.bot.get_user(int(game['author'])) + author = self.bot.get_user(int(game["author"])) # Creating and formatting Embed embed = discord.Embed(color=discord.Colour.blue()) if author is not None: embed.set_author(name=author.name, icon_url=author.avatar_url) - embed.set_image(url=game['image']) - embed.add_field(name='Recommendation: ' + game['title'] + '\n' + game['link'], value=game['description']) + embed.set_image(url=game["image"]) + embed.add_field(name="Recommendation: " + game["title"] + "\n" + game["link"], value=game["description"]) await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/reddit.py b/bot/exts/evergreen/reddit.py index 51a360b3..82af6ce9 100644 --- a/bot/exts/evergreen/reddit.py +++ b/bot/exts/evergreen/reddit.py @@ -21,18 +21,18 @@ class Reddit(commands.Cog): """Send a get request to the reddit API and get json response.""" session = self.bot.http_session params = { - 'limit': 50 + "limit": 50 } headers = { - 'User-Agent': 'Iceman' + "User-Agent": "Iceman" } async with session.get(url=url, params=params, headers=headers) as response: return await response.json() - @commands.command(name='reddit') + @commands.command(name="reddit") @commands.cooldown(1, 10, BucketType.user) - async def get_reddit(self, ctx: commands.Context, subreddit: str = 'python', sort: str = "hot") -> None: + async def get_reddit(self, ctx: commands.Context, subreddit: str = "python", sort: str = "hot") -> None: """ Fetch reddit posts by using this command. @@ -46,15 +46,15 @@ class Reddit(commands.Cog): await ctx.send(f"Invalid sorting: {sort}\nUsing default sorting: `Hot`") sort = "hot" - data = await self.fetch(f'https://www.reddit.com/r/{subreddit}/{sort}/.json') + data = await self.fetch(f"https://www.reddit.com/r/{subreddit}/{sort}/.json") try: posts = data["data"]["children"] except KeyError: - await ctx.send('Subreddit not found!') + await ctx.send("Subreddit not found!") return if not posts: - await ctx.send('No posts available!') + await ctx.send("No posts available!") return if posts[0]["data"]["over_18"] is True: @@ -106,12 +106,12 @@ class Reddit(commands.Cog): post_stats = f"{image_emoji} " image_url = post_url - votes = f'{upvote_emoji}{post["data"]["ups"]}' - comments = f'{comment_emoji}\u2002{ post["data"]["num_comments"]}' + votes = f"{upvote_emoji}{post['data']['ups']}" + comments = f"{comment_emoji}\u2002{ post['data']['num_comments']}" post_stats += ( f"\u2002{votes}\u2003" f"{comments}" - f'\u2003{user_emoji}\u2002{post["data"]["author"]}\n' + f"\u2003{user_emoji}\u2002{post['data']['author']}\n" ) embed_titles += f"{post_stats}\n" page_text = f"**[{post_title}]({post_url})**\n{post_stats}\n{post['data']['selftext'][0:200]}" diff --git a/bot/exts/evergreen/snakes/_converter.py b/bot/exts/evergreen/snakes/_converter.py index eee248cf..0ca10d6c 100644 --- a/bot/exts/evergreen/snakes/_converter.py +++ b/bot/exts/evergreen/snakes/_converter.py @@ -24,8 +24,8 @@ class Snake(Converter): await self.build_list() name = name.lower() - if name == 'python': - return 'Python (programming language)' + if name == "python": + return "Python (programming language)" def get_potential(iterable: Iterable, *, threshold: int = 80) -> List[str]: nonlocal name @@ -47,12 +47,12 @@ class Snake(Converter): if name.lower() in self.special_cases: return self.special_cases.get(name.lower(), name.lower()) - names = {snake['name']: snake['scientific'] for snake in self.snakes} + names = {snake["name"]: snake["scientific"] for snake in self.snakes} all_names = names.keys() | names.values() timeout = len(all_names) * (3 / 4) embed = discord.Embed( - title='Found multiple choices. Please choose the correct one.', colour=0x59982F) + title="Found multiple choices. Please choose the correct one.", colour=0x59982F) embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url) name = await disambiguate(ctx, get_potential(all_names), timeout=timeout, embed=embed) @@ -70,7 +70,7 @@ class Snake(Converter): if cls.special_cases is None: with (SNAKE_RESOURCES / "special_snakes.json").open(encoding="utf8") as snakefile: special_cases = json.load(snakefile) - cls.special_cases = {snake['name'].lower(): snake for snake in special_cases} + cls.special_cases = {snake["name"].lower(): snake for snake in special_cases} @classmethod async def random(cls) -> str: @@ -81,5 +81,5 @@ class Snake(Converter): so I can get it from here. """ await cls.build_list() - names = [snake['scientific'] for snake in cls.snakes] + names = [snake["scientific"] for snake in cls.snakes] return random.choice(names) diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index c8633ce7..d95970da 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -143,8 +143,8 @@ class Snakes(Cog): https://github.com/python-discord/code-jam-1 """ - wiki_brief = re.compile(r'(.*?)(=+ (.*?) =+)', flags=re.DOTALL) - valid_image_extensions = ('gif', 'png', 'jpeg', 'jpg', 'webp') + wiki_brief = re.compile(r"(.*?)(=+ (.*?) =+)", flags=re.DOTALL) + valid_image_extensions = ("gif", "png", "jpeg", "jpg", "webp") def __init__(self, bot: Bot): self.active_sal = {} @@ -183,28 +183,28 @@ class Snakes(Cog): # Get the size of the snake icon, configure the height of the image box (yes, it changes) icon_width = 347 # Hardcoded, not much i can do about that icon_height = int((icon_width / snake.width) * snake.height) - frame_copies = icon_height // CARD['frame'].height + 1 + frame_copies = icon_height // CARD["frame"].height + 1 snake.thumbnail((icon_width, icon_height)) # Get the dimensions of the final image - main_height = icon_height + CARD['top'].height + CARD['bottom'].height - main_width = CARD['frame'].width + main_height = icon_height + CARD["top"].height + CARD["bottom"].height + main_width = CARD["frame"].width # Start creating the foreground foreground = Image.new("RGBA", (main_width, main_height), (0, 0, 0, 0)) - foreground.paste(CARD['top'], (0, 0)) + foreground.paste(CARD["top"], (0, 0)) # Generate the frame borders to the correct height for offset in range(frame_copies): - position = (0, CARD['top'].height + offset * CARD['frame'].height) - foreground.paste(CARD['frame'], position) + position = (0, CARD["top"].height + offset * CARD["frame"].height) + foreground.paste(CARD["frame"], position) # Add the image and bottom part of the image - foreground.paste(snake, (36, CARD['top'].height)) # Also hardcoded :( - foreground.paste(CARD['bottom'], (0, CARD['top'].height + icon_height)) + foreground.paste(snake, (36, CARD["top"].height)) # Also hardcoded :( + foreground.paste(CARD["bottom"], (0, CARD["top"].height + icon_height)) # Setup the background - back = random.choice(CARD['backs']) + back = random.choice(CARD["backs"]) back_copies = main_height // back.height + 1 full_image = Image.new("RGBA", (main_width, main_height), (0, 0, 0, 0)) @@ -216,11 +216,11 @@ class Snakes(Cog): full_image.paste(foreground, (0, 0), foreground) # Get the first two sentences of the info - description = '.'.join(content['info'].split(".")[:2]) + '.' + description = ".".join(content["info"].split(".")[:2]) + "." # Setup positioning variables margin = 36 - offset = CARD['top'].height + icon_height + margin + offset = CARD["top"].height + icon_height + margin # Create blank rectangle image which will be behind the text rectangle = Image.new( @@ -242,12 +242,12 @@ class Snakes(Cog): # Draw the text onto the final image draw = ImageDraw.Draw(full_image) for line in textwrap.wrap(description, 36): - draw.text([margin + 4, offset], line, font=CARD['font']) - offset += CARD['font'].getsize(line)[1] + draw.text([margin + 4, offset], line, font=CARD["font"]) + offset += CARD["font"].getsize(line)[1] # Get the image contents as a BufferIO object buffer = BytesIO() - full_image.save(buffer, 'PNG') + full_image.save(buffer, "PNG") buffer.seek(0) return buffer @@ -311,12 +311,12 @@ class Snakes(Cog): async with aiohttp.ClientSession() as session: params = { - 'format': 'json', - 'action': 'query', - 'list': 'search', - 'srsearch': name, - 'utf8': '', - 'srlimit': '1', + "format": "json", + "action": "query", + "list": "search", + "srsearch": name, + "utf8": "", + "srlimit": "1", } json = await self._fetch(session, URL, params=params) @@ -331,13 +331,13 @@ class Snakes(Cog): return None params = { - 'format': 'json', - 'action': 'query', - 'prop': 'extracts|images|info', - 'exlimit': 'max', - 'explaintext': '', - 'inprop': 'url', - 'pageids': pageid + "format": "json", + "action": "query", + "prop": "extracts|images|info", + "exlimit": "max", + "explaintext": "", + "inprop": "url", + "pageids": pageid } json = await self._fetch(session, URL, params=params) @@ -353,32 +353,32 @@ class Snakes(Cog): snake_info["error"] = True if snake_info["images"]: - i_url = 'https://commons.wikimedia.org/wiki/Special:FilePath/' + i_url = "https://commons.wikimedia.org/wiki/Special:FilePath/" image_list = [] map_list = [] thumb_list = [] # Wikipedia has arbitrary images that are not snakes banned = [ - 'Commons-logo.svg', - 'Red%20Pencil%20Icon.png', - 'distribution', - 'The%20Death%20of%20Cleopatra%20arthur.jpg', - 'Head%20of%20holotype', - 'locator', - 'Woma.png', - '-map.', - '.svg', - 'ange.', - 'Adder%20(PSF).png' + "Commons-logo.svg", + "Red%20Pencil%20Icon.png", + "distribution", + "The%20Death%20of%20Cleopatra%20arthur.jpg", + "Head%20of%20holotype", + "locator", + "Woma.png", + "-map.", + ".svg", + "ange.", + "Adder%20(PSF).png" ] for image in snake_info["images"]: # Images come in the format of `File:filename.extension` - file, sep, filename = image["title"].partition(':') + file, sep, filename = image["title"].partition(":") filename = filename.replace(" ", "%20") # Wikipedia returns good data! - if not filename.startswith('Map'): + if not filename.startswith("Map"): if any(ban in filename for ban in banned): pass else: @@ -392,7 +392,7 @@ class Snakes(Cog): snake_info["thumb_list"] = thumb_list snake_info["name"] = name - match = self.wiki_brief.match(snake_info['extract']) + match = self.wiki_brief.match(snake_info["extract"]) info = match.group(1) if match else None if info: @@ -438,13 +438,13 @@ class Snakes(Cog): # endregion # region: Commands - @group(name='snakes', aliases=('snake',), invoke_without_command=True) + @group(name="snakes", aliases=("snake",), invoke_without_command=True) async def snakes_group(self, ctx: Context) -> None: """Commands from our first code jam.""" await invoke_help_command(ctx) @bot_has_permissions(manage_messages=True) - @snakes_group.command(name='antidote') + @snakes_group.command(name="antidote") @locked() async def antidote_command(self, ctx: Context) -> None: """ @@ -586,7 +586,7 @@ class Snakes(Cog): log.debug("Ending pagination and removing all reactions...") await board_id.clear_reactions() - @snakes_group.command(name='draw') + @snakes_group.command(name="draw") async def draw_command(self, ctx: Context) -> None: """ Draws a random snek using Perlin noise. @@ -621,10 +621,10 @@ class Snakes(Cog): bg_color=bg_color ) png_bytes = utils.frame_to_png_bytes(image_frame) - file = File(png_bytes, filename='snek.png') + file = File(png_bytes, filename="snek.png") await ctx.send(file=file) - @snakes_group.command(name='get') + @snakes_group.command(name="get") @bot_has_permissions(manage_messages=True) @locked() async def get_command(self, ctx: Context, *, name: Snake = None) -> None: @@ -642,8 +642,8 @@ class Snakes(Cog): else: data = await self._get_snek(name) - if data.get('error'): - await ctx.send('Could not fetch data from Wikipedia.') + if data.get("error"): + await ctx.send("Could not fetch data from Wikipedia.") return description = data["info"] @@ -662,19 +662,19 @@ class Snakes(Cog): # Build and send the embed. embed = Embed( - title=data.get("title", data.get('name')), + title=data.get("title", data.get("name")), description=description, colour=0x59982F, ) - emoji = 'https://emojipedia-us.s3.amazonaws.com/thumbs/60/google/3/snake_1f40d.png' - image = next((url for url in data['image_list'] + emoji = "https://emojipedia-us.s3.amazonaws.com/thumbs/60/google/3/snake_1f40d.png" + image = next((url for url in data["image_list"] if url.endswith(self.valid_image_extensions)), emoji) embed.set_image(url=image) await ctx.send(embed=embed) - @snakes_group.command(name='guess', aliases=('identify',)) + @snakes_group.command(name="guess", aliases=("identify",)) @locked() async def guess_command(self, ctx: Context) -> None: """ @@ -694,11 +694,11 @@ class Snakes(Cog): data = await self._get_snek(snake) - image = next((url for url in data['image_list'] + image = next((url for url in data["image_list"] if url.endswith(self.valid_image_extensions)), None) embed = Embed( - title='Which of the following is the snake in the image?', + title="Which of the following is the snake in the image?", description="\n".join( f"{'ABCD'[snakes.index(snake)]}: {snake}" for snake in snakes), colour=SNAKE_COLOR @@ -709,7 +709,7 @@ class Snakes(Cog): options = {f"{'abcd'[snakes.index(snake)]}": snake for snake in snakes} await self._validate_answer(ctx, guess, answer, options) - @snakes_group.command(name='hatch') + @snakes_group.command(name="hatch") async def hatch_command(self, ctx: Context) -> None: """ Hatches your personal snake. @@ -740,7 +740,7 @@ class Snakes(Cog): await ctx.send(embed=my_snake_embed) - @snakes_group.command(name='movie') + @snakes_group.command(name="movie") async def movie_command(self, ctx: Context) -> None: """ Gets a random snake-related movie from TMDB. @@ -806,7 +806,7 @@ class Snakes(Cog): await ctx.send("An error occurred while fetching a snake-related movie!") raise err from None - @snakes_group.command(name='quiz') + @snakes_group.command(name="quiz") @locked() async def quiz_command(self, ctx: Context) -> None: """ @@ -832,7 +832,7 @@ class Snakes(Cog): quiz = await ctx.send("", embed=embed) await self._validate_answer(ctx, quiz, answer, options) - @snakes_group.command(name='name', aliases=('name_gen',)) + @snakes_group.command(name="name", aliases=("name_gen",)) async def name_command(self, ctx: Context, *, name: str = None) -> None: """ Snakifies a username. @@ -856,7 +856,7 @@ class Snakes(Cog): This was written by Iceman, and modified for inclusion into the bot by lemon. """ snake_name = await self._get_snake_name() - snake_name = snake_name['name'] + snake_name = snake_name["name"] snake_prefix = "" # Set aside every word in the snake name except the last. @@ -904,7 +904,7 @@ class Snakes(Cog): await ctx.send(embed=embed) return - @snakes_group.command(name='sal') + @snakes_group.command(name="sal") @locked() async def sal_command(self, ctx: Context) -> None: """ @@ -923,7 +923,7 @@ class Snakes(Cog): await game.open_game() - @snakes_group.command(name='about') + @snakes_group.command(name="about") async def about_command(self, ctx: Context) -> None: """Show an embed with information about the event, its participants, and its winners.""" contributors = [ @@ -968,7 +968,7 @@ class Snakes(Cog): await ctx.send(embed=embed) - @snakes_group.command(name='card') + @snakes_group.command(name="card") async def card_command(self, ctx: Context, *, name: Snake = None) -> None: """ Create an interesting little card from a snake. @@ -978,7 +978,7 @@ class Snakes(Cog): # Get the snake data we need if not name: name_obj = await self._get_snake_name() - name = name_obj['scientific'] + name = name_obj["scientific"] content = await self._get_snek(name) elif isinstance(name, dict): @@ -992,7 +992,7 @@ class Snakes(Cog): stream = BytesIO() async with async_timeout.timeout(10): - async with self.bot.http_session.get(content['image_list'][0]) as response: + async with self.bot.http_session.get(content["image_list"][0]) as response: stream.write(await response.read()) stream.seek(0) @@ -1003,10 +1003,10 @@ class Snakes(Cog): # Send it! await ctx.send( f"A wild {content['name'].title()} appears!", - file=File(final_buffer, filename=content['name'].replace(" ", "") + ".png") + file=File(final_buffer, filename=content["name"].replace(" ", "") + ".png") ) - @snakes_group.command(name='fact') + @snakes_group.command(name="fact") async def fact_command(self, ctx: Context) -> None: """ Gets a snake-related fact. @@ -1022,7 +1022,7 @@ class Snakes(Cog): ) await ctx.send(embed=embed) - @snakes_group.command(name='snakify') + @snakes_group.command(name="snakify") async def snakify_command(self, ctx: Context, *, message: str = None) -> None: """ How would I talk if I were a snake? @@ -1063,7 +1063,7 @@ class Snakes(Cog): await ctx.send(embed=embed) - @snakes_group.command(name='video', aliases=('get_video',)) + @snakes_group.command(name="video", aliases=("get_video",)) async def video_command(self, ctx: Context, *, search: str = None) -> None: """ Gets a YouTube video about snakes. @@ -1074,13 +1074,13 @@ class Snakes(Cog): """ # Are we searching for anything specific? if search: - query = search + ' snake' + query = search + " snake" else: snake = await self._get_snake_name() - query = snake['name'] + query = snake["name"] # Build the URL and make the request - url = 'https://www.googleapis.com/youtube/v3/search' + url = "https://www.googleapis.com/youtube/v3/search" response = await self.bot.http_session.get( url, params={ @@ -1096,14 +1096,14 @@ class Snakes(Cog): # Send the user a video if len(data) > 0: num = random.randint(0, len(data) - 1) - youtube_base_url = 'https://www.youtube.com/watch?v=' + youtube_base_url = "https://www.youtube.com/watch?v=" await ctx.send( content=f"{youtube_base_url}{data[num]['id']['videoId']}" ) else: log.warning(f"YouTube API error. Full response looks like {response}") - @snakes_group.command(name='zen') + @snakes_group.command(name="zen") async def zen_command(self, ctx: Context) -> None: """ Gets a random quote from the Zen of Python, except as if spoken by a snake. diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index 7d6caf04..d58ee279 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -321,7 +321,7 @@ def create_snek_frame( image_dimensions[Y] / 2 - (dimension_range[Y] / 2 + min_dimensions[Y]) ) - image = Image.new(mode='RGB', size=image_dimensions, color=bg_color) + image = Image.new(mode="RGB", size=image_dimensions, color=bg_color) draw = ImageDraw(image) for index in range(1, len(points)): point = points[index] @@ -345,7 +345,7 @@ def create_snek_frame( def frame_to_png_bytes(image: Image) -> io.BytesIO: """Convert image to byte stream.""" stream = io.BytesIO() - image.save(stream, format='PNG') + image.save(stream, format="PNG") stream.seek(0) return stream @@ -373,7 +373,7 @@ class SnakeAndLaddersGame: self.snakes = snakes self.ctx = context self.channel = self.ctx.channel - self.state = 'booting' + self.state = "booting" self.started = False self.author = self.ctx.author self.players = [] @@ -413,7 +413,7 @@ class SnakeAndLaddersGame: "**Snakes and Ladders**: A new game is about to start!", file=File( str(SNAKE_RESOURCES / "snakes_and_ladders" / "banner.jpg"), - filename='Snakes and Ladders.jpg' + filename="Snakes and Ladders.jpg" ) ) startup = await self.channel.send( @@ -423,7 +423,7 @@ class SnakeAndLaddersGame: for emoji in STARTUP_SCREEN_EMOJI: await startup.add_reaction(emoji) - self.state = 'waiting' + self.state = "waiting" while not self.started: try: @@ -460,7 +460,7 @@ class SnakeAndLaddersGame: self.players.append(user) self.player_tiles[user.id] = 1 - avatar_bytes = await user.avatar_url_as(format='jpeg', size=PLAYER_ICON_IMAGE_SIZE).read() + avatar_bytes = await user.avatar_url_as(format="jpeg", size=PLAYER_ICON_IMAGE_SIZE).read() im = Image.open(io.BytesIO(avatar_bytes)).resize((BOARD_PLAYER_SIZE, BOARD_PLAYER_SIZE)) self.avatar_images[user.id] = im @@ -475,7 +475,7 @@ class SnakeAndLaddersGame: if user == p: await self.channel.send(user.mention + " You are already in the game.", delete_after=10) return - if self.state != 'waiting': + if self.state != "waiting": await self.channel.send(user.mention + " You cannot join at this time.", delete_after=10) return if len(self.players) is MAX_PLAYERS: @@ -510,7 +510,7 @@ class SnakeAndLaddersGame: delete_after=10 ) - if self.state != 'waiting' and len(self.players) == 0: + if self.state != "waiting" and len(self.players) == 0: await self.channel.send("**Snakes and Ladders**: The game has been surrendered!") is_surrendered = True self._destruct() @@ -535,12 +535,12 @@ class SnakeAndLaddersGame: await self.channel.send(user.mention + " Only the author of the game can start it.", delete_after=10) return - if not self.state == 'waiting': + if not self.state == "waiting": await self.channel.send(user.mention + " The game cannot be started at this time.", delete_after=10) return - self.state = 'starting' - player_list = ', '.join(user.mention for user in self.players) + self.state = "starting" + player_list = ", ".join(user.mention for user in self.players) await self.channel.send("**Snakes and Ladders**: The game is starting!\nPlayers: " + player_list) await self.start_round() @@ -556,7 +556,7 @@ class SnakeAndLaddersGame: )) ) - self.state = 'roll' + self.state = "roll" for user in self.players: self.round_has_rolled[user.id] = False board_img = Image.open(str(SNAKE_RESOURCES / "snakes_and_ladders" / "board.jpg")) @@ -574,8 +574,8 @@ class SnakeAndLaddersGame: board_img.paste(self.avatar_images[player.id], box=(x_offset, y_offset)) - board_file = File(frame_to_png_bytes(board_img), filename='Board.jpg') - player_list = '\n'.join((user.mention + ": Tile " + str(self.player_tiles[user.id])) for user in self.players) + board_file = File(frame_to_png_bytes(board_img), filename="Board.jpg") + player_list = "\n".join((user.mention + ": Tile " + str(self.player_tiles[user.id])) for user in self.players) # Store and send new messages temp_board = await self.channel.send( @@ -644,7 +644,7 @@ class SnakeAndLaddersGame: if user.id not in self.player_tiles: await self.channel.send(user.mention + " You are not in the match.", delete_after=10) return - if self.state != 'roll': + if self.state != "roll": await self.channel.send(user.mention + " You may not roll at this time.", delete_after=10) return if self.round_has_rolled[user.id]: @@ -673,7 +673,7 @@ class SnakeAndLaddersGame: async def _complete_round(self) -> None: """At the conclusion of a round check to see if there's been a winner.""" - self.state = 'post_round' + self.state = "post_round" # check for winner winner = self._check_winner() @@ -688,7 +688,7 @@ class SnakeAndLaddersGame: def _check_winner(self) -> Member: """Return a winning member if we're in the post-round state and there's a winner.""" - if self.state != 'post_round': + if self.state != "post_round": return None return next((player for player in self.players if self.player_tiles[player.id] == 100), None) diff --git a/bot/exts/evergreen/source.py b/bot/exts/evergreen/source.py index 14fd02f3..2f25e4cb 100644 --- a/bot/exts/evergreen/source.py +++ b/bot/exts/evergreen/source.py @@ -83,7 +83,7 @@ class BotSource(commands.Cog): url, location, first_line = self.get_source_link(source_object) if isinstance(source_object, commands.Command): - if source_object.cog_name == 'Help': + if source_object.cog_name == "Help": title = "Help Command" description = source_object.__doc__.splitlines()[1] else: diff --git a/bot/exts/evergreen/speedrun.py b/bot/exts/evergreen/speedrun.py index bf6f2117..110d5c13 100644 --- a/bot/exts/evergreen/speedrun.py +++ b/bot/exts/evergreen/speedrun.py @@ -8,7 +8,7 @@ from discord.ext import commands from bot.bot import Bot log = logging.getLogger(__name__) -with Path('bot/resources/evergreen/speedrun_links.json').open(encoding="utf8") as file: +with Path("bot/resources/evergreen/speedrun_links.json").open(encoding="utf8") as file: LINKS = json.load(file) diff --git a/bot/exts/evergreen/status_codes.py b/bot/exts/evergreen/status_codes.py index 635eef3d..a866692e 100644 --- a/bot/exts/evergreen/status_codes.py +++ b/bot/exts/evergreen/status_codes.py @@ -22,10 +22,10 @@ class HTTPStatusCodes(commands.Cog): if not ctx.invoked_subcommand: await invoke_help_command(ctx) - @http_status_group.command(name='cat') + @http_status_group.command(name="cat") async def http_cat(self, ctx: commands.Context, code: int) -> None: """Sends an embed with an image of a cat, portraying the status code.""" - embed = discord.Embed(title=f'**Status: {code}**') + embed = discord.Embed(title=f"**Status: {code}**") url = HTTP_CAT_URL.format(code=code) try: @@ -37,18 +37,18 @@ class HTTPStatusCodes(commands.Cog): raise NotImplementedError except ValueError: - embed.set_footer(text='Inputted status code does not exist.') + embed.set_footer(text="Inputted status code does not exist.") except NotImplementedError: - embed.set_footer(text='Inputted status code is not implemented by http.cat yet.') + embed.set_footer(text="Inputted status code is not implemented by http.cat yet.") finally: await ctx.send(embed=embed) - @http_status_group.command(name='dog') + @http_status_group.command(name="dog") async def http_dog(self, ctx: commands.Context, code: int) -> None: """Sends an embed with an image of a dog, portraying the status code.""" - embed = discord.Embed(title=f'**Status: {code}**') + embed = discord.Embed(title=f"**Status: {code}**") url = HTTP_DOG_URL.format(code=code) try: @@ -60,10 +60,10 @@ class HTTPStatusCodes(commands.Cog): raise NotImplementedError except ValueError: - embed.set_footer(text='Inputted status code does not exist.') + embed.set_footer(text="Inputted status code does not exist.") except NotImplementedError: - embed.set_footer(text='Inputted status code is not implemented by httpstatusdogs.com yet.') + embed.set_footer(text="Inputted status code is not implemented by httpstatusdogs.com yet.") finally: await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/tic_tac_toe.py b/bot/exts/evergreen/tic_tac_toe.py index 1fef427a..7b387c0a 100644 --- a/bot/exts/evergreen/tic_tac_toe.py +++ b/bot/exts/evergreen/tic_tac_toe.py @@ -58,7 +58,7 @@ class Player: ) try: - react, _ = await self.ctx.bot.wait_for('reaction_add', timeout=30.0, check=check_for_move) + react, _ = await self.ctx.bot.wait_for("reaction_add", timeout=30.0, check=check_for_move) except asyncio.TimeoutError: return True, None else: diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index bfd7d357..1953253b 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -129,7 +129,7 @@ class TriviaQuiz(commands.Cog): ) try: - msg = await self.bot.wait_for('message', check=check, timeout=10) + msg = await self.bot.wait_for("message", check=check, timeout=10) except asyncio.TimeoutError: # In case of TimeoutError and the game has been stopped, then do nothing. if self.game_status[ctx.channel.id] is False: diff --git a/bot/exts/evergreen/wikipedia.py b/bot/exts/evergreen/wikipedia.py index e2172fc3..fa21b916 100644 --- a/bot/exts/evergreen/wikipedia.py +++ b/bot/exts/evergreen/wikipedia.py @@ -20,7 +20,7 @@ WIKI_THUMBNAIL = ( "https://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg" "/330px-Wikipedia-logo-v2.svg.png" ) -WIKI_SNIPPET_REGEX = r'(|<[^>]*>)' +WIKI_SNIPPET_REGEX = r"(|<[^>]*>)" WIKI_SEARCH_RESULT = ( "**[{name}]({url})**\n" "{description}\n" @@ -39,18 +39,18 @@ class WikipediaSearch(commands.Cog): async with self.bot.http_session.get(url=url) as resp: if resp.status == 200: raw_data = await resp.json() - number_of_results = raw_data['query']['searchinfo']['totalhits'] + number_of_results = raw_data["query"]["searchinfo"]["totalhits"] if number_of_results: - results = raw_data['query']['search'] + results = raw_data["query"]["search"] lines = [] for article in results: line = WIKI_SEARCH_RESULT.format( - name=article['title'], + name=article["title"], description=unescape( re.sub( - WIKI_SNIPPET_REGEX, '', article['snippet'] + WIKI_SNIPPET_REGEX, "", article["snippet"] ) ), url=f"https://en.wikipedia.org/?curid={article['pageid']}" diff --git a/bot/exts/evergreen/wolfram.py b/bot/exts/evergreen/wolfram.py index c57a8d7a..3cc12c03 100644 --- a/bot/exts/evergreen/wolfram.py +++ b/bot/exts/evergreen/wolfram.py @@ -59,7 +59,7 @@ def custom_cooldown(*ignore: List[int]) -> Callable: A list of roles may be provided to ignore the per-user cooldown. """ async def predicate(ctx: Context) -> bool: - if ctx.invoked_with == 'help': + if ctx.invoked_with == "help": # if the invoked command is help we don't want to increase the ratelimits since it's not actually # invoking the command/making a request, so instead just check if the user/guild are on cooldown. guild_cooldown = not guildcd.get_bucket(ctx.message).get_tokens() == 0 # if guild is on cooldown @@ -118,7 +118,7 @@ async def get_pod_pages(ctx: Context, bot: Bot, query: str) -> Optional[List[Tup request_url = QUERY.format(request="query", data=url_str) async with bot.http_session.get(request_url) as response: - json = await response.json(content_type='text/plain') + json = await response.json(content_type="text/plain") result = json["queryresult"] diff --git a/bot/exts/evergreen/xkcd.py b/bot/exts/evergreen/xkcd.py index ba9e46e0..c98830bc 100644 --- a/bot/exts/evergreen/xkcd.py +++ b/bot/exts/evergreen/xkcd.py @@ -53,7 +53,7 @@ class XKCD(Cog): await ctx.send(embed=embed) return - comic = randint(1, self.latest_comic_info['num']) if comic is None else comic.group(0) + comic = randint(1, self.latest_comic_info["num"]) if comic is None else comic.group(0) if comic == "latest": info = self.latest_comic_info @@ -69,7 +69,7 @@ class XKCD(Cog): return embed.title = f"XKCD comic #{info['num']}" - embed.description = info['alt'] + embed.description = info["alt"] embed.url = f"{BASE_URL}/{info['num']}" if info["img"][-3:] in ("jpg", "png", "gif"): diff --git a/bot/exts/halloween/8ball.py b/bot/exts/halloween/8ball.py index 59d4acc5..d6c5a299 100644 --- a/bot/exts/halloween/8ball.py +++ b/bot/exts/halloween/8ball.py @@ -17,7 +17,7 @@ with Path("bot/resources/halloween/responses.json").open("r", encoding="utf8") a class SpookyEightBall(commands.Cog): """Spooky Eightball answers.""" - @commands.command(aliases=('spooky8ball',)) + @commands.command(aliases=("spooky8ball",)) async def spookyeightball(self, ctx: commands.Context, *, question: str) -> None: """Responds with a random response to a question.""" choice = random.choice(RESPONSES["responses"]) diff --git a/bot/exts/halloween/candy_collection.py b/bot/exts/halloween/candy_collection.py index 5441d8a5..14efa1fb 100644 --- a/bot/exts/halloween/candy_collection.py +++ b/bot/exts/halloween/candy_collection.py @@ -22,11 +22,11 @@ EMOJIS = dict( CANDY="\N{CANDY}", SKULL="\N{SKULL}", MEDALS=( - '\N{FIRST PLACE MEDAL}', - '\N{SECOND PLACE MEDAL}', - '\N{THIRD PLACE MEDAL}', - '\N{SPORTS MEDAL}', - '\N{SPORTS MEDAL}', + "\N{FIRST PLACE MEDAL}", + "\N{SECOND PLACE MEDAL}", + "\N{THIRD PLACE MEDAL}", + "\N{SPORTS MEDAL}", + "\N{SPORTS MEDAL}", ), ) @@ -106,7 +106,7 @@ class CandyCollection(commands.Cog): await self.candy_records.decrement(user.id, lost) if lost == prev_record: - await CandyCollection.send_spook_msg(user, message.channel, 'all of your') + await CandyCollection.send_spook_msg(user, message.channel, "all of your") else: await CandyCollection.send_spook_msg(user, message.channel, lost) else: @@ -125,7 +125,7 @@ class CandyCollection(commands.Cog): """ if random.randint(1, ADD_SKULL_EXISTING_REACTION_CHANCE) == 1: await self.skull_messages.set(message.id, "skull") - await message.add_reaction(EMOJIS['SKULL']) + await message.add_reaction(EMOJIS["SKULL"]) elif random.randint(1, ADD_CANDY_EXISTING_REACTION_CHANCE) == 1: await self.candy_messages.set(message.id, "candy") @@ -173,7 +173,7 @@ class CandyCollection(commands.Cog): ) top_five = top_sorted[:5] - return '\n'.join( + return "\n".join( f"{EMOJIS['MEDALS'][index]} <@{record[0]}>: {record[1]}" for index, record in enumerate(top_five) ) if top_five else "No Candies" @@ -185,7 +185,7 @@ class CandyCollection(commands.Cog): inline=False ) e.add_field( - name='\u200b', + name="\u200b", value="Candies will randomly appear on messages sent. " "\nHit the candy when it appears as fast as possible to get the candy! " "\nBut beware the ghosts...", diff --git a/bot/exts/halloween/hacktober-issue-finder.py b/bot/exts/halloween/hacktober-issue-finder.py index c88e2b6f..baee9612 100644 --- a/bot/exts/halloween/hacktober-issue-finder.py +++ b/bot/exts/halloween/hacktober-issue-finder.py @@ -102,7 +102,7 @@ class HacktoberIssues(commands.Cog): labels = [label["name"] for label in issue["labels"]] embed = discord.Embed(title=title) - embed.description = body[:500] + '...' if len(body) > 500 else body + embed.description = body[:500] + "..." if len(body) > 500 else body embed.add_field(name="labels", value="\n".join(labels)) embed.url = issue_url embed.set_footer(text=issue_url) diff --git a/bot/exts/halloween/hacktoberstats.py b/bot/exts/halloween/hacktoberstats.py index 9695ba2a..25da9ad5 100644 --- a/bot/exts/halloween/hacktoberstats.py +++ b/bot/exts/halloween/hacktoberstats.py @@ -138,7 +138,7 @@ class HacktoberStats(commands.Cog): if prs: stats_embed = await self.build_embed(github_username, prs) - await ctx.send('Here are some stats!', embed=stats_embed) + await ctx.send("Here are some stats!", embed=stats_embed) else: await ctx.send(f"No valid Hacktoberfest PRs found for '{github_username}'") @@ -355,7 +355,7 @@ class HacktoberStats(commands.Cog): # loop through reviews and check for approval for item in jsonresp2: - if item.get('status') == "APPROVED": + if item.get("status") == "APPROVED": return True return False @@ -387,9 +387,9 @@ class HacktoberStats(commands.Cog): in_review = [] accepted = [] for pr in prs: - if (pr['created_at'] + timedelta(REVIEW_DAYS)) > now: + if (pr["created_at"] + timedelta(REVIEW_DAYS)) > now: in_review.append(pr) - elif (pr['created_at'] <= oct3) or await self._is_accepted(pr): + elif (pr["created_at"] <= oct3) or await self._is_accepted(pr): accepted.append(pr) return in_review, accepted diff --git a/bot/exts/halloween/halloweenify.py b/bot/exts/halloween/halloweenify.py index 5a8f4ecc..47b20a2a 100644 --- a/bot/exts/halloween/halloweenify.py +++ b/bot/exts/halloween/halloweenify.py @@ -34,8 +34,8 @@ class Halloweenify(commands.Cog): embed.colour = discord.Colour.dark_orange() embed.title = "Not spooky enough?" embed.description = ( - f"**{ctx.author.display_name}** wasn\'t spooky enough for you? That\'s understandable, " - f"{ctx.author.display_name} isn\'t scary at all! " + f"**{ctx.author.display_name}** wasn't spooky enough for you? That's understandable, " + f"{ctx.author.display_name} isn't scary at all! " "Let me think of something better. Hmm... I got it!\n\n " ) embed.set_image(url=image) diff --git a/bot/exts/halloween/monsterbio.py b/bot/exts/halloween/monsterbio.py index f484305d..dbafa43f 100644 --- a/bot/exts/halloween/monsterbio.py +++ b/bot/exts/halloween/monsterbio.py @@ -37,7 +37,7 @@ class MonsterBio(commands.Cog): continue options = seeded_random.sample(TEXT_OPTIONS[key], value) - words[key] = ' '.join(options) + words[key] = " ".join(options) embed = discord.Embed( title=f"{name}'s Biography", diff --git a/bot/exts/halloween/monstersurvey.py b/bot/exts/halloween/monstersurvey.py index 0610503d..486e8937 100644 --- a/bot/exts/halloween/monstersurvey.py +++ b/bot/exts/halloween/monstersurvey.py @@ -9,8 +9,8 @@ from discord.ext.commands import Bot, Cog, Context log = logging.getLogger(__name__) EMOJIS = { - 'SUCCESS': u'\u2705', - 'ERROR': u'\u274C' + "SUCCESS": u"\u2705", + "ERROR": u"\u274C" } @@ -25,63 +25,63 @@ class MonsterSurvey(Cog): def __init__(self): """Initializes values for the bot to use within the voting commands.""" - self.registry_location = os.path.join(os.getcwd(), 'bot', 'resources', 'halloween', 'monstersurvey.json') - with open(self.registry_location, 'r', encoding="utf8") as jason: + self.registry_location = os.path.join(os.getcwd(), "bot", "resources", "halloween", "monstersurvey.json") + with open(self.registry_location, "r", encoding="utf8") as jason: self.voter_registry = json.load(jason) def json_write(self) -> None: """Write voting results to a local JSON file.""" log.info("Saved Monster Survey Results") - with open(self.registry_location, 'w', encoding="utf8") as jason: + with open(self.registry_location, "w", encoding="utf8") as jason: json.dump(self.voter_registry, jason, indent=2) def cast_vote(self, id: int, monster: str) -> None: """ - Cast a user's vote for the specified monster. + Cast a user"s vote for the specified monster. If the user has already voted, their existing vote is removed. """ vr = self.voter_registry for m in vr.keys(): - if id not in vr[m]['votes'] and m == monster: - vr[m]['votes'].append(id) + if id not in vr[m]["votes"] and m == monster: + vr[m]["votes"].append(id) else: - if id in vr[m]['votes'] and m != monster: - vr[m]['votes'].remove(id) + if id in vr[m]["votes"] and m != monster: + vr[m]["votes"].remove(id) def get_name_by_leaderboard_index(self, n: int) -> str: """Return the monster at the specified leaderboard index.""" n = n - 1 vr = self.voter_registry - top = sorted(vr, key=lambda k: len(vr[k]['votes']), reverse=True) + top = sorted(vr, key=lambda k: len(vr[k]["votes"]), reverse=True) name = top[n] if n >= 0 else None return name @commands.group( - name='monster', - aliases=('mon',) + name="monster", + aliases=("mon",) ) async def monster_group(self, ctx: Context) -> None: """The base voting command. If nothing is called, then it will return an embed.""" if ctx.invoked_subcommand is None: async with ctx.typing(): default_embed = Embed( - title='Monster Voting', + title="Monster Voting", color=0xFF6800, - description='Vote for your favorite monster!' + description="Vote for your favorite monster!" ) default_embed.add_field( - name='.monster show monster_name(optional)', - value='Show a specific monster. If none is listed, it will give you an error with valid choices.', + name=".monster show monster_name(optional)", + value="Show a specific monster. If none is listed, it will give you an error with valid choices.", inline=False) default_embed.add_field( - name='.monster vote monster_name', - value='Vote for a specific monster. You get one vote, but can change it at any time.', + name=".monster vote monster_name", + value="Vote for a specific monster. You get one vote, but can change it at any time.", inline=False ) default_embed.add_field( - name='.monster leaderboard', - value='Which monster has the most votes? This command will tell you.', + name=".monster leaderboard", + value="Which monster has the most votes? This command will tell you.", inline=False ) default_embed.set_footer(text=f"Monsters choices are: {', '.join(self.voter_registry.keys())}") @@ -89,7 +89,7 @@ class MonsterSurvey(Cog): await ctx.send(embed=default_embed) @monster_group.command( - name='vote' + name="vote" ) async def monster_vote(self, ctx: Context, name: str = None) -> None: """ @@ -110,37 +110,37 @@ class MonsterSurvey(Cog): name = name.lower() vote_embed = Embed( - name='Monster Voting', + name="Monster Voting", color=0xFF6800 ) m = self.voter_registry.get(name) if m is None: - vote_embed.description = f'You cannot vote for {name} because it\'s not in the running.' + vote_embed.description = f"You cannot vote for {name} because it's not in the running." vote_embed.add_field( - name='Use `.monster show {monster_name}` for more information on a specific monster', - value='or use `.monster vote {monster}` to cast your vote for said monster.', + name="Use `.monster show {monster_name}` for more information on a specific monster", + value="or use `.monster vote {monster}` to cast your vote for said monster.", inline=False ) vote_embed.add_field( - name='You may vote for or show the following monsters:', - value=f"{', '.join(self.voter_registry.keys())}" + name="You may vote for or show the following monsters:", + value=", ".join(self.voter_registry.keys()) ) else: self.cast_vote(ctx.author.id, name) vote_embed.add_field( - name='Vote successful!', - value=f'You have successfully voted for {m["full_name"]}!', + name="Vote successful!", + value=f"You have successfully voted for {m['full_name']}!", inline=False ) - vote_embed.set_thumbnail(url=m['image']) + vote_embed.set_thumbnail(url=m["image"]) vote_embed.set_footer(text="Please note that any previous votes have been removed.") self.json_write() await ctx.send(embed=vote_embed) @monster_group.command( - name='show' + name="show" ) async def monster_show(self, ctx: Context, name: str = None) -> None: """Shows the named monster. If one is not named, it sends the default voting embed instead.""" @@ -158,31 +158,31 @@ class MonsterSurvey(Cog): m = self.voter_registry.get(name) if not m: - await ctx.send('That monster does not exist.') + await ctx.send("That monster does not exist.") await ctx.invoke(self.monster_vote) return - embed = Embed(title=m['full_name'], color=0xFF6800) - embed.add_field(name='Summary', value=m['summary']) - embed.set_image(url=m['image']) - embed.set_footer(text=f'To vote for this monster, type .monster vote {name}') + embed = Embed(title=m["full_name"], color=0xFF6800) + embed.add_field(name="Summary", value=m["summary"]) + embed.set_image(url=m["image"]) + embed.set_footer(text=f"To vote for this monster, type .monster vote {name}") await ctx.send(embed=embed) @monster_group.command( - name='leaderboard', - aliases=('lb',) + name="leaderboard", + aliases=("lb",) ) async def monster_leaderboard(self, ctx: Context) -> None: """Shows the current standings.""" async with ctx.typing(): vr = self.voter_registry - top = sorted(vr, key=lambda k: len(vr[k]['votes']), reverse=True) - total_votes = sum(len(m['votes']) for m in self.voter_registry.values()) + top = sorted(vr, key=lambda k: len(vr[k]["votes"]), reverse=True) + total_votes = sum(len(m["votes"]) for m in self.voter_registry.values()) embed = Embed(title="Monster Survey Leader Board", color=0xFF6800) for rank, m in enumerate(top): - votes = len(vr[m]['votes']) + votes = len(vr[m]["votes"]) percentage = ((votes / total_votes) * 100) if total_votes > 0 else 0 embed.add_field(name=f"{rank+1}. {vr[m]['full_name']}", value=( diff --git a/bot/exts/halloween/scarymovie.py b/bot/exts/halloween/scarymovie.py index 48c9f53d..f4cf41db 100644 --- a/bot/exts/halloween/scarymovie.py +++ b/bot/exts/halloween/scarymovie.py @@ -47,7 +47,7 @@ class ScaryMovie(commands.Cog): total_pages = data.get("total_pages") # Get movie details from one random result on a random page - params['page'] = random.randint(1, total_pages) + params["page"] = random.randint(1, total_pages) async with self.bot.http_session.get(url=url, params=params, headers=headers) as response: data = await response.json() selection_id = random.choice(data.get("results")).get("id") @@ -71,26 +71,26 @@ class ScaryMovie(commands.Cog): # Get cast names cast = [] - for actor in movie.get('credits', {}).get('cast', [])[:3]: - cast.append(actor.get('name')) + for actor in movie.get("credits", {}).get("cast", [])[:3]: + cast.append(actor.get("name")) # Get director name - director = movie.get('credits', {}).get('crew', []) + director = movie.get("credits", {}).get("crew", []) if director: - director = director[0].get('name') + director = director[0].get("name") # Determine the spookiness rating - rating = '' - rating_count = movie.get('vote_average', 0) / 2 + rating = "" + rating_count = movie.get("vote_average", 0) / 2 for _ in range(int(rating_count)): - rating += ':skull:' + rating += ":skull:" if (rating_count % 1) >= .5: - rating += ':bat:' + rating += ":bat:" # Try to get year of release and runtime - year = movie.get('release_date', [])[:4] - runtime = movie.get('runtime') + year = movie.get("release_date", [])[:4] + runtime = movie.get("runtime") runtime = f"{runtime} minutes" if runtime else None # Not all these attributes will always be present diff --git a/bot/exts/halloween/spookygif.py b/bot/exts/halloween/spookygif.py index bfdf2128..ffb91b1b 100644 --- a/bot/exts/halloween/spookygif.py +++ b/bot/exts/halloween/spookygif.py @@ -19,11 +19,11 @@ class SpookyGif(commands.Cog): async def spookygif(self, ctx: commands.Context) -> None: """Fetches a random gif from the GIPHY API and responds with it.""" async with ctx.typing(): - params = {'api_key': Tokens.giphy, 'tag': 'halloween', 'rating': 'g'} + params = {"api_key": Tokens.giphy, "tag": "halloween", "rating": "g"} # Make a GET request to the Giphy API to get a random halloween gif. - async with self.bot.http_session.get('http://api.giphy.com/v1/gifs/random', params=params) as resp: + async with self.bot.http_session.get("http://api.giphy.com/v1/gifs/random", params=params) as resp: data = await resp.json() - url = data['data']['image_url'] + url = data["data"]["image_url"] embed = discord.Embed(colour=0x9b59b6) embed.title = "A spooooky gif!" diff --git a/bot/exts/halloween/spookynamerate.py b/bot/exts/halloween/spookynamerate.py index 9191f5f6..87172922 100644 --- a/bot/exts/halloween/spookynamerate.py +++ b/bot/exts/halloween/spookynamerate.py @@ -81,7 +81,7 @@ class SpookyNameRate(Cog): # The data cache stores small information such as the current name that is going on and whether it is the first time # the bot is running data = RedisCache() - debug = getenv('SPOOKYNAMERATE_DEBUG', False) # Enable if you do not want to limit the commands to October or if + debug = getenv("SPOOKYNAMERATE_DEBUG", False) # Enable if you do not want to limit the commands to October or if # you do not want to wait till 12 UTC. Note: if debug is enabled and you run `.cogs reload spookynamerate`, it # will automatically start the scoring and announcing the result (without waiting for 12, so do not expect it to.). # Also, it won't wait for the two hours (when the poll closes). diff --git a/bot/exts/halloween/spookyrating.py b/bot/exts/halloween/spookyrating.py index dc398e2e..6c79fbed 100644 --- a/bot/exts/halloween/spookyrating.py +++ b/bot/exts/halloween/spookyrating.py @@ -46,16 +46,16 @@ class SpookyRating(commands.Cog): _, data = SPOOKY_DATA[index] embed = discord.Embed( - title=data['title'], - description=f'{who} scored {spooky_percent}%!', + title=data["title"], + description=f"{who} scored {spooky_percent}%!", color=Colours.orange ) embed.add_field( - name='A whisper from Satan', - value=data['text'] + name="A whisper from Satan", + value=data["text"] ) embed.set_thumbnail( - url=data['image'] + url=data["image"] ) await ctx.send(embed=embed) diff --git a/bot/exts/halloween/spookyreact.py b/bot/exts/halloween/spookyreact.py index dabc3c1f..25e783f4 100644 --- a/bot/exts/halloween/spookyreact.py +++ b/bot/exts/halloween/spookyreact.py @@ -11,13 +11,13 @@ from bot.utils.decorators import in_month log = logging.getLogger(__name__) SPOOKY_TRIGGERS = { - 'spooky': (r"\bspo{2,}ky\b", "\U0001F47B"), - 'skeleton': (r"\bskeleton\b", "\U0001F480"), - 'doot': (r"\bdo{2,}t\b", "\U0001F480"), - 'pumpkin': (r"\bpumpkin\b", "\U0001F383"), - 'halloween': (r"\bhalloween\b", "\U0001F383"), - 'jack-o-lantern': (r"\bjack-o-lantern\b", "\U0001F383"), - 'danger': (r"\bdanger\b", "\U00002620") + "spooky": (r"\bspo{2,}ky\b", "\U0001F47B"), + "skeleton": (r"\bskeleton\b", "\U0001F480"), + "doot": (r"\bdo{2,}t\b", "\U0001F480"), + "pumpkin": (r"\bpumpkin\b", "\U0001F383"), + "halloween": (r"\bhalloween\b", "\U0001F383"), + "jack-o-lantern": (r"\bjack-o-lantern\b", "\U0001F383"), + "danger": (r"\bdanger\b", "\U00002620") } diff --git a/bot/exts/internal_eval/_internal_eval.py b/bot/exts/internal_eval/_internal_eval.py index 757a2a1e..4fe3bc09 100644 --- a/bot/exts/internal_eval/_internal_eval.py +++ b/bot/exts/internal_eval/_internal_eval.py @@ -142,14 +142,14 @@ class InternalEval(commands.Cog): log.trace("Sending the formatted output back to the context") await self._send_output(ctx, eval_context.format_output()) - @commands.group(name='internal', aliases=('int',)) + @commands.group(name="internal", aliases=("int",)) @with_role(Roles.admin) async def internal_group(self, ctx: commands.Context) -> None: """Internal commands. Top secret!""" if not ctx.invoked_subcommand: await invoke_help_command(ctx) - @internal_group.command(name='eval', aliases=('e',)) + @internal_group.command(name="eval", aliases=("e",)) @with_role(Roles.admin) async def eval(self, ctx: commands.Context, *, code: str) -> None: """Run eval in a REPL-like format.""" @@ -157,7 +157,7 @@ class InternalEval(commands.Cog): blocks = [block for block in match if block.group("block")] if len(blocks) > 1: - code = '\n'.join(block.group("code") for block in blocks) + code = "\n".join(block.group("code") for block in blocks) else: match = match[0] if len(blocks) == 0 else blocks[0] code, block, lang, delim = match.group("code", "block", "lang", "delim") @@ -168,7 +168,7 @@ class InternalEval(commands.Cog): code = textwrap.dedent(code) await self._eval(ctx, code) - @internal_group.command(name='reset', aliases=("clear", "exit", "r", "c")) + @internal_group.command(name="reset", aliases=("clear", "exit", "r", "c")) @with_role(Roles.admin) async def reset(self, ctx: commands.Context) -> None: """Reset the context and locals of the eval session.""" diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index 051f09b8..e94efda0 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -70,7 +70,7 @@ class BeMyValentine(commands.Cog): await ctx.send("The lovefest role has been successfully removed!") @commands.cooldown(1, 1800, BucketType.user) - @commands.group(name='bemyvalentine', invoke_without_command=True) + @commands.group(name="bemyvalentine", invoke_without_command=True) async def send_valentine( self, ctx: commands.Context, user: discord.Member, *, valentine_type: str = None ) -> None: @@ -102,14 +102,14 @@ class BeMyValentine(commands.Cog): valentine, title = self.valentine_check(valentine_type) embed = discord.Embed( - title=f'{emoji_1} {title} {user.display_name} {emoji_2}', - description=f'{valentine} \n **{emoji_2}From {ctx.author}{emoji_1}**', + title=f"{emoji_1} {title} {user.display_name} {emoji_2}", + description=f"{valentine} \n **{emoji_2}From {ctx.author}{emoji_1}**", color=Colours.pink ) await channel.send(user.mention, embed=embed) @commands.cooldown(1, 1800, BucketType.user) - @send_valentine.command(name='secret') + @send_valentine.command(name="secret") async def anonymous( self, ctx: commands.Context, user: discord.Member, *, valentine_type: str = None ) -> None: @@ -137,8 +137,8 @@ class BeMyValentine(commands.Cog): valentine, title = self.valentine_check(valentine_type) embed = discord.Embed( - title=f'{emoji_1}{title} {user.display_name}{emoji_2}', - description=f'{valentine} \n **{emoji_2}From anonymous{emoji_1}**', + title=f"{emoji_1}{title} {user.display_name}{emoji_2}", + description=f"{valentine} \n **{emoji_2}From anonymous{emoji_1}**", color=Colours.pink ) await ctx.message.delete() @@ -154,18 +154,18 @@ class BeMyValentine(commands.Cog): if valentine_type is None: valentine, title = self.random_valentine() - elif valentine_type.lower() in ['p', 'poem']: + elif valentine_type.lower() in ["p", "poem"]: valentine = self.valentine_poem() - title = 'A poem dedicated to' + title = "A poem dedicated to" - elif valentine_type.lower() in ['c', 'compliment']: + elif valentine_type.lower() in ["c", "compliment"]: valentine = self.valentine_compliment() - title = 'A compliment for' + title = "A compliment for" else: # in this case, the user decides to type his own valentine. valentine = valentine_type - title = 'A message for' + title = "A message for" return valentine, title @staticmethod @@ -177,23 +177,23 @@ class BeMyValentine(commands.Cog): def random_valentine(self) -> Tuple[str, str]: """Grabs a random poem or a compliment (any message).""" - valentine_poem = random.choice(self.valentines['valentine_poems']) - valentine_compliment = random.choice(self.valentines['valentine_compliments']) + valentine_poem = random.choice(self.valentines["valentine_poems"]) + valentine_compliment = random.choice(self.valentines["valentine_compliments"]) random_valentine = random.choice([valentine_compliment, valentine_poem]) if random_valentine == valentine_poem: - title = 'A poem dedicated to' + title = "A poem dedicated to" else: - title = 'A compliment for ' + title = "A compliment for " return random_valentine, title def valentine_poem(self) -> str: """Grabs a random poem.""" - valentine_poem = random.choice(self.valentines['valentine_poems']) + valentine_poem = random.choice(self.valentines["valentine_poems"]) return valentine_poem def valentine_compliment(self) -> str: """Grabs a random compliment.""" - valentine_compliment = random.choice(self.valentines['valentine_compliments']) + valentine_compliment = random.choice(self.valentines["valentine_compliments"]) return valentine_compliment diff --git a/bot/exts/valentines/myvalenstate.py b/bot/exts/valentines/myvalenstate.py index 19e6b57f..7a0f8318 100644 --- a/bot/exts/valentines/myvalenstate.py +++ b/bot/exts/valentines/myvalenstate.py @@ -47,12 +47,12 @@ class MyValenstate(commands.Cog): """Find the vacation spot(s) with the most matching characters to the invoking user.""" eq_chars = collections.defaultdict(int) if name is None: - author = ctx.author.name.lower().replace(' ', '') + author = ctx.author.name.lower().replace(" ", "") else: - author = name.lower().replace(' ', '') + author = name.lower().replace(" ", "") for state in STATES.keys(): - lower_state = state.lower().replace(' ', '') + lower_state = state.lower().replace(" ", "") eq_chars[state] = self.levenshtein(author, lower_state) matches = [x for x, y in eq_chars.items() if y == min(eq_chars.values())] @@ -73,8 +73,8 @@ class MyValenstate(commands.Cog): " you better" embed = discord.Embed( - title=f'Your Valenstate is {valenstate} \u2764', - description=f'{STATES[valenstate]["text"]}', + title=f"Your Valenstate is {valenstate} \u2764", + description=f"{STATES[valenstate]['text']}", colour=Colours.pink ) embed.add_field(name=embed_title, value=embed_text) diff --git a/bot/exts/valentines/pickuplines.py b/bot/exts/valentines/pickuplines.py index bb322016..216ee13b 100644 --- a/bot/exts/valentines/pickuplines.py +++ b/bot/exts/valentines/pickuplines.py @@ -25,14 +25,14 @@ class PickupLine(commands.Cog): Note that most of them are very cheesy. """ - random_line = random.choice(pickup_lines['lines']) + random_line = random.choice(pickup_lines["lines"]) embed = discord.Embed( - title=':cheese: Your pickup line :cheese:', - description=random_line['line'], + title=":cheese: Your pickup line :cheese:", + description=random_line["line"], color=Colours.pink ) embed.set_thumbnail( - url=random_line.get('image', pickup_lines['placeholder']) + url=random_line.get("image", pickup_lines["placeholder"]) ) await ctx.send(embed=embed) diff --git a/bot/exts/valentines/savethedate.py b/bot/exts/valentines/savethedate.py index bda5d8c6..ed2d2c5f 100644 --- a/bot/exts/valentines/savethedate.py +++ b/bot/exts/valentines/savethedate.py @@ -23,7 +23,7 @@ class SaveTheDate(commands.Cog): @commands.command() async def savethedate(self, ctx: commands.Context) -> None: """Gives you ideas for what to do on a date with your valentine.""" - random_date = random.choice(VALENTINES_DATES['ideas']) + random_date = random.choice(VALENTINES_DATES["ideas"]) emoji_1 = random.choice(HEART_EMOJIS) emoji_2 = random.choice(HEART_EMOJIS) embed = discord.Embed( diff --git a/bot/exts/valentines/valentine_zodiac.py b/bot/exts/valentines/valentine_zodiac.py index 237fe5db..72fd93fe 100644 --- a/bot/exts/valentines/valentine_zodiac.py +++ b/bot/exts/valentines/valentine_zodiac.py @@ -14,7 +14,7 @@ from bot.constants import Colours log = logging.getLogger(__name__) -LETTER_EMOJI = ':love_letter:' +LETTER_EMOJI = ":love_letter:" HEART_EMOJIS = [":heart:", ":gift_heart:", ":revolving_hearts:", ":sparkling_heart:", ":two_hearts:"] @@ -32,8 +32,8 @@ class ValentineZodiac(commands.Cog): with explanation_file.open(encoding="utf8") as json_data: zodiac_fact = json.load(json_data) for zodiac_data in zodiac_fact.values(): - zodiac_data['start_at'] = datetime.fromisoformat(zodiac_data['start_at']) - zodiac_data['end_at'] = datetime.fromisoformat(zodiac_data['end_at']) + zodiac_data["start_at"] = datetime.fromisoformat(zodiac_data["start_at"]) + zodiac_data["end_at"] = datetime.fromisoformat(zodiac_data["end_at"]) with compatibility_file.open(encoding="utf8") as json_data: zodiacs = json.load(json_data) @@ -62,10 +62,10 @@ class ValentineZodiac(commands.Cog): log.trace("Making zodiac embed.") embed.title = f"__{zodiac}__" embed.description = self.zodiac_fact[zodiac]["About"] - embed.add_field(name='__Motto__', value=self.zodiac_fact[zodiac]["Motto"], inline=False) - embed.add_field(name='__Strengths__', value=self.zodiac_fact[zodiac]["Strengths"], inline=False) - embed.add_field(name='__Weaknesses__', value=self.zodiac_fact[zodiac]["Weaknesses"], inline=False) - embed.add_field(name='__Full form__', value=self.zodiac_fact[zodiac]["full_form"], inline=False) + embed.add_field(name="__Motto__", value=self.zodiac_fact[zodiac]["Motto"], inline=False) + embed.add_field(name="__Strengths__", value=self.zodiac_fact[zodiac]["Strengths"], inline=False) + embed.add_field(name="__Weaknesses__", value=self.zodiac_fact[zodiac]["Weaknesses"], inline=False) + embed.add_field(name="__Full form__", value=self.zodiac_fact[zodiac]["full_form"], inline=False) embed.set_thumbnail(url=self.zodiac_fact[zodiac]["url"]) else: embed = self.generate_invalidname_embed(zodiac) @@ -79,7 +79,7 @@ class ValentineZodiac(commands.Cog): log.trace("Zodiac name sent.") return zodiac_name - @commands.group(name='zodiac', invoke_without_command=True) + @commands.group(name="zodiac", invoke_without_command=True) async def zodiac(self, ctx: commands.Context, zodiac_sign: str) -> None: """Provides information about zodiac sign by taking zodiac sign name as input.""" final_embed = self.zodiac_build_embed(zodiac_sign) @@ -93,9 +93,9 @@ class ValentineZodiac(commands.Cog): month = month.capitalize() try: month = list(calendar.month_abbr).index(month[:3]) - log.trace('Valid month name entered by user') + log.trace("Valid month name entered by user") except ValueError: - log.info('Invalid month name entered by user') + log.info("Invalid month name entered by user") await ctx.send(f"Sorry, but `{month}` is not a valid month name.") return if (month == 1 and 1 <= date <= 19) or (month == 12 and 22 <= date <= 31): @@ -109,14 +109,14 @@ class ValentineZodiac(commands.Cog): final_embed = discord.Embed() final_embed.color = Colours.soft_red final_embed.description = f"Zodiac sign could not be found because.\n```{e}```" - log.info(f'Error in "zodiac date" command:\n{e}.') + log.info(f"Error in 'zodiac date' command:\n{e}.") else: final_embed = self.zodiac_build_embed(zodiac_sign_based_on_date) await ctx.send(embed=final_embed) log.trace("Embed from date successfully sent.") - @zodiac.command(name="partnerzodiac", aliases=['partner']) + @zodiac.command(name="partnerzodiac", aliases=["partner"]) async def partner_zodiac(self, ctx: commands.Context, zodiac_sign: str) -> None: """Provides a random counter compatible zodiac sign to the given user's zodiac sign.""" embed = discord.Embed() @@ -128,12 +128,12 @@ class ValentineZodiac(commands.Cog): emoji2 = random.choice(HEART_EMOJIS) embed.title = "Zodiac Compatibility" embed.description = ( - f'{zodiac_sign.capitalize()}{emoji1}{compatible_zodiac["Zodiac"]}\n' - f'{emoji2}Compatibility meter : {compatible_zodiac["compatibility_score"]}{emoji2}' + f"{zodiac_sign.capitalize()}{emoji1}{compatible_zodiac['Zodiac']}\n" + f"{emoji2}Compatibility meter : {compatible_zodiac['compatibility_score']}{emoji2}" ) embed.add_field( - name=f'A letter from Dr.Zodiac {LETTER_EMOJI}', - value=compatible_zodiac['description'] + name=f"A letter from Dr.Zodiac {LETTER_EMOJI}", + value=compatible_zodiac["description"] ) else: embed = self.generate_invalidname_embed(zodiac_sign) diff --git a/bot/exts/valentines/whoisvalentine.py b/bot/exts/valentines/whoisvalentine.py index 73cdcf52..3789fad5 100644 --- a/bot/exts/valentines/whoisvalentine.py +++ b/bot/exts/valentines/whoisvalentine.py @@ -18,17 +18,17 @@ with open(Path("bot/resources/valentines/valentine_facts.json"), "r", encoding=" class ValentineFacts(commands.Cog): """A Cog for displaying facts about Saint Valentine.""" - @commands.command(aliases=('whoisvalentine', 'saint_valentine')) + @commands.command(aliases=("whoisvalentine", "saint_valentine")) async def who_is_valentine(self, ctx: commands.Context) -> None: """Displays info about Saint Valentine.""" embed = discord.Embed( title="Who is Saint Valentine?", - description=FACTS['whois'], + description=FACTS["whois"], color=Colours.pink ) embed.set_thumbnail( - url='https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Saint_Valentine_-_' - 'facial_reconstruction.jpg/1024px-Saint_Valentine_-_facial_reconstruction.jpg' + url="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Saint_Valentine_-_" + "facial_reconstruction.jpg/1024px-Saint_Valentine_-_facial_reconstruction.jpg" ) await ctx.send(embed=embed) @@ -37,8 +37,8 @@ class ValentineFacts(commands.Cog): async def valentine_fact(self, ctx: commands.Context) -> None: """Shows a random fact about Valentine's Day.""" embed = discord.Embed( - title=choice(FACTS['titles']), - description=choice(FACTS['text']), + title=choice(FACTS["titles"]), + description=choice(FACTS["text"]), color=Colours.pink ) diff --git a/bot/utils/__init__.py b/bot/utils/__init__.py index 35ef0a7b..2fac2086 100644 --- a/bot/utils/__init__.py +++ b/bot/utils/__init__.py @@ -43,12 +43,12 @@ async def disambiguate( or if the user makes an invalid choice. """ if len(entries) == 0: - raise BadArgument('No matches found.') + raise BadArgument("No matches found.") if len(entries) == 1: return entries[0] - choices = (f'{index}: {entry}' for index, entry in enumerate(entries, start=1)) + choices = (f"{index}: {entry}" for index, entry in enumerate(entries, start=1)) def check(message: discord.Message) -> bool: return (message.content.isdigit() @@ -59,7 +59,7 @@ async def disambiguate( if embed is None: embed = discord.Embed() - coro1 = ctx.bot.wait_for('message', check=check, timeout=timeout) + coro1 = ctx.bot.wait_for("message", check=check, timeout=timeout) coro2 = LinePaginator.paginate(choices, ctx, embed=embed, max_lines=entries_per_page, empty=empty, max_size=6000, timeout=9000) @@ -74,7 +74,7 @@ async def disambiguate( if result is None: for coro in pending: coro.cancel() - raise BadArgument('Canceled.') + raise BadArgument("Canceled.") # Pagination was not initiated, only one page if result.author == ctx.bot.user: @@ -85,7 +85,7 @@ async def disambiguate( for coro in pending: coro.cancel() except asyncio.TimeoutError: - raise BadArgument('Timed out.') + raise BadArgument("Timed out.") # Guaranteed to not error because of isdigit() in check index = int(result.content) @@ -93,7 +93,7 @@ async def disambiguate( try: return entries[index - 1] except IndexError: - raise BadArgument('Invalid choice.') + raise BadArgument("Invalid choice.") def replace_many( @@ -139,7 +139,7 @@ def replace_many( return replacement # Clean punctuation from word so string methods work - cleaned_word = word.translate(str.maketrans('', '', string.punctuation)) + cleaned_word = word.translate(str.maketrans("", "", string.punctuation)) if cleaned_word.isupper(): return replacement.upper() elif cleaned_word[0].isupper(): diff --git a/bot/utils/checks.py b/bot/utils/checks.py index 9dd4dde0..3783dd38 100644 --- a/bot/utils/checks.py +++ b/bot/utils/checks.py @@ -154,8 +154,8 @@ def cooldown_with_role_bypass(rate: int, per: float, type: BucketType = BucketTy # # If the `before_invoke` detail is ever a problem then I can quickly just swap over. if not isinstance(command, Command): - raise TypeError('Decorator `cooldown_with_role_bypass` must be applied after the command decorator. ' - 'This means it has to be above the command decorator in the code.') + raise TypeError("Decorator `cooldown_with_role_bypass` must be applied after the command decorator. " + "This means it has to be above the command decorator in the code.") command._before_invoke = predicate diff --git a/bot/utils/decorators.py b/bot/utils/decorators.py index 60066dc4..c0783144 100644 --- a/bot/utils/decorators.py +++ b/bot/utils/decorators.py @@ -269,7 +269,7 @@ def whitelist_check(**default_kwargs: t.Container[int]) -> t.Callable[[Context], channels.update(channel.id for channel in category.text_channels) if channels: - channels_str = ', '.join(f"<#{c_id}>" for c_id in channels) + channels_str = ", ".join(f"<#{c_id}>" for c_id in channels) message = f"Sorry, but you may only use this command within {channels_str}." else: message = "Sorry, but you may not use this command." diff --git a/bot/utils/extensions.py b/bot/utils/extensions.py index 459588a1..cd491c4b 100644 --- a/bot/utils/extensions.py +++ b/bot/utils/extensions.py @@ -35,8 +35,8 @@ def walk_extensions() -> Iterator[str]: async def invoke_help_command(ctx: Context) -> None: """Invoke the help command or default help command if help extensions is not loaded.""" - if 'bot.exts.evergreen.help' in ctx.bot.extensions: - help_command = ctx.bot.get_command('help') + if "bot.exts.evergreen.help" in ctx.bot.extensions: + help_command = ctx.bot.get_command("help") await ctx.invoke(help_command, ctx.command.qualified_name) return await ctx.send_help(ctx.command) diff --git a/bot/utils/halloween/spookifications.py b/bot/utils/halloween/spookifications.py index 11f69850..f69dd6fd 100644 --- a/bot/utils/halloween/spookifications.py +++ b/bot/utils/halloween/spookifications.py @@ -13,16 +13,16 @@ def inversion(im: Image) -> Image: Returns an inverted image when supplied with an Image object. """ - im = im.convert('RGB') + im = im.convert("RGB") inv = ImageOps.invert(im) return inv def pentagram(im: Image) -> Image: """Adds pentagram to the image.""" - im = im.convert('RGB') + im = im.convert("RGB") wt, ht = im.size - penta = Image.open('bot/resources/halloween/bloody-pentagram.png') + penta = Image.open("bot/resources/halloween/bloody-pentagram.png") penta = penta.resize((wt, ht)) im.paste(penta, (0, 0), penta) return im @@ -35,9 +35,9 @@ def bat(im: Image) -> Image: The bat silhoutte is of a size at least one-fifths that of the original image and may be rotated up to 90 degrees anti-clockwise. """ - im = im.convert('RGB') + im = im.convert("RGB") wt, ht = im.size - bat = Image.open('bot/resources/halloween/bat-clipart.png') + bat = Image.open("bot/resources/halloween/bat-clipart.png") bat_size = randint(wt//10, wt//7) rot = randint(0, 90) bat = bat.resize((bat_size, bat_size)) diff --git a/bot/utils/pagination.py b/bot/utils/pagination.py index a97dd023..a073a00b 100644 --- a/bot/utils/pagination.py +++ b/bot/utils/pagination.py @@ -26,7 +26,7 @@ class EmptyPaginatorEmbed(Exception): class LinePaginator(Paginator): """A class that aids in paginating code blocks for Discord messages.""" - def __init__(self, prefix: str = '```', suffix: str = '```', max_size: int = 2000, max_lines: int = None): + def __init__(self, prefix: str = "```", suffix: str = "```", max_size: int = 2000, max_lines: int = None): """ Overrides the Paginator.__init__ from inside discord.ext.commands. @@ -44,7 +44,7 @@ class LinePaginator(Paginator): self._count = len(prefix) + 1 # prefix + newline self._pages = [] - def add_line(self, line: str = '', *, empty: bool = False) -> None: + def add_line(self, line: str = "", *, empty: bool = False) -> None: """ Adds a line to the current page. @@ -56,7 +56,7 @@ class LinePaginator(Paginator): If `empty` is True, an empty line will be placed after the a given `line`. """ if len(line) > self.max_size - len(self.prefix) - 2: - raise RuntimeError('Line exceeds maximum page size %s' % (self.max_size - len(self.prefix) - 2)) + raise RuntimeError("Line exceeds maximum page size %s" % (self.max_size - len(self.prefix) - 2)) if self.max_lines is not None: if self._linecount >= self.max_lines: @@ -71,7 +71,7 @@ class LinePaginator(Paginator): self._current_page.append(line) if empty: - self._current_page.append('') + self._current_page.append("") self._count += 1 @classmethod -- cgit v1.2.3 From c051abf49ce5bb82d127c8ddfad7ece431bb028f Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Tue, 4 May 2021 13:15:55 -0400 Subject: chore: Apply suggested changes --- bot/exts/evergreen/magic_8ball.py | 6 +++--- bot/exts/evergreen/minesweeper.py | 4 ++-- bot/exts/evergreen/tic_tac_toe.py | 4 ++-- bot/exts/evergreen/wonder_twins.py | 4 ++-- bot/exts/halloween/hacktoberstats.py | 6 +++--- 5 files changed, 12 insertions(+), 12 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/magic_8ball.py b/bot/exts/evergreen/magic_8ball.py index 708aa6d2..7c9b929d 100644 --- a/bot/exts/evergreen/magic_8ball.py +++ b/bot/exts/evergreen/magic_8ball.py @@ -13,7 +13,7 @@ log = logging.getLogger(__name__) class Magic8ball(commands.Cog): """A Magic 8ball command to respond to a user's question.""" - def __init__(self, _bot: Bot): + def __init__(self): with open(Path("bot/resources/evergreen/magic8ball.json"), "r", encoding="utf8") as file: self.answers = json.load(file) @@ -28,5 +28,5 @@ class Magic8ball(commands.Cog): def setup(bot: Bot) -> None: - """Load the Magic8Ball cog.""" - bot.add_cog(Magic8ball(bot)) + """Load the Magic8Ball Cog.""" + bot.add_cog(Magic8ball()) diff --git a/bot/exts/evergreen/minesweeper.py b/bot/exts/evergreen/minesweeper.py index f2c5e656..bd28d365 100644 --- a/bot/exts/evergreen/minesweeper.py +++ b/bot/exts/evergreen/minesweeper.py @@ -79,7 +79,7 @@ GamesDict = typing.Dict[int, Game] class Minesweeper(commands.Cog): """Play a game of Minesweeper.""" - def __init__(self, _bot: Bot) -> None: + def __init__(self) -> None: self.games: GamesDict = {} # Store the currently running games @commands.group(name="minesweeper", aliases=("ms",), invoke_without_command=True) @@ -295,4 +295,4 @@ class Minesweeper(commands.Cog): def setup(bot: Bot) -> None: """Load the Minesweeper cog.""" - bot.add_cog(Minesweeper(bot)) + bot.add_cog(Minesweeper()) diff --git a/bot/exts/evergreen/tic_tac_toe.py b/bot/exts/evergreen/tic_tac_toe.py index 7b387c0a..bd5e0102 100644 --- a/bot/exts/evergreen/tic_tac_toe.py +++ b/bot/exts/evergreen/tic_tac_toe.py @@ -246,7 +246,7 @@ def is_requester_free() -> t.Callable: class TicTacToe(Cog): """TicTacToe cog contains tic-tac-toe game commands.""" - def __init__(self, _bot: Bot): + def __init__(self): self.games: t.List[Game] = [] @guild_only() @@ -323,4 +323,4 @@ class TicTacToe(Cog): def setup(bot: Bot) -> None: """Load the TicTacToe cog.""" - bot.add_cog(TicTacToe(bot)) + bot.add_cog(TicTacToe()) diff --git a/bot/exts/evergreen/wonder_twins.py b/bot/exts/evergreen/wonder_twins.py index 9fa2d7f8..437d69f1 100644 --- a/bot/exts/evergreen/wonder_twins.py +++ b/bot/exts/evergreen/wonder_twins.py @@ -10,7 +10,7 @@ from bot.bot import Bot class WonderTwins(Cog): """Cog for a Wonder Twins inspired command.""" - def __init__(self, _bot: Bot): + def __init__(self): with open(Path.cwd() / "bot" / "resources" / "evergreen" / "wonder_twins.yaml", "r", encoding="utf-8") as f: info = yaml.load(f, Loader=yaml.FullLoader) self.water_types = info["water_types"] @@ -46,4 +46,4 @@ class WonderTwins(Cog): def setup(bot: Bot) -> None: """Load the WonderTwins cog.""" - bot.add_cog(WonderTwins(bot)) + bot.add_cog(WonderTwins()) diff --git a/bot/exts/halloween/hacktoberstats.py b/bot/exts/halloween/hacktoberstats.py index 25da9ad5..33e9ca31 100644 --- a/bot/exts/halloween/hacktoberstats.py +++ b/bot/exts/halloween/hacktoberstats.py @@ -10,7 +10,7 @@ from async_rediscache import RedisCache from discord.ext import commands from bot.bot import Bot -from bot.constants import Channels, Month, NEGATIVE_REPLIES, Tokens, WHITELISTED_CHANNELS +from bot.constants import Channels, Colours, Month, NEGATIVE_REPLIES, Tokens, WHITELISTED_CHANNELS from bot.utils.decorators import in_month, whitelist_override log = logging.getLogger(__name__) @@ -157,7 +157,7 @@ class HacktoberStats(commands.Cog): stats_embed = discord.Embed( title=f"{github_username}'s Hacktoberfest", - color=0x9c4af7, + color=Colours.purple, description=( f"{github_username} has made {n} valid " f"{self._contributionator(n)} in " @@ -227,7 +227,7 @@ class HacktoberStats(commands.Cog): f"+created:{date_range}" f"&per_page={per_page}" ) - log.logProcesses.debug(f"GitHub query URL generated: {query_url}") + log.debug(f"GitHub query URL generated: {query_url}") jsonresp = await self._fetch_url(query_url, REQUEST_HEADERS) if "message" in jsonresp: -- cgit v1.2.3 From dd20f59b9fb12288f286d479b5719697ab1a30f4 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Tue, 4 May 2021 15:04:18 -0400 Subject: Apply suggested changes to hanukkah_embed.py --- bot/exts/christmas/hanukkah_embed.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'bot') diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index 32002f76..214044b8 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -65,24 +65,24 @@ class HanukkahEmbed(commands.Cog): hanukkah_start_hour = 18 if hours < hanukkah_start_hour: embed.description = (f"Hanukkah hasnt started yet, " - f"it will start in about {hanukkah_start_hour-hours} hour/s.") + f"it will start in about {hanukkah_start_hour - hours} hour/s.") await ctx.send(embed=embed) return elif hours > hanukkah_start_hour: embed.description = (f"It is the starting day of Hanukkah ! " - f"Its been {hours-hanukkah_start_hour} hours hanukkah started !") + f"Its been {hours - hanukkah_start_hour} hours hanukkah started !") await ctx.send(embed=embed) return festival_day = self.hanukkah_days.index(day) number_suffixes = ["st", "nd", "rd", "th"] suffix = "" - if int(festival_day) == 1: + if festival_day == 1: suffix = number_suffixes[0] - if int(festival_day) == 2: + if festival_day == 2: suffix = number_suffixes[1] - if int(festival_day) == 3: + if festival_day == 3: suffix = number_suffixes[2] - if int(festival_day) > 3: + if festival_day > 3: suffix = number_suffixes[3] message = "" for _ in range(1, festival_day + 1): -- cgit v1.2.3 From 6d31315fa72ca9e6ccd7553e78548fed6e5e4829 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Tue, 4 May 2021 15:44:31 -0400 Subject: fix: Pass bot only when __init__ is defined --- bot/exts/easter/bunny_name_generator.py | 2 +- bot/exts/easter/egg_decorating.py | 2 +- bot/exts/evergreen/avatar_modification/avatar_modify.py | 5 +++-- bot/exts/evergreen/bookmark.py | 2 +- bot/exts/evergreen/catify.py | 8 +++----- bot/exts/evergreen/conversationstarters.py | 2 +- bot/exts/evergreen/emoji.py | 2 +- bot/exts/evergreen/error_handler.py | 2 +- bot/exts/evergreen/latex.py | 2 +- bot/exts/evergreen/pythonfacts.py | 2 +- bot/exts/evergreen/snakes/__init__.py | 5 ++--- bot/exts/evergreen/source.py | 2 +- bot/exts/evergreen/speedrun.py | 2 +- bot/exts/evergreen/timed.py | 2 +- bot/exts/evergreen/uptime.py | 2 +- bot/exts/halloween/timeleft.py | 5 +---- bot/exts/valentines/be_my_valentine.py | 4 ++-- bot/exts/valentines/lovecalculator.py | 2 +- bot/exts/valentines/movie_generator.py | 4 ++-- bot/exts/valentines/myvalenstate.py | 7 ++----- bot/exts/valentines/pickuplines.py | 2 +- bot/exts/valentines/savethedate.py | 2 +- bot/exts/valentines/valentine_zodiac.py | 2 +- bot/exts/valentines/whoisvalentine.py | 2 +- 24 files changed, 32 insertions(+), 40 deletions(-) (limited to 'bot') diff --git a/bot/exts/easter/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index 23f85226..19a0b0f6 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -88,4 +88,4 @@ class BunnyNameGenerator(commands.Cog): def setup(bot: Bot) -> None: """Load the Bunny Name Generator Cog.""" - bot.add_cog(BunnyNameGenerator(bot)) + bot.add_cog(BunnyNameGenerator()) diff --git a/bot/exts/easter/egg_decorating.py b/bot/exts/easter/egg_decorating.py index 1432fa31..3744989d 100644 --- a/bot/exts/easter/egg_decorating.py +++ b/bot/exts/easter/egg_decorating.py @@ -118,4 +118,4 @@ class EggDecorating(commands.Cog): def setup(bot: Bot) -> None: """Load the Egg decorating Cog.""" - bot.add_cog(EggDecorating(bot)) + bot.add_cog(EggDecorating()) diff --git a/bot/exts/evergreen/avatar_modification/avatar_modify.py b/bot/exts/evergreen/avatar_modification/avatar_modify.py index 0baee8b2..2304e459 100644 --- a/bot/exts/evergreen/avatar_modification/avatar_modify.py +++ b/bot/exts/evergreen/avatar_modification/avatar_modify.py @@ -11,6 +11,7 @@ from aiohttp import client_exceptions from discord.ext import commands from discord.ext.commands.errors import BadArgument +from bot.bot import Bot from bot.constants import Client, Colours, Emojis from bot.exts.evergreen.avatar_modification._effects import PfpEffects from bot.utils.extensions import invoke_help_command @@ -58,7 +59,7 @@ def file_safe_name(effect: str, display_name: str) -> str: class AvatarModify(commands.Cog): """Various commands for users to apply affects to their own avatars.""" - def __init__(self, bot: commands.Bot) -> None: + def __init__(self, bot: Bot) -> None: self.bot = bot async def _fetch_member(self, member_id: int) -> t.Optional[discord.Member]: @@ -309,6 +310,6 @@ class AvatarModify(commands.Cog): await ctx.send(file=file, embed=embed) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the PfpModify cog.""" bot.add_cog(AvatarModify(bot)) diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 6a272784..f0fad0ea 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -60,4 +60,4 @@ class Bookmark(commands.Cog): def setup(bot: Bot) -> None: """Load the Bookmark cog.""" - bot.add_cog(Bookmark(bot)) + bot.add_cog(Bookmark()) diff --git a/bot/exts/evergreen/catify.py b/bot/exts/evergreen/catify.py index d8a7442d..b4ae4a25 100644 --- a/bot/exts/evergreen/catify.py +++ b/bot/exts/evergreen/catify.py @@ -5,6 +5,7 @@ from typing import Optional from discord import AllowedMentions, Embed, Forbidden from discord.ext import commands +from bot.bot import Bot from bot.constants import Cats, Colours, NEGATIVE_REPLIES from bot.utils import helpers @@ -12,9 +13,6 @@ from bot.utils import helpers class Catify(commands.Cog): """Cog for the catify command.""" - def __init__(self, bot: commands.Bot): - self.bot = bot - @commands.command(aliases=["ᓚᘏᗢify", "ᓚᘏᗢ"]) async def catify(self, ctx: commands.Context, *, text: Optional[str]) -> None: """ @@ -82,6 +80,6 @@ class Catify(commands.Cog): ) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Loads the catify cog.""" - bot.add_cog(Catify(bot)) + bot.add_cog(Catify()) diff --git a/bot/exts/evergreen/conversationstarters.py b/bot/exts/evergreen/conversationstarters.py index 4fe8c47c..fdc4467a 100644 --- a/bot/exts/evergreen/conversationstarters.py +++ b/bot/exts/evergreen/conversationstarters.py @@ -66,4 +66,4 @@ class ConvoStarters(commands.Cog): def setup(bot: Bot) -> None: """Load the ConvoStarters cog.""" - bot.add_cog(ConvoStarters(bot)) + bot.add_cog(ConvoStarters()) diff --git a/bot/exts/evergreen/emoji.py b/bot/exts/evergreen/emoji.py index e7452a15..11615214 100644 --- a/bot/exts/evergreen/emoji.py +++ b/bot/exts/evergreen/emoji.py @@ -120,4 +120,4 @@ class Emojis(commands.Cog): def setup(bot: Bot) -> None: """Load the Emojis cog.""" - bot.add_cog(Emojis(bot)) + bot.add_cog(Emojis()) diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index 5cd8d28d..62529f52 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -135,4 +135,4 @@ class CommandErrorHandler(commands.Cog): def setup(bot: Bot) -> None: """Load the ErrorHandler cog.""" - bot.add_cog(CommandErrorHandler(bot)) + bot.add_cog(CommandErrorHandler()) diff --git a/bot/exts/evergreen/latex.py b/bot/exts/evergreen/latex.py index 3a93907a..54d25267 100644 --- a/bot/exts/evergreen/latex.py +++ b/bot/exts/evergreen/latex.py @@ -93,4 +93,4 @@ class Latex(commands.Cog): def setup(bot: Bot) -> None: """Load the Latex Cog.""" - bot.add_cog(Latex(bot)) + bot.add_cog(Latex()) diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index 2dc4996f..c0086c20 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -28,4 +28,4 @@ class PythonFacts(commands.Cog): def setup(bot: Bot) -> None: """Load the PythonFacts Cog.""" - bot.add_cog(PythonFacts(bot)) + bot.add_cog(PythonFacts()) diff --git a/bot/exts/evergreen/snakes/__init__.py b/bot/exts/evergreen/snakes/__init__.py index bc42f0c2..049bc964 100644 --- a/bot/exts/evergreen/snakes/__init__.py +++ b/bot/exts/evergreen/snakes/__init__.py @@ -1,12 +1,11 @@ import logging -from discord.ext import commands - +from bot.bot import Bot from bot.exts.evergreen.snakes._snakes_cog import Snakes log = logging.getLogger(__name__) -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Snakes Cog load.""" bot.add_cog(Snakes(bot)) diff --git a/bot/exts/evergreen/source.py b/bot/exts/evergreen/source.py index 2f25e4cb..685b3111 100644 --- a/bot/exts/evergreen/source.py +++ b/bot/exts/evergreen/source.py @@ -104,4 +104,4 @@ class BotSource(commands.Cog): def setup(bot: Bot) -> None: """Load the BotSource cog.""" - bot.add_cog(BotSource(bot)) + bot.add_cog(BotSource()) diff --git a/bot/exts/evergreen/speedrun.py b/bot/exts/evergreen/speedrun.py index 110d5c13..d9820287 100644 --- a/bot/exts/evergreen/speedrun.py +++ b/bot/exts/evergreen/speedrun.py @@ -23,4 +23,4 @@ class Speedrun(commands.Cog): def setup(bot: Bot) -> None: """Load the Speedrun cog.""" - bot.add_cog(Speedrun(bot)) + bot.add_cog(Speedrun()) diff --git a/bot/exts/evergreen/timed.py b/bot/exts/evergreen/timed.py index 42a77346..491231cc 100644 --- a/bot/exts/evergreen/timed.py +++ b/bot/exts/evergreen/timed.py @@ -45,4 +45,4 @@ class TimedCommands(commands.Cog): def setup(bot: Bot) -> None: """Load the Timed cog.""" - bot.add_cog(TimedCommands(bot)) + bot.add_cog(TimedCommands()) diff --git a/bot/exts/evergreen/uptime.py b/bot/exts/evergreen/uptime.py index d2509e6f..b390e7f7 100644 --- a/bot/exts/evergreen/uptime.py +++ b/bot/exts/evergreen/uptime.py @@ -28,4 +28,4 @@ class Uptime(commands.Cog): def setup(bot: Bot) -> None: """Load the Uptime cog.""" - bot.add_cog(Uptime(bot)) + bot.add_cog(Uptime()) diff --git a/bot/exts/halloween/timeleft.py b/bot/exts/halloween/timeleft.py index f4ab9284..e80025dc 100644 --- a/bot/exts/halloween/timeleft.py +++ b/bot/exts/halloween/timeleft.py @@ -12,9 +12,6 @@ log = logging.getLogger(__name__) class TimeLeft(commands.Cog): """A Cog that tells you how long left until Hacktober is over!""" - def __init__(self, bot: Bot): - self.bot = bot - def in_hacktober(self) -> bool: """Return True if the current time is within Hacktoberfest.""" _, end, start = self.load_date() @@ -68,4 +65,4 @@ class TimeLeft(commands.Cog): def setup(bot: Bot) -> None: """Load the Time Left Cog.""" - bot.add_cog(TimeLeft(bot)) + bot.add_cog(TimeLeft()) diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index e94efda0..cf6099d2 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -21,7 +21,7 @@ HEART_EMOJIS = [":heart:", ":gift_heart:", ":revolving_hearts:", ":sparkling_hea class BeMyValentine(commands.Cog): """A cog that sends Valentines to other users!""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot self.valentines = self.load_json() @@ -198,5 +198,5 @@ class BeMyValentine(commands.Cog): def setup(bot: Bot) -> None: - """Be my Valentine Cog load.""" + """Load the Be my Valentine Cog.""" bot.add_cog(BeMyValentine(bot)) diff --git a/bot/exts/valentines/lovecalculator.py b/bot/exts/valentines/lovecalculator.py index c2a5da26..e55dc128 100644 --- a/bot/exts/valentines/lovecalculator.py +++ b/bot/exts/valentines/lovecalculator.py @@ -93,5 +93,5 @@ class LoveCalculator(Cog): def setup(bot: Bot) -> None: - """Love calculator Cog load.""" + """Load the Love calculator Cog.""" bot.add_cog(LoveCalculator()) diff --git a/bot/exts/valentines/movie_generator.py b/bot/exts/valentines/movie_generator.py index 461255ff..4508c3b2 100644 --- a/bot/exts/valentines/movie_generator.py +++ b/bot/exts/valentines/movie_generator.py @@ -16,7 +16,7 @@ log = logging.getLogger(__name__) class RomanceMovieFinder(commands.Cog): """A Cog that returns a random romance movie suggestion to a user.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @commands.command(name="romancemovie") @@ -62,5 +62,5 @@ class RomanceMovieFinder(commands.Cog): def setup(bot: Bot) -> None: - """Romance movie Cog load.""" + """Load the Romance movie Cog.""" bot.add_cog(RomanceMovieFinder(bot)) diff --git a/bot/exts/valentines/myvalenstate.py b/bot/exts/valentines/myvalenstate.py index 7a0f8318..1c67984b 100644 --- a/bot/exts/valentines/myvalenstate.py +++ b/bot/exts/valentines/myvalenstate.py @@ -19,9 +19,6 @@ with open(Path("bot/resources/valentines/valenstates.json"), "r", encoding="utf8 class MyValenstate(commands.Cog): """A Cog to find your most likely Valentine's vacation destination.""" - def __init__(self, bot: commands.Bot): - self.bot = bot - def levenshtein(self, source: str, goal: str) -> int: """Calculates the Levenshtein Distance between source and goal.""" if len(source) < len(goal): @@ -83,5 +80,5 @@ class MyValenstate(commands.Cog): def setup(bot: Bot) -> None: - """Valenstate Cog load.""" - bot.add_cog(MyValenstate(bot)) + """Load the Valenstate Cog.""" + bot.add_cog(MyValenstate()) diff --git a/bot/exts/valentines/pickuplines.py b/bot/exts/valentines/pickuplines.py index 216ee13b..909169e6 100644 --- a/bot/exts/valentines/pickuplines.py +++ b/bot/exts/valentines/pickuplines.py @@ -38,5 +38,5 @@ class PickupLine(commands.Cog): def setup(bot: Bot) -> None: - """Pickup lines Cog load.""" + """Load the Pickup lines Cog.""" bot.add_cog(PickupLine()) diff --git a/bot/exts/valentines/savethedate.py b/bot/exts/valentines/savethedate.py index ed2d2c5f..cc16f5c9 100644 --- a/bot/exts/valentines/savethedate.py +++ b/bot/exts/valentines/savethedate.py @@ -35,5 +35,5 @@ class SaveTheDate(commands.Cog): def setup(bot: Bot) -> None: - """Save the date Cog Load.""" + """Load the Save the date Cog.""" bot.add_cog(SaveTheDate()) diff --git a/bot/exts/valentines/valentine_zodiac.py b/bot/exts/valentines/valentine_zodiac.py index 72fd93fe..a444a355 100644 --- a/bot/exts/valentines/valentine_zodiac.py +++ b/bot/exts/valentines/valentine_zodiac.py @@ -142,5 +142,5 @@ class ValentineZodiac(commands.Cog): def setup(bot: Bot) -> None: - """Valentine zodiac Cog load.""" + """Load the Valentine zodiac Cog.""" bot.add_cog(ValentineZodiac()) diff --git a/bot/exts/valentines/whoisvalentine.py b/bot/exts/valentines/whoisvalentine.py index 3789fad5..3f23201f 100644 --- a/bot/exts/valentines/whoisvalentine.py +++ b/bot/exts/valentines/whoisvalentine.py @@ -46,5 +46,5 @@ class ValentineFacts(commands.Cog): def setup(bot: Bot) -> None: - """Who is Valentine Cog load.""" + """Load the Who is Valentine Cog.""" bot.add_cog(ValentineFacts()) -- cgit v1.2.3 From d73eaf3d4d0724444161d0232533b2daaf7baedd Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Tue, 4 May 2021 16:03:25 -0400 Subject: chore: Change back to the original string --- bot/exts/evergreen/game.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 7abbadcd..f3d4e9a2 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -260,7 +260,7 @@ class Games(Cog): display_possibilities = "`, `".join(p[1] for p in possibilities) await ctx.send( f"Invalid genre `{genre}`. " - f"Maybe you meant `{display_possibilities}`?" if display_possibilities else '' + f"{f'Maybe you meant `{display_possibilities}`?' if display_possibilities else ''}" ) return elif len(possibilities) == 1: -- cgit v1.2.3 From f7c9fecf5dbab7320ff91eecd322c5521034b628 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Tue, 4 May 2021 16:15:57 -0400 Subject: chore: Replace the remaining double quotes with double quotes --- bot/__init__.py | 2 +- bot/exts/evergreen/reddit.py | 2 +- bot/exts/halloween/halloweenify.py | 4 ++-- bot/exts/valentines/lovecalculator.py | 12 ++++++------ bot/utils/pagination.py | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) (limited to 'bot') diff --git a/bot/__init__.py b/bot/__init__.py index 71b7c8a3..669f9f5d 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -64,7 +64,7 @@ logging.getLogger("matplotlib").setLevel(logging.ERROR) # Setup new logging configuration logging.basicConfig( - format='%(asctime)s - %(name)s %(levelname)s: %(message)s', + format="%(asctime)s - %(name)s %(levelname)s: %(message)s", datefmt="%D %H:%M:%S", level=logging.TRACE if Client.debug else logging.DEBUG, handlers=[console_handler, file_handler], diff --git a/bot/exts/evergreen/reddit.py b/bot/exts/evergreen/reddit.py index 82af6ce9..f2b95fe2 100644 --- a/bot/exts/evergreen/reddit.py +++ b/bot/exts/evergreen/reddit.py @@ -84,7 +84,7 @@ class Reddit(commands.Cog): for i, post in enumerate(random_posts, start=1): post_title = post["data"]["title"][0:50] - post_url = post['data']['url'] + post_url = post["data"]["url"] if post_title == "": post_title = "No Title." elif post_title == post_url: diff --git a/bot/exts/halloween/halloweenify.py b/bot/exts/halloween/halloweenify.py index 47b20a2a..df55b55d 100644 --- a/bot/exts/halloween/halloweenify.py +++ b/bot/exts/halloween/halloweenify.py @@ -26,8 +26,8 @@ class Halloweenify(commands.Cog): # Choose a random character from our list we loaded above and set apart the nickname and image url. character = choice(data["characters"]) - nickname = ''.join([nickname for nickname in character]) - image = ''.join([character[nickname] for nickname in character]) + nickname = "".join([nickname for nickname in character]) + image = "".join([character[nickname] for nickname in character]) # Build up a Embed embed = discord.Embed() diff --git a/bot/exts/valentines/lovecalculator.py b/bot/exts/valentines/lovecalculator.py index e55dc128..9096d994 100644 --- a/bot/exts/valentines/lovecalculator.py +++ b/bot/exts/valentines/lovecalculator.py @@ -23,7 +23,7 @@ with Path("bot/resources/valentines/love_matches.json").open(encoding="utf8") as class LoveCalculator(Cog): """A cog for calculating the love between two people.""" - @commands.command(aliases=('love_calculator', 'love_calc')) + @commands.command(aliases=("love_calculator", "love_calc")) @commands.cooldown(rate=1, per=5, type=commands.BucketType.user) async def love(self, ctx: commands.Context, who: Union[Member, str], whom: Union[Member, str] = None) -> None: """ @@ -61,7 +61,7 @@ class LoveCalculator(Cog): # Make sure user didn't provide something silly such as 10 spaces if not (who and whom): - raise BadArgument('Arguments be non-empty strings.') + raise BadArgument("Arguments be non-empty strings.") # Hash inputs to guarantee consistent results (hashing algorithm choice arbitrary) # @@ -78,15 +78,15 @@ class LoveCalculator(Cog): # We only need the dict, so we can ditch the first element _, data = LOVE_DATA[index] - status = random.choice(data['titles']) + status = random.choice(data["titles"]) embed = discord.Embed( title=status, - description=f'{who} \N{HEAVY BLACK HEART} {whom} scored {love_percent}%!\n\u200b', + description=f"{who} \N{HEAVY BLACK HEART} {whom} scored {love_percent}%!\n\u200b", color=discord.Color.dark_magenta() ) embed.add_field( - name='A letter from Dr. Love:', - value=data['text'] + name="A letter from Dr. Love:", + value=data["text"] ) await ctx.send(embed=embed) diff --git a/bot/utils/pagination.py b/bot/utils/pagination.py index a073a00b..e0dc25b4 100644 --- a/bot/utils/pagination.py +++ b/bot/utils/pagination.py @@ -283,7 +283,7 @@ class ImagePaginator(Paginator): self.images = [] self._pages = [] - def add_line(self, line: str = '', *, empty: bool = False) -> None: + def add_line(self, line: str = "", *, empty: bool = False) -> None: """ Adds a line to each page, usually just 1 line in this context. -- cgit v1.2.3 From 6ae760663b7055f9b74089591b4f46ac75c6f8e5 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Wed, 5 May 2021 12:10:18 -0400 Subject: chore: Don't have defaults for typing.Optional[...] in commands --- bot/exts/evergreen/game.py | 2 +- bot/exts/evergreen/space.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index f3d4e9a2..4da33259 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -225,7 +225,7 @@ class Games(Cog): self.genres[genre_name] = genre @group(name="games", aliases=["game"], invoke_without_command=True) - async def games(self, ctx: Context, amount: Optional[int] = 5, *, genre: Optional[str] = None) -> None: + async def games(self, ctx: Context, amount: Optional[int] = 5, *, genre: Optional[str]) -> None: """ Get random game(s) by genre from IGDB. Use .games genres command to get all available genres. diff --git a/bot/exts/evergreen/space.py b/bot/exts/evergreen/space.py index ee9ad38c..7d83dbfb 100644 --- a/bot/exts/evergreen/space.py +++ b/bot/exts/evergreen/space.py @@ -66,7 +66,7 @@ class Space(Cog): await invoke_help_command(ctx) @space.command(name="apod") - async def apod(self, ctx: Context, date: Optional[str] = None) -> None: + async def apod(self, ctx: Context, date: Optional[str]) -> None: """ Get Astronomy Picture of Day from NASA API. Date is optional parameter, what formatting is YYYY-MM-DD. @@ -99,7 +99,7 @@ class Space(Cog): ) @space.command(name="nasa") - async def nasa(self, ctx: Context, *, search_term: Optional[str] = None) -> None: + async def nasa(self, ctx: Context, *, search_term: Optional[str]) -> None: """Get random NASA information/facts + image. Support `search_term` parameter for more specific search.""" params = { "media_type": "image" @@ -124,7 +124,7 @@ class Space(Cog): ) @space.command(name="epic") - async def epic(self, ctx: Context, date: Optional[str] = None) -> None: + async def epic(self, ctx: Context, date: Optional[str]) -> None: """Get one of latest random image of earth from NASA EPIC API. Support date parameter, format is YYYY-MM-DD.""" if date: try: @@ -160,8 +160,8 @@ class Space(Cog): async def mars( self, ctx: Context, - date: Optional[DateConverter] = None, - rover: Optional[str] = "curiosity" + date: Optional[DateConverter], + rover: str = "curiosity" ) -> None: """ Get random Mars image by date. Support both SOL (martian solar day) and earth date and rovers. -- cgit v1.2.3 From 7a18b365f3ffe43fe3de6bb342d98b0414e0283c Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Wed, 5 May 2021 13:23:59 -0400 Subject: chore: Don't use "is not None" Co-authored-by: Anand Krishna <40204976+anand2312@users.noreply.github.com> --- bot/exts/evergreen/githubinfo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/githubinfo.py b/bot/exts/evergreen/githubinfo.py index 24479c79..fe126aa2 100644 --- a/bot/exts/evergreen/githubinfo.py +++ b/bot/exts/evergreen/githubinfo.py @@ -67,7 +67,7 @@ class GithubInfo(commands.Cog): embed = discord.Embed( title=f"`{user_data['login']}`'s GitHub profile info", - description=f"```{user_data['bio']}```\n" if user_data["bio"] is not None else "", + description=f"```{user_data['bio']}```\n" if user_data["bio"] else "", colour=discord.Colour.blurple(), url=user_data["html_url"], timestamp=datetime.strptime(user_data["created_at"], "%Y-%m-%dT%H:%M:%SZ") -- cgit v1.2.3 From 888f83170bce384315a0a5c47b87b7ffbfb5d8ea Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Wed, 5 May 2021 13:46:08 -0400 Subject: chore: Add all of the converters into bot/utils/converters.py --- bot/exts/evergreen/minesweeper.py | 28 +------------- bot/exts/evergreen/source.py | 23 +----------- bot/exts/evergreen/space.py | 19 ++-------- bot/utils/converters.py | 77 +++++++++++++++++++++++++++++++++++++-- 4 files changed, 80 insertions(+), 67 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/minesweeper.py b/bot/exts/evergreen/minesweeper.py index bd28d365..7a31dfde 100644 --- a/bot/exts/evergreen/minesweeper.py +++ b/bot/exts/evergreen/minesweeper.py @@ -8,6 +8,7 @@ from discord.ext import commands from bot.bot import Bot from bot.constants import Client +from bot.utils.converters import CoordinateConverter from bot.utils.exceptions import UserNotPlayingError from bot.utils.extensions import invoke_help_command @@ -32,33 +33,6 @@ MESSAGE_MAPPING = { log = logging.getLogger(__name__) -class CoordinateConverter(commands.Converter): - """Converter for Coordinates.""" - - async def convert(self, ctx: commands.Context, coordinate: str) -> typing.Tuple[int, int]: - """Take in a coordinate string and turn it into an (x, y) tuple.""" - if not 2 <= len(coordinate) <= 3: - raise commands.BadArgument("Invalid co-ordinate provided.") - - coordinate = coordinate.lower() - if coordinate[0].isalpha(): - digit = coordinate[1:] - letter = coordinate[0] - else: - digit = coordinate[:-1] - letter = coordinate[-1] - - if not digit.isdigit(): - raise commands.BadArgument - - x = ord(letter) - ord("a") - y = int(digit) - 1 - - if (not 0 <= x <= 9) or (not 0 <= y <= 9): - raise commands.BadArgument - return x, y - - GameBoard = typing.List[typing.List[typing.Union[str, int]]] diff --git a/bot/exts/evergreen/source.py b/bot/exts/evergreen/source.py index 685b3111..8fb72143 100644 --- a/bot/exts/evergreen/source.py +++ b/bot/exts/evergreen/source.py @@ -1,32 +1,13 @@ import inspect from pathlib import Path -from typing import Optional, Tuple, Union +from typing import Optional, Tuple from discord import Embed from discord.ext import commands from bot.bot import Bot from bot.constants import Source - -SourceType = Union[commands.Command, commands.Cog, str, commands.ExtensionNotLoaded] - - -class SourceConverter(commands.Converter): - """Convert an argument into a help command, tag, command, or cog.""" - - async def convert(self, ctx: commands.Context, argument: str) -> SourceType: - """Convert argument into source object.""" - cog = ctx.bot.get_cog(argument) - if cog: - return cog - - cmd = ctx.bot.get_command(argument) - if cmd: - return cmd - - raise commands.BadArgument( - f"Unable to convert `{argument}` to valid command or Cog." - ) +from bot.utils.converters import SourceConverter, SourceType class BotSource(commands.Cog): diff --git a/bot/exts/evergreen/space.py b/bot/exts/evergreen/space.py index 7d83dbfb..77b63946 100644 --- a/bot/exts/evergreen/space.py +++ b/bot/exts/evergreen/space.py @@ -1,15 +1,16 @@ import logging import random from datetime import date, datetime -from typing import Any, Dict, Optional, Union +from typing import Any, Dict, Optional from urllib.parse import urlencode from discord import Embed from discord.ext import tasks -from discord.ext.commands import BadArgument, Cog, Context, Converter, group +from discord.ext.commands import Cog, Context, group from bot.bot import Bot from bot.constants import Tokens +from bot.utils.converters import DateConverter from bot.utils.extensions import invoke_help_command logger = logging.getLogger(__name__) @@ -21,20 +22,6 @@ NASA_EPIC_BASE_URL = "https://epic.gsfc.nasa.gov" APOD_MIN_DATE = date(1995, 6, 16) -class DateConverter(Converter): - """Parse SOL or earth date (in format YYYY-MM-DD) into `int` or `datetime`. When invalid input, raise error.""" - - async def convert(self, ctx: Context, argument: str) -> Union[int, datetime]: - """Parse date (SOL or earth) into `datetime` or `int`. When invalid value, raise error.""" - if argument.isdigit(): - return int(argument) - try: - date = datetime.strptime(argument, "%Y-%m-%d") - except ValueError: - raise BadArgument(f"Can't convert `{argument}` to `datetime` in format `YYYY-MM-DD` or `int` in SOL.") - return date - - class Space(Cog): """Space Cog contains commands, that show images, facts or other information about space.""" diff --git a/bot/utils/converters.py b/bot/utils/converters.py index 228714c9..98607087 100644 --- a/bot/utils/converters.py +++ b/bot/utils/converters.py @@ -1,11 +1,15 @@ +from datetime import datetime +from typing import Tuple, Union + import discord -from discord.ext.commands.converter import MessageConverter +from discord.ext import commands -class WrappedMessageConverter(MessageConverter): +class WrappedMessageConverter(commands.MessageConverter): """A converter that handles embed-suppressed links like .""" - async def convert(self, ctx: discord.ext.commands.Context, argument: str) -> discord.Message: + @staticmethod + async def convert(ctx: commands.Context, argument: str) -> discord.Message: """Wrap the commands.MessageConverter to handle <> delimited message links.""" # It's possible to wrap a message in [<>] as well, and it's supported because its easy if argument.startswith("[") and argument.endswith("]"): @@ -14,3 +18,70 @@ class WrappedMessageConverter(MessageConverter): argument = argument[1:-1] return await super().convert(ctx, argument) + + +class CoordinateConverter(commands.Converter): + """Converter for Coordinates.""" + + @staticmethod + async def convert(ctx: commands.Context, coordinate: str) -> Tuple[int, int]: + """Take in a coordinate string and turn it into an (x, y) tuple.""" + if len(coordinate) not in (2, 3): + raise commands.BadArgument("Invalid co-ordinate provided.") + + coordinate = coordinate.lower() + if coordinate[0].isalpha(): + digit = coordinate[1:] + letter = coordinate[0] + else: + digit = coordinate[:-1] + letter = coordinate[-1] + + if not digit.isdigit(): + raise commands.BadArgument + + x = ord(letter) - ord("a") + y = int(digit) - 1 + + if (not 0 <= x <= 9) or (not 0 <= y <= 9): + raise commands.BadArgument + return x, y + + +SourceType = Union[commands.Command, commands.Cog] + + +class SourceConverter(commands.Converter): + """Convert an argument into a command or cog.""" + + @staticmethod + async def convert(ctx: commands.Context, argument: str) -> SourceType: + """Convert argument into source object.""" + cog = ctx.bot.get_cog(argument) + if cog: + return cog + + cmd = ctx.bot.get_command(argument) + if cmd: + return cmd + + raise commands.BadArgument( + f"Unable to convert `{argument}` to valid command or Cog." + ) + + +class DateConverter(commands.Converter): + """Parse SOL or earth date (in format YYYY-MM-DD) into `int` or `datetime`. When invalid input, raise error.""" + + @staticmethod + async def convert(ctx: commands.Context, argument: str) -> Union[int, datetime]: + """Parse date (SOL or earth) into `datetime` or `int`. When invalid value, raise error.""" + if argument.isdigit(): + return int(argument) + try: + date = datetime.strptime(argument, "%Y-%m-%d") + except ValueError: + raise commands.BadArgument( + f"Can't convert `{argument}` to `datetime` in format `YYYY-MM-DD` or `int` in SOL." + ) + return date -- cgit v1.2.3 From 780aaeb5c272f7a9fd9fe9e8cdc1c041beb90a25 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Wed, 5 May 2021 14:20:40 -0400 Subject: chore: Apply anand's suggested changes --- bot/exts/evergreen/error_handler.py | 2 +- bot/exts/evergreen/githubinfo.py | 3 +- bot/exts/evergreen/movie.py | 10 +- bot/exts/evergreen/reddit.py | 3 +- bot/exts/evergreen/snakes/__init__.py | 2 +- bot/exts/evergreen/snakes/_snakes_cog.py | 175 +++++++++++++++---------------- 6 files changed, 96 insertions(+), 99 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index 62529f52..faaf1386 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -39,7 +39,7 @@ class CommandErrorHandler(commands.Cog): @commands.Cog.listener() async def on_command_error(self, ctx: commands.Context, error: commands.CommandError) -> None: - """Activates when a command opens an error.""" + """Activates when a command raises an error.""" if getattr(error, "handled", False): logging.debug(f"Command {ctx.command} had its error already handled locally; ignoring.") return diff --git a/bot/exts/evergreen/githubinfo.py b/bot/exts/evergreen/githubinfo.py index fe126aa2..27e607e5 100644 --- a/bot/exts/evergreen/githubinfo.py +++ b/bot/exts/evergreen/githubinfo.py @@ -5,7 +5,6 @@ from urllib.parse import quote import discord from discord.ext import commands -from discord.ext.commands.cooldowns import BucketType from bot.bot import Bot from bot.constants import Colours, NEGATIVE_REPLIES @@ -28,7 +27,7 @@ class GithubInfo(commands.Cog): return await r.json() @commands.group(name="github", aliases=("gh", "git")) - @commands.cooldown(1, 10, BucketType.user) + @commands.cooldown(1, 10, commands.BucketType.user) async def github_group(self, ctx: commands.Context) -> None: """Commands for finding information related to GitHub.""" if ctx.invoked_subcommand is None: diff --git a/bot/exts/evergreen/movie.py b/bot/exts/evergreen/movie.py index e67f8d04..fa284417 100644 --- a/bot/exts/evergreen/movie.py +++ b/bot/exts/evergreen/movie.py @@ -72,13 +72,13 @@ class Movie(Cog): # Capitalize genre for getting data from Enum, get random page, send help when genre don't exist. genre = genre.capitalize() try: - result = await self.get_movies_list(self.http_session, MovieGenres[genre].value, 1) + result = await self.get_movies_data(self.http_session, MovieGenres[genre].value, 1) except KeyError: await invoke_help_command(ctx) return # Check if "results" is in result. If not, throw error. - if "results" not in result.keys(): + if "results" not in result: err_msg = f"There is problem while making TMDB API request. Response Code: {result['status_code']}, " \ f"{result['status_message']}." await ctx.send(err_msg) @@ -88,8 +88,8 @@ class Movie(Cog): page = random.randint(1, result["total_pages"]) # Get movies list from TMDB, check if results key in result. When not, raise error. - movies = await self.get_movies_list(self.http_session, MovieGenres[genre].value, page) - if "results" not in movies.keys(): + movies = await self.get_movies_data(self.http_session, MovieGenres[genre].value, page) + if "results" not in movies: err_msg = f"There is problem while making TMDB API request. Response Code: {result['status_code']}, " \ f"{result['status_message']}." await ctx.send(err_msg) @@ -106,7 +106,7 @@ class Movie(Cog): """Show all currently available genres for .movies command.""" await ctx.send(f"Current available genres: {', '.join('`' + genre.name + '`' for genre in MovieGenres)}") - async def get_movies_list(self, client: ClientSession, genre_id: str, page: int) -> Dict[str, Any]: + async def get_movies_data(self, client: ClientSession, genre_id: str, page: int) -> List[Dict[str, Any]]: """Return JSON of TMDB discover request.""" # Define params of request params = { diff --git a/bot/exts/evergreen/reddit.py b/bot/exts/evergreen/reddit.py index f2b95fe2..bda155c3 100644 --- a/bot/exts/evergreen/reddit.py +++ b/bot/exts/evergreen/reddit.py @@ -3,7 +3,6 @@ import random import discord from discord.ext import commands -from discord.ext.commands.cooldowns import BucketType from bot.bot import Bot from bot.utils.pagination import ImagePaginator @@ -31,7 +30,7 @@ class Reddit(commands.Cog): return await response.json() @commands.command(name="reddit") - @commands.cooldown(1, 10, BucketType.user) + @commands.cooldown(1, 10, commands.BucketType.user) async def get_reddit(self, ctx: commands.Context, subreddit: str = "python", sort: str = "hot") -> None: """ Fetch reddit posts by using this command. diff --git a/bot/exts/evergreen/snakes/__init__.py b/bot/exts/evergreen/snakes/__init__.py index 049bc964..7740429b 100644 --- a/bot/exts/evergreen/snakes/__init__.py +++ b/bot/exts/evergreen/snakes/__init__.py @@ -7,5 +7,5 @@ log = logging.getLogger(__name__) def setup(bot: Bot) -> None: - """Snakes Cog load.""" + """Load the Snakes Cog.""" bot.add_cog(Snakes(bot)) diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index 353bcd66..62795aef 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -9,15 +9,15 @@ import textwrap import urllib from functools import partial from io import BytesIO -from typing import Any, Dict, List +from typing import Any, Dict, List, Optional -import aiohttp import async_timeout from PIL import Image, ImageDraw, ImageFont from discord import Colour, Embed, File, Member, Message, Reaction from discord.errors import HTTPException -from discord.ext.commands import Bot, Cog, CommandError, Context, bot_has_permissions, group +from discord.ext.commands import Cog, CommandError, Context, bot_has_permissions, group +from bot.bot import Bot from bot.constants import ERROR_REPLIES, Tokens from bot.exts.evergreen.snakes import _utils as utils from bot.exts.evergreen.snakes._converter import Snake @@ -275,13 +275,13 @@ class Snakes(Cog): return message - async def _fetch(self, session: aiohttp.ClientSession, url: str, params: dict = None) -> dict: + async def _fetch(self, url: str, params: Optional[dict] = None) -> dict: """Asynchronous web request helper method.""" if params is None: params = {} async with async_timeout.timeout(10): - async with session.get(url, params=params) as response: + async with self.bot.http_session.get(url, params=params) as response: return await response.json() def _get_random_long_message(self, messages: List[str], retries: int = 10) -> str: @@ -309,96 +309,95 @@ class Snakes(Cog): """ snake_info = {} - async with aiohttp.ClientSession() as session: - params = { - "format": "json", - "action": "query", - "list": "search", - "srsearch": name, - "utf8": "", - "srlimit": "1", - } - - json = await self._fetch(session, URL, params=params) - - # Wikipedia does have a error page - try: - pageid = json["query"]["search"][0]["pageid"] - except KeyError: - # Wikipedia error page ID(?) - pageid = 41118 - except IndexError: - return None - - params = { - "format": "json", - "action": "query", - "prop": "extracts|images|info", - "exlimit": "max", - "explaintext": "", - "inprop": "url", - "pageids": pageid - } + params = { + "format": "json", + "action": "query", + "list": "search", + "srsearch": name, + "utf8": "", + "srlimit": "1", + } - json = await self._fetch(session, URL, params=params) + json = await self._fetch(URL, params=params) - # Constructing dict - handle exceptions later - try: - snake_info["title"] = json["query"]["pages"][f"{pageid}"]["title"] - snake_info["extract"] = json["query"]["pages"][f"{pageid}"]["extract"] - snake_info["images"] = json["query"]["pages"][f"{pageid}"]["images"] - snake_info["fullurl"] = json["query"]["pages"][f"{pageid}"]["fullurl"] - snake_info["pageid"] = json["query"]["pages"][f"{pageid}"]["pageid"] - except KeyError: - snake_info["error"] = True - - if snake_info["images"]: - i_url = "https://commons.wikimedia.org/wiki/Special:FilePath/" - image_list = [] - map_list = [] - thumb_list = [] - - # Wikipedia has arbitrary images that are not snakes - banned = [ - "Commons-logo.svg", - "Red%20Pencil%20Icon.png", - "distribution", - "The%20Death%20of%20Cleopatra%20arthur.jpg", - "Head%20of%20holotype", - "locator", - "Woma.png", - "-map.", - ".svg", - "ange.", - "Adder%20(PSF).png" - ] - - for image in snake_info["images"]: - # Images come in the format of `File:filename.extension` - file, sep, filename = image["title"].partition(":") - filename = filename.replace(" ", "%20") # Wikipedia returns good data! - - if not filename.startswith("Map"): - if any(ban in filename for ban in banned): - pass - else: - image_list.append(f"{i_url}{filename}") - thumb_list.append(f"{i_url}{filename}?width=100") + # Wikipedia does have a error page + try: + pageid = json["query"]["search"][0]["pageid"] + except KeyError: + # Wikipedia error page ID(?) + pageid = 41118 + except IndexError: + return None + + params = { + "format": "json", + "action": "query", + "prop": "extracts|images|info", + "exlimit": "max", + "explaintext": "", + "inprop": "url", + "pageids": pageid + } + + json = await self._fetch(URL, params=params) + + # Constructing dict - handle exceptions later + try: + snake_info["title"] = json["query"]["pages"][f"{pageid}"]["title"] + snake_info["extract"] = json["query"]["pages"][f"{pageid}"]["extract"] + snake_info["images"] = json["query"]["pages"][f"{pageid}"]["images"] + snake_info["fullurl"] = json["query"]["pages"][f"{pageid}"]["fullurl"] + snake_info["pageid"] = json["query"]["pages"][f"{pageid}"]["pageid"] + except KeyError: + snake_info["error"] = True + + if snake_info["images"]: + i_url = "https://commons.wikimedia.org/wiki/Special:FilePath/" + image_list = [] + map_list = [] + thumb_list = [] + + # Wikipedia has arbitrary images that are not snakes + banned = [ + "Commons-logo.svg", + "Red%20Pencil%20Icon.png", + "distribution", + "The%20Death%20of%20Cleopatra%20arthur.jpg", + "Head%20of%20holotype", + "locator", + "Woma.png", + "-map.", + ".svg", + "ange.", + "Adder%20(PSF).png" + ] + + for image in snake_info["images"]: + # Images come in the format of `File:filename.extension` + file, sep, filename = image["title"].partition(":") + filename = filename.replace(" ", "%20") # Wikipedia returns good data! + + if not filename.startswith("Map"): + if any(ban in filename for ban in banned): + pass else: - map_list.append(f"{i_url}{filename}") + image_list.append(f"{i_url}{filename}") + thumb_list.append(f"{i_url}{filename}?width=100") + else: + map_list.append(f"{i_url}{filename}") - snake_info["image_list"] = image_list - snake_info["map_list"] = map_list - snake_info["thumb_list"] = thumb_list - snake_info["name"] = name + snake_info["image_list"] = image_list + snake_info["map_list"] = map_list + snake_info["thumb_list"] = thumb_list + snake_info["name"] = name - match = self.wiki_brief.match(snake_info["extract"]) - info = match.group(1) if match else None + match = self.wiki_brief.match(snake_info["extract"]) + info = match.group(1) if match else None - if info: - info = info.replace("\n", "\n\n") # Give us some proper paragraphs. + if info: + info = info.replace("\n", "\n\n") # Give us some proper paragraphs. - snake_info["info"] = info + snake_info["info"] = info return snake_info -- cgit v1.2.3 From 353264e53f54ba32d6f71fc027bf81aca871fdf7 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Wed, 5 May 2021 14:25:59 -0400 Subject: chore: Improve .space epic's docstring --- bot/exts/evergreen/space.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/space.py b/bot/exts/evergreen/space.py index 77b63946..6c991d26 100644 --- a/bot/exts/evergreen/space.py +++ b/bot/exts/evergreen/space.py @@ -112,7 +112,7 @@ class Space(Cog): @space.command(name="epic") async def epic(self, ctx: Context, date: Optional[str]) -> None: - """Get one of latest random image of earth from NASA EPIC API. Support date parameter, format is YYYY-MM-DD.""" + """Get a random image of the Earth from the NASA EPIC API. Support date parameter, format is YYYY-MM-DD.""" if date: try: show_date = datetime.strptime(date, "%Y-%m-%d").date().isoformat() -- cgit v1.2.3 From 19e2efaf5572a0edb4595bead6877aaae078adae Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Wed, 5 May 2021 14:46:29 -0400 Subject: chore: Apply suggested changes --- bot/exts/halloween/hacktober-issue-finder.py | 12 +++++++----- bot/exts/halloween/hacktoberstats.py | 3 +-- 2 files changed, 8 insertions(+), 7 deletions(-) (limited to 'bot') diff --git a/bot/exts/halloween/hacktober-issue-finder.py b/bot/exts/halloween/hacktober-issue-finder.py index baee9612..20a06770 100644 --- a/bot/exts/halloween/hacktober-issue-finder.py +++ b/bot/exts/halloween/hacktober-issue-finder.py @@ -73,15 +73,17 @@ class HacktoberIssues(commands.Cog): log.debug(f"making api request to url: {url}") async with self.bot.http_session.get(url, headers=REQUEST_HEADERS) as response: if response.status != 200: - log.error(f"expected 200 status (got {response.status}) from the GitHub api.") - await ctx.send(f"ERROR: expected 200 status (got {response.status}) from the GitHub api.") - await ctx.send(await response.text()) + log.error(f"expected 200 status (got {response.status}) by the GitHub api.") + await ctx.send( + f"ERROR: expected 200 status (got {response.status}) by the GitHub api.\n" + f"{await response.text()}" + ) return None data = await response.json() if len(data["items"]) == 0: - log.error(f"no issues returned from GitHub api. with url: {response.url}") - await ctx.send(f"ERROR: no issues returned from GitHub api. with url: {response.url}") + log.error(f"no issues returned by GitHub API, with url: {response.url}") + await ctx.send(f"ERROR: no issues returned by GitHub API, with url: {response.url}") return None if option == "beginner": diff --git a/bot/exts/halloween/hacktoberstats.py b/bot/exts/halloween/hacktoberstats.py index 33e9ca31..b74e680b 100644 --- a/bot/exts/halloween/hacktoberstats.py +++ b/bot/exts/halloween/hacktoberstats.py @@ -302,8 +302,7 @@ class HacktoberStats(commands.Cog): async def _fetch_url(self, url: str, headers: dict) -> dict: """Retrieve API response from URL.""" async with self.bot.http_session.get(url, headers=headers) as resp: - jsonresp = await resp.json() - return jsonresp + return await resp.json() @staticmethod def _has_label(pr: dict, labels: Union[List[str], str]) -> bool: -- cgit v1.2.3 From e22c03395b83d81b4c5de90378bc09fae9dce4e1 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Wed, 5 May 2021 15:33:08 -0400 Subject: chore: Use pathlib more often and apply other changes --- bot/exts/halloween/halloween_facts.py | 1 - bot/exts/halloween/monstersurvey.py | 16 ++++++++-------- bot/exts/pride/drag_queen_name.py | 4 ++-- 3 files changed, 10 insertions(+), 11 deletions(-) (limited to 'bot') diff --git a/bot/exts/halloween/halloween_facts.py b/bot/exts/halloween/halloween_facts.py index 139e0810..3a89b5aa 100644 --- a/bot/exts/halloween/halloween_facts.py +++ b/bot/exts/halloween/halloween_facts.py @@ -33,7 +33,6 @@ class HalloweenFacts(commands.Cog): with Path("bot/resources/halloween/halloween_facts.json").open("r", encoding="utf8") as file: self.halloween_facts = json.load(file) self.facts = list(enumerate(self.halloween_facts)) - random.shuffle(self.facts) def random_fact(self) -> Tuple[int, str]: """Return a random fact from the loaded facts.""" diff --git a/bot/exts/halloween/monstersurvey.py b/bot/exts/halloween/monstersurvey.py index 486e8937..38e3850e 100644 --- a/bot/exts/halloween/monstersurvey.py +++ b/bot/exts/halloween/monstersurvey.py @@ -1,6 +1,6 @@ import json import logging -import os +import pathlib from discord import Embed from discord.ext import commands @@ -25,24 +25,24 @@ class MonsterSurvey(Cog): def __init__(self): """Initializes values for the bot to use within the voting commands.""" - self.registry_location = os.path.join(os.getcwd(), "bot", "resources", "halloween", "monstersurvey.json") - with open(self.registry_location, "r", encoding="utf8") as jason: - self.voter_registry = json.load(jason) + self.registry_path = pathlib.Path("bot", "resources", "halloween", "monstersurvey.json") + with self.registry_path.open(encoding="utf8") as data: + self.voter_registry = json.load(data) def json_write(self) -> None: """Write voting results to a local JSON file.""" log.info("Saved Monster Survey Results") - with open(self.registry_location, "w", encoding="utf8") as jason: - json.dump(self.voter_registry, jason, indent=2) + with self.registry_path.open("w", encoding="utf8") as data: + json.dump(self.voter_registry, data, indent=2) def cast_vote(self, id: int, monster: str) -> None: """ - Cast a user"s vote for the specified monster. + Cast a user's vote for the specified monster. If the user has already voted, their existing vote is removed. """ vr = self.voter_registry - for m in vr.keys(): + for m in vr: if id not in vr[m]["votes"] and m == monster: vr[m]["votes"].append(id) else: diff --git a/bot/exts/pride/drag_queen_name.py b/bot/exts/pride/drag_queen_name.py index 9839f089..d9424001 100644 --- a/bot/exts/pride/drag_queen_name.py +++ b/bot/exts/pride/drag_queen_name.py @@ -19,7 +19,7 @@ class DragNames(commands.Cog): @staticmethod def load_names() -> list: """Loads a list of drag queen names.""" - with open(Path("bot/resources/pride/drag_queen_names.json"), "r", encoding="utf8") as f: + with Path("bot/resources/pride/drag_queen_names.json").open(encoding="utf8") as f: return json.load(f) @commands.command(name="dragname", aliases=["dragqueenname", "queenme"]) @@ -29,5 +29,5 @@ class DragNames(commands.Cog): def setup(bot: Bot) -> None: - """Load the Drag Queen Cog.""" + """Load the Drag Names Cog.""" bot.add_cog(DragNames()) -- cgit v1.2.3 From b486ed47478adf2916291497243e760026e686bd Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Wed, 5 May 2021 15:36:39 -0400 Subject: chore: Remove useless call of `dict.keys()` Co-authored-by: Anand Krishna <40204976+anand2312@users.noreply.github.com> --- bot/exts/halloween/monstersurvey.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/halloween/monstersurvey.py b/bot/exts/halloween/monstersurvey.py index 486e8937..42a316e6 100644 --- a/bot/exts/halloween/monstersurvey.py +++ b/bot/exts/halloween/monstersurvey.py @@ -84,7 +84,7 @@ class MonsterSurvey(Cog): value="Which monster has the most votes? This command will tell you.", inline=False ) - default_embed.set_footer(text=f"Monsters choices are: {', '.join(self.voter_registry.keys())}") + default_embed.set_footer(text=f"Monsters choices are: {', '.join(self.voter_registry)}") await ctx.send(embed=default_embed) -- cgit v1.2.3 From df65a5091100a59424bedc14144f37c43954d0b3 Mon Sep 17 00:00:00 2001 From: Chris Date: Thu, 6 May 2021 14:45:29 +0100 Subject: Use bot.bot.Bot for type hint, over commands.Bot --- bot/exts/evergreen/bookmark.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index f0b828f8..5f550a4a 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -5,6 +5,7 @@ import random import discord from discord.ext import commands +from bot.bot import Bot from bot.constants import Colours, ERROR_REPLIES, Icons from bot.utils.converters import WrappedMessageConverter @@ -18,7 +19,7 @@ BOOKMARK_EMOJI = "📌" class Bookmark(commands.Cog): """Creates personal bookmarks by relaying a message link to the user's DMs.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: Bot): self.bot = bot @staticmethod @@ -140,6 +141,6 @@ class Bookmark(commands.Cog): await reaction_message.delete() -def setup(bot: commands.Bot) -> None: +def setup(bot: Bot) -> None: """Load the Bookmark cog.""" bot.add_cog(Bookmark(bot)) -- cgit v1.2.3 From 4c3312a642f1876427d17a41eeb9c912f9cd4b06 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 10:41:30 -0300 Subject: Add 30 math questions and 30 science questions to trivia_quiz.json --- bot/resources/evergreen/trivia_quiz.json | 331 +++++++++++++++++++++++++++++++ 1 file changed, 331 insertions(+) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index a4225eb1..b20b953f 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -44,6 +44,24 @@ ], "question": "What was the first game Yoshi appeared in?", "answer": "Super Mario World" + }, + { + "id": 6, + "hints": [ + "They were used alternatively to playing cards.", + "They generally have handdrawn nature images on them." + ], + "question": "What did Nintendo make before video games and toys?", + "answer": "Hanafuda, Hanafuda cards" + }, + { + "id": 7, + "hints": [ + "Before being Nintendo's main competitor in home gaming, they were successful in arcades.", + "Their first console was called the Master System." + ], + "question": "Who was Nintendo's biggest competitor in 1990?", + "answer": "Sega" } ], "general": [ @@ -269,5 +287,318 @@ "answer": "1492", "info": "The explorer Christopher Columbus made four trips across the Atlantic Ocean from Spain: in 1492, 1493, 1498 and 1502. He was determined to find a direct water route west from Europe to Asia, but he never did. Instead, he stumbled upon the Americas" } + ], + "math": [ + { + "id": 201, + "question": "What is the highest power of a biquadratic polynomial?", + "answer": "4, four" + }, + { + "id": 202, + "question": "What is the formula for surface area of a sphere?", + "answer": "4pir^2, 4πr^2" + }, + { + "id": 203, + "question": "Which theorem states that hypotenuse2 = base2 + height2?", + "answer": "Pythagorean's, Pythagorean's theorem" + }, + { + "id": 204, + "question": "Which trigonometric function is defined as hypotenuse/opposite?", + "answer": "cosecant, cosec, csc" + }, + { + "id": 205, + "question": "Does the harmonic series converge or diverge?", + "answer": "diverge" + }, + { + "id": 206, + "question": "How many quadrants are there in a cartesian plane?", + "answer": "4, four" + }, + { + "id": 207, + "question": "What is the (0,0) coordinate in a cartesian plane termed as?", + "answer": "origin" + }, + { + "id": 208, + "question": "What's the following formula that finds the area of a triangle called?", + "img_url": "https://wikimedia.org/api/rest_v1/media/math/render/png/d22b8566e8187542966e8d166e72e93746a1a6fc", + "answer": "Heron's formula" + }, + { + "id": 209, + "dynamic_id": 201, + "question": "Solve the following system of linear equations (format your answer like this & ):\n{}x + {}y = {},\n{}x + {}y = {}", + "answer": "{} & {}" + }, + { + "id": 210, + "dynamic_id": 202, + "question": "What's {} + {} mod {} congruent to?", + "answer": "{}" + }, + { + "id": 211, + "question": "What is the bottom number on a fraction called?", + "answer": "denominator" + }, + { + "id": 212, + "dynamic_id": 203, + "question": "How many vertices are on a {}gonal prism?", + "answer": "{}" + }, + { + "id": 213, + "question": "What is the term used to describe two triangles that have equal corresponding sides and angle measures?", + "answer": "congruent" + }, + { + "id": 214, + "question": "⅓πr2h is the volume of which 3 dimensional figure?", + "answer": "cone" + }, + { + "id": 215, + "dynamic_id": 204, + "question": "Find the square root of -{}.", + "answer": "{}i" + }, + { + "id": 216, + "question": "In set builder notation, {p/q | q ≠ 0, p & q ∈ Z} represents what?", + "answer": "Rational Numbers" + }, + { + "id": 217, + "question": "What is the natural log of -1 (use i for imaginary number)?", + "answer": "pi*i, pii, πi" + }, + { + "id": 218, + "question": "When is the *inaugural* World Maths Day (format your answer in MM/DD)?", + "answer": "03/13" + }, + { + "id": 219, + "question": "As the Fibonacci sequence extends to infinity, what's the ratio of each number `n` and its preceding number `n-1` approaching?", + "answer": "Golden Ratio" + }, + { + "id": 220, + "question": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34 are numbers of which sequence?", + "answer": "Fibonacci" + }, + { + "id": 221, + "question": "Prime numbers only have __ factors.", + "answer": "2, two" + }, + { + "id": 222, + "question": "In probability, the ________ ______ of an experiment or random trial is the set of all possible outcomes of it.", + "answer": "sample space" + }, + { + "id": 223, + "question": "In statistics, what does this formula represent?", + "img_url": "https://www.statisticshowto.com/wp-content/uploads/2013/11/sample-standard-deviation.jpg", + "answer": "sample standard deviation, standard deviation of a sample" + }, + { + "id": 224, + "question": "\"Hexakosioihexekontahexaphobia\" is the fear of which number?", + "answer": "666" + }, + { + "id": 225, + "question": "Prove or disprove the Riemann Hypothesis", + "answer": "" + }, + { + "id": 226, + "dynamic_id": 205, + "question": "BASE TWO QUESTION: Calculate {} {} {}", + "answer": "{}" + }, + { + "id": 227, + "question": "What is the only number in the entire number system which can be spelled with the same number of letters as itself?", + "answer": "4, four" + + }, + { + "id": 228, + "question": "1/100th of a second is also termed as what?", + "answer": "jiffy" + }, + { + "id": 229, + "question": "What is this triangle called?", + "img_url": "https://cdn.askpython.com/wp-content/uploads/2020/07/Pascals-triangle.png", + "answer": "Pascal's triangle, Pascal" + }, + { + "id": 230, + "question": "6a^2 is the surface area of which 3 dimensional figure?", + "answer": "cube" + } + ], + "science": [ + { + "id": 301, + "question": "The three main components of a normal atom are: protons, neutrons, and…", + "answer": "electrons" + }, + { + "id": 302, + "question": "As of 2021, how many elements are there in the Periodic Table?", + "answer": "118" + }, + { + "id": 303, + "question": "What is the universal force discovered by Newton that causes objects with mass to attract each other called?", + "answer": "gravity" + }, + { + "id": 304, + "question": "What do you call an organism composed of only one cell?", + "answer": "unicellular, single-celled" + }, + { + "id": 305, + "question": "The Heisenberg’s Uncertainty Principle states that the position and ________ of a quantum object can’t be both exactly measured at the same time.", + "answer": "velocity, momentum" + }, + { + "id": 306, + "question": "A ____________ reaction is the one wherein an atom or a set of atoms is/are replaced by another atom or a set of atoms", + "answer": "displacement, exchange" + }, + { + "id": 307, + "question": "What is the process by which green plants and certain other organisms transform light energy into chemical energy?", + "answer": "photosynthesis" + }, + { + "id": 308, + "question": "DYNAMIC QUESTION, TO BE DETERMINED", + "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + }, + { + "id": 309, + "question": "DYNAMIC QUESTION, TO BE DETERMINED", + "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + }, + { + "id": 310, + "question": "DYNAMIC QUESTION, TO BE DETERMINED", + "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + }, + { + "id": 311, + "question": "How does one call the direct phase transition from gas to solid?", + "answer": "deposition" + }, + { + "id": 312, + "question": "What is the intermolecular force caused by temporary and induced dipoles?", + "answer": "LDF, London dispersion, London dispersion force" + }, + { + "id": 313, + "question": "What is the force that causes objects to float in fluids called?", + "answer": "buoyancy" + }, + { + "id": 314, + "question": "About how many neurons are in the human brain? (A. 1 billion, B. 10 billion, C. 100 billion, D. 300 billion)", + "answer": "C, 100 billion, 100 bil" + }, + { + "id": 315, + "question": "What is the name of our galaxy group in which the Milky Way resides?", + "answer": "Local Group" + }, + { + "id": 316, + "question": "Which cell organelle is nicknamed \"the powerhouse of the cell\"?", + "answer": "mitochondria" + }, + { + "id": 317, + "question": "Which vascular tissue transports water and minerals from the roots to the rest of a plant?", + "answer": "xylem" + }, + { + "id": 318, + "question": "Who discovered the theories of relativity?", + "answer": "Albert Einstein, Einstein" + }, + { + "id": 319, + "question": "In particle physics, the hypothetical isolated elementary particle with only one magnetic pole is termed as...", + "answer": "magnetic monopole" + }, + { + "id": 320, + "question": "How does one describe a chemical reaction wherein heat is released?", + "answer": "exothermic" + }, + { + "id": 321, + "question": "What range of frequency are the average human ears capable of hearing (A. 10Hz-10kHz, B. 20Hz-20kHz, C. 20Hz-2000Hz, D. 10kHz-20kHz)?", + "answer": "B, 20Hz-20kHz" + }, + { + "id": 322, + "question": "What is the process used to separate substances with different polarity in a mixture, using a stationary and mobile phase?", + "answer": "chromatography" + }, + { + "id": 323, + "question": "Which law states that the current through a conductor between two points is directly proportional to the voltage across the two points?", + "answer": "Ohm's law" + }, + { + "id": 324, + "question": "The type of rock that is formed by the accumulation or deposition of mineral or organic particles at the Earth's surface, followed by cementation, is called...", + "answer": "sedimentary, sedimentary rock" + }, + { + "id": 325, + "question": "Is the Richter scale (common earthquake scale) linear or logarithmic?", + "answer": "logarithmic" + }, + { + "id": 326, + "question": "What type of image is formed by a convex mirror?", + "answer": "virtual image, virtual" + }, + { + "id": 327, + "question": "How does one call the branch of physics that deals with the study of mechanical waves in gases, liquids, and solids including topics such as vibration, sound, ultrasound and infrasound", + "answer": "acoustics" + }, + { + "id": 328, + "question": "Which law states that the global entropy in a closed system can only increase?", + "answer": "second law of thermodynamics" + }, + { + "id": 329, + "question": "Which particle is emitted during the beta decay of a radioactive element?", + "answer": "an electron, electron" + }, + { + "id": 330, + "question": "When DNA is unzipped, two strands are formed. What are they called (separate both answers by the word \"and\")?", + "answer": "leading and lagging, leading strand and lagging strand" + } ] } -- cgit v1.2.3 From 113a20a62fdd55776052e3e1968a52aae2c07771 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 11:03:16 -0300 Subject: Implement the math and science questions, added a dynamic_id checker --- bot/exts/evergreen/trivia_quiz.py | 241 ++++++++++++++++++++++++++++---------- 1 file changed, 182 insertions(+), 59 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index fe692c2a..1139e3e1 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -25,34 +25,58 @@ class TriviaQuiz(commands.Cog): def __init__(self, bot: commands.Bot) -> None: self.bot = bot - self.questions = self.load_questions() + self.game_status = {} # A variable to store the game status: either running or not running. self.game_owners = {} # A variable to store the person's ID who started the quiz game in a channel. - self.question_limit = 4 + + self.questions = self.load_questions() + self.question_limit = 7 + self.player_scores = {} # A variable to store all player's scores for a bot session. self.game_player_scores = {} # A variable to store temporary game player's scores. + self.categories = { - "general": "Test your general knowledge" - # "retro": "Questions related to retro gaming." + "general": "Test your general knowledge.", + "retro": "Questions related to retro gaming.", + "math": "General questions about mathematics ranging from grade 8 to grade 12.", + "science": "Put your understanding of science to the test!", } + @commands.command() + async def test(self, ctx: commands.Context) -> None: + embed = discord.Embed( + title="yeet", + description="yeet", + ) + + print("yeet") + embed.set_image(url="") + + await ctx.send(embed=embed) + @staticmethod def load_questions() -> dict: """Load the questions from the JSON file.""" p = Path("bot", "resources", "evergreen", "trivia_quiz.json") + with p.open(encoding="utf8") as json_data: questions = json.load(json_data) return questions @commands.group(name="quiz", aliases=["trivia"], invoke_without_command=True) - async def quiz_game(self, ctx: commands.Context, category: str = None) -> None: + async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! Questions for the quiz can be selected from the following categories: - - general : Test your general knowledge. (default) + - general: Test your general knowledge. (default) + - retro: Questions related to retro gaming. + - math: General questions about mathematics ranging from grade 8 to grade 12. + - science: Put your understanding of science to the test! + (More to come!) """ + if ctx.channel.id not in self.game_status: self.game_status[ctx.channel.id] = False @@ -61,11 +85,13 @@ class TriviaQuiz(commands.Cog): # Stop game if running. if self.game_status[ctx.channel.id] is True: - return await ctx.send( - f"Game is already running..." + await ctx.send( + "Game is already running..." f"do `{self.bot.command_prefix}quiz stop`" ) + return + # Send embed showing available categories if inputted category is invalid. if category is None: category = random.choice(list(self.categories)) @@ -76,6 +102,30 @@ class TriviaQuiz(commands.Cog): await ctx.send(embed=embed) return + topic = self.questions[category] + topic_length = len(topic) + + if questions: + if questions > topic_length: + await ctx.send( + embed=self.make_error_embed( + f"This category only has {topic_length} questions. " + "Please input a lower value!" + ) + ) + return + + elif questions < 1: + await ctx.send( + embed=self.make_error_embed( + "Please do at least one question." + ) + ) + return + + else: + self.question_limit = questions - 1 + # Start game if not running. if self.game_status[ctx.channel.id] is False: self.game_owners[ctx.channel.id] = ctx.author @@ -85,16 +135,17 @@ class TriviaQuiz(commands.Cog): await ctx.send(embed=start_embed) # send an embed with the rules await asyncio.sleep(1) - topic = self.questions[category] - done_question = [] hint_no = 0 - answer = None + answers = None + while self.game_status[ctx.channel.id]: # Exit quiz if number of questions for a round are already sent. if len(done_question) > self.question_limit and hint_no == 0: await ctx.send("The round has ended.") - await self.declare_winner(ctx.channel, self.game_player_scores[ctx.channel.id]) + await self.declare_winner( + ctx.channel, self.game_player_scores[ctx.channel.id] + ) self.game_status[ctx.channel.id] = False del self.game_owners[ctx.channel.id] @@ -111,23 +162,39 @@ class TriviaQuiz(commands.Cog): done_question.append(question_dict["id"]) break - q = question_dict["question"] - answer = question_dict["answer"] + if "dynamic_id" not in question_dict: + q = question_dict["question"] + answers = question_dict["answer"].split(", ") + else: + q, answers = DYNAMIC_QUESTIONS_FORMAT_FUNCS[ + question_dict["dynamic_id"] + ]( + question_dict["question"], + question_dict["answer"], + ) + + answers = [answers] + + embed = discord.Embed( + colour=discord.Colour.gold(), + title=f"Question #{len(done_question)}", + description=q, + ) + + if "img_url" in question_dict: + embed.set_image(url=question_dict["img_url"]) - embed = discord.Embed(colour=discord.Colour.gold()) - embed.title = f"Question #{len(done_question)}" - embed.description = q await ctx.send(embed=embed) # Send question embed. # A function to check whether user input is the correct answer(close to the right answer) def check(m: discord.Message) -> bool: - return ( - m.channel == ctx.channel - and fuzz.ratio(answer.lower(), m.content.lower()) > 85 + return m.channel == ctx.channel and any( + fuzz.ratio(answer.lower(), m.content.lower()) > VARIATION_TOLERANCE + for answer in answers ) try: - msg = await self.bot.wait_for('message', check=check, timeout=10) + msg = await self.bot.wait_for("message", check=check, timeout=10) except asyncio.TimeoutError: # In case of TimeoutError and the game has been stopped, then do nothing. if self.game_status[ctx.channel.id] is False: @@ -136,9 +203,14 @@ class TriviaQuiz(commands.Cog): # if number of hints sent or time alerts sent is less than 2, then send one. if hint_no < 2: hint_no += 1 + if "hints" in question_dict: hints = question_dict["hints"] - await ctx.send(f"**Hint #{hint_no+1}\n**{hints[hint_no]}") + + await ctx.send( + f"**Hint #{hint_no}\n**" + f"{hints[hint_no - 1]}" + ) else: await ctx.send(f"{30 - hint_no * 10}s left!") @@ -151,19 +223,22 @@ class TriviaQuiz(commands.Cog): response = random.choice(WRONG_ANS_RESPONSE) await ctx.send(response) - await self.send_answer(ctx.channel, question_dict) + await self.send_answer(ctx.channel, answers, question_dict) await asyncio.sleep(1) hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. - await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) + await self.send_score( + ctx.channel, self.game_player_scores[ctx.channel.id] + ) + await asyncio.sleep(2) else: if self.game_status[ctx.channel.id] is False: break # Reduce points by 25 for every hint/time alert that has been sent. - points = 100 - 25*hint_no + points = 100 - 25 * hint_no if msg.author in self.game_player_scores[ctx.channel.id]: self.game_player_scores[ctx.channel.id][msg.author] += points else: @@ -177,24 +252,49 @@ class TriviaQuiz(commands.Cog): hint_no = 0 - await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") - await self.send_answer(ctx.channel, question_dict) - await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) + await ctx.send( + f"{msg.author.mention} got the correct answer :tada: {points} points!" + ) + + await self.send_answer(ctx.channel, answers, question_dict) + await self.send_score( + ctx.channel, self.game_player_scores[ctx.channel.id] + ) + await asyncio.sleep(2) - @staticmethod - def make_start_embed(category: str) -> discord.Embed: + def make_start_embed(self, category: str) -> discord.Embed: """Generate a starting/introduction embed for the quiz.""" - start_embed = discord.Embed(colour=discord.Colour.red()) - start_embed.title = "Quiz game Starting!!" - start_embed.description = "Each game consists of 5 questions.\n" - start_embed.description += "**Rules :**\nNo cheating and have fun!" - start_embed.description += f"\n **Category** : {category}" + start_embed = discord.Embed( + colour=discord.Colour.red(), + title="Quiz game starting!", + description=( + f"Each game consists of {self.question_limit + 1} questions.\n" + "**Rules: **No cheating and have fun!\n" + f"**Category**: {category}" + ), + ) + start_embed.set_footer( - text="Points for each question reduces by 25 after 10s or after a hint. Total time is 30s per question" + text=( + "Points for each question reduces by 25 after 10s or after a hint." + "Total time is 30s per question" + ) ) + return start_embed + @staticmethod + def make_error_embed(desc: str) -> discord.Embed: + """Generate an error embed with the given description.""" + error_embed = discord.Embed( + colour=discord.Colour.red(), + title=random.choice(NEGATIVE_REPLIES), + description=desc, + ) + + return error_embed + @quiz_game.command(name="stop") async def stop_quiz(self, ctx: commands.Context) -> None: """ @@ -204,18 +304,23 @@ class TriviaQuiz(commands.Cog): """ if self.game_status[ctx.channel.id] is True: # Check if the author is the game starter or a moderator. - if ( - ctx.author == self.game_owners[ctx.channel.id] - or any(Roles.moderator == role.id for role in ctx.author.roles) + if ctx.author == self.game_owners[ctx.channel.id] or any( + Roles.moderator == role.id for role in ctx.author.roles ): + await ctx.send("Quiz stopped.") - await self.declare_winner(ctx.channel, self.game_player_scores[ctx.channel.id]) + await self.declare_winner( + ctx.channel, self.game_player_scores[ctx.channel.id] + ) self.game_status[ctx.channel.id] = False del self.game_owners[ctx.channel.id] self.game_player_scores[ctx.channel.id] = {} + else: - await ctx.send(f"{ctx.author.mention}, you are not authorised to stop this game :ghost:!") + await ctx.send( + f"{ctx.author.mention}, you are not authorised to stop this game :ghost:!" + ) else: await ctx.send("No quiz running.") @@ -231,13 +336,15 @@ class TriviaQuiz(commands.Cog): await channel.send("No one has made it onto the leaderboard yet.") return - embed = discord.Embed(colour=discord.Colour.blue()) - embed.title = "Score Board" - embed.description = "" + embed = discord.Embed( + colour=discord.Colour.blue(), + title="Score Board", + description="", + ) sorted_dict = sorted(player_data.items(), key=lambda a: a[1], reverse=True) for item in sorted_dict: - embed.description += f"{item[0]} : {item[1]}\n" + embed.description += f"{item[0]}: {item[1]}\n" await channel.send(embed=embed) @@ -250,7 +357,6 @@ class TriviaQuiz(commands.Cog): # Check if more than 1 player has highest points. if no_of_winners > 1: - word = "You guys" winners = [] points_copy = list(player_data.values()).copy() @@ -261,36 +367,53 @@ class TriviaQuiz(commands.Cog): winners_mention = " ".join(winner.mention for winner in winners) else: - word = "You" author_index = list(player_data.values()).index(highest_points) winner = list(player_data.keys())[author_index] winners_mention = winner.mention await channel.send( f"Congratulations {winners_mention} :tada: " - f"{word} have won this quiz game with a grand total of {highest_points} points!" + f"You have won this quiz game with a grand total of {highest_points} points!" ) def category_embed(self) -> discord.Embed: """Build an embed showing all available trivia categories.""" - embed = discord.Embed(colour=discord.Colour.blue()) - embed.title = "The available question categories are:" - embed.set_footer(text="If a category is not chosen, a random one will be selected.") - embed.description = "" + embed = discord.Embed( + colour=discord.Colour.blue(), + title="The available question categories are:", + description="", + ) + + embed.set_footer( + text="If a category is not chosen, a random one will be selected." + ) for cat, description in self.categories.items(): - embed.description += f"**- {cat.capitalize()}**\n{description.capitalize()}\n" + embed.description += ( + f"**- {cat.capitalize()}**\n" + f"{description.capitalize()}\n" + ) return embed @staticmethod - async def send_answer(channel: discord.TextChannel, question_dict: dict) -> None: + async def send_answer( + channel: discord.TextChannel, + answers: List[str], + question_dict: dict, + ) -> None: + """Send the correct answer of a question to the game channel.""" - answer = question_dict["answer"] - info = question_dict["info"] - embed = discord.Embed(color=discord.Colour.red()) - embed.title = f"The correct answer is **{answer}**\n" - embed.description = "" + if "info" in question_dict: + info = question_dict["info"] + else: + info = "" + + embed = discord.Embed( + color=discord.Colour.red(), + title=f"The correct answer is/are **{', '.join(answers)}**\n", + description="", + ) if info != "": embed.description += f"**Information**\n{info}\n\n" -- cgit v1.2.3 From 9e6004f26d7d95537cef6e60c8ee7bf78e705a82 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 11:19:31 -0300 Subject: fix NameError, add some forgotten imports --- bot/exts/evergreen/trivia_quiz.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 1139e3e1..2158ac9c 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -9,11 +9,12 @@ from discord.ext import commands from fuzzywuzzy import fuzz from bot.constants import Roles +from bot.constants import NEGATIVE_REPLIES +from typing import Optional, List, Tuple logger = logging.getLogger(__name__) - WRONG_ANS_RESPONSE = [ "No one answered correctly!", "Better luck next time" -- cgit v1.2.3 From 0913bf2ba9a66bb7d6dc7c729d689b98dfdcb520 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 14:06:34 -0300 Subject: Add dynamically generated science questions --- bot/resources/evergreen/trivia_quiz.json | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index b20b953f..ce33e8c9 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -435,7 +435,7 @@ { "id": 228, "question": "1/100th of a second is also termed as what?", - "answer": "jiffy" + "answer": "a jiffy, jiffy" }, { "id": 229, @@ -487,18 +487,22 @@ }, { "id": 308, - "question": "DYNAMIC QUESTION, TO BE DETERMINED", - "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + "dynamic_id": 301, + "question": "What is the {} planet of our Solar System?", + "answer": "{}" }, { "id": 309, - "question": "DYNAMIC QUESTION, TO BE DETERMINED", - "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + "dynamic_id": 302, + "question": "In the biological taxonomic hierarchy, what is placed directly above {}?", + "answer": "{}" }, { "id": 310, - "question": "DYNAMIC QUESTION, TO BE DETERMINED", - "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + "dynamic_id": 303, + "question": "How does one describe the unit {} in SI base units?\n**IMPORTANT:** use * for multiplication, ^ for exponentiation, and place your base units in this order: m - kg - s - A", + "img_url": "https://i.imgur.com/NRzU6tf.png", + "answer": "{}" }, { "id": 311, @@ -533,7 +537,7 @@ { "id": 317, "question": "Which vascular tissue transports water and minerals from the roots to the rest of a plant?", - "answer": "xylem" + "answer": "the xylem, xylem" }, { "id": 318, @@ -593,7 +597,7 @@ { "id": 329, "question": "Which particle is emitted during the beta decay of a radioactive element?", - "answer": "an electron, electron" + "answer": "an electron, the electron, electron" }, { "id": 330, -- cgit v1.2.3 From c940d96a9d11ddfaaf4b599f429d559b2da60d1b Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 14:08:39 -0300 Subject: Add dynamic question formatters and its constants --- bot/exts/evergreen/trivia_quiz.py | 164 +++++++++++++++++++++++++++++++++++++- 1 file changed, 162 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 2158ac9c..d57ddc09 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -15,11 +15,171 @@ from typing import Optional, List, Tuple logger = logging.getLogger(__name__) +VARIATION_TOLERANCE = 83 + WRONG_ANS_RESPONSE = [ "No one answered correctly!", - "Better luck next time" + "Better luck next time...", +] + +N_PREFIX_STARTS_AT = 5 +N_PREFIXES = [ + "penta", "hexa", "hepta", "octa", "nona", + "deca", "hendeca", "dodeca", "trideca", "tetradeca", +] + +PLANETS = [ + ("1st", "Mercury"), + ("2nd", "Venus"), + ("3rd", "Earth"), + ("4th", "Mars"), + ("5th", "Jupiter"), + ("6th", "Saturn"), + ("7th", "Uranus"), + ("8th", "Neptune"), +] + +TAXONOMIC_HIERARCHY = [ + "species", "genus", "family", "order", + "class", "phylum", "kingdom", "domain", ] +UNITS_TO_BASE_UNITS = { + "hertz": ("(unit of frequency)", "s^-1"), + "newton": ("(unit of force)", "m*kg*s^-2"), + "pascal": ("(unit of pressure & stress)", "m^-1*kg*s^-2"), + "joule": ("(unit of energy & quantity of heat)", "m^2*kg*s^-2"), + "watt": ("(unit of power)", "m^2*kg*s^-3"), + "coulomb": ("(unit of electric charge & quantity of electricity)", "s*A"), + "volt": ("(unit of voltage & electromotive force)", "m^2*kg*s^-3*A^-1"), + "farad": ("(unit of capacitance)", "m^-2*kg^-1*s^4*A^2"), + "ohm": ("(unit of electric resistance)", "m^2*kg*s^-3*A^-2"), + "weber": ("(unit of magnetic flux)", "m^2*kg*s^-2*A^-1"), + "tesla": ("(unit of magnetic flux density)", "kg*s^-2*A^-1"), +} + + +def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: + x, y = random.randint(2, 5), random.randint(2, 5) + answer = a_format.format(x, y) + + nums = [i for i in range(1, 6)] + coeffs = [nums.pop(random.randint(0, len(nums) - 1)) for _ in range(4)] + + question = q_format.format( + coeffs[0], + coeffs[1], + ( + coeffs[0] * x + coeffs[1] * y + ), + coeffs[2], + coeffs[3], + ( + coeffs[2] * x + coeffs[3] * y + ), + ) + + return question, answer + + +def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: + quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) + ans = random.randint(0, 9) # max 9 because min mod 10 + a = quotient * m + ans - b + + question = q_format.format(a, b, m) + answer = a_format.format(ans) + + return question, answer + + +def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: + n = random.randint(0, len(N_PREFIXES) - 1) + + question = q_format.format(N_PREFIXES[n]) + answer = a_format.format((n + N_PREFIX_STARTS_AT) * 2) + + return question, answer + + +def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: + ans_coeff = random.randint(3, 10) + + question = q_format.format(ans_coeff ** 2) + answer = a_format.format(ans_coeff) + + return question, answer + + +def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: + a = random.randint(15, 20) + b = random.randint(10, a) + oper = random.choice( + ( + ("+", lambda x, y: x + y), + ("-", lambda x, y: x - y), + ("*", lambda x, y: x * y), + ) + ) + + if oper[0] == "*": + a -= 5 + b -= 5 + + question = q_format.format( + bin(a)[2:], + oper[0], + bin(b)[2:], + ) + answer = a_format.format( + bin(oper[1](a, b))[2:] + ) + + return question, answer + + +def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: + planet = random.choice(PLANETS) + + question = q_format.format(planet[0]) + answer = a_format.format(planet[1]) + + return question, answer + + +def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: + level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) + + question = q_format.format(TAXONOMIC_HIERARCHY[level]) + answer = a_format.format(TAXONOMIC_HIERARCHY[level + 1]) + + return question, answer + + +def base_units_convert(q_format: str, a_format: str) -> Tuple[str, str]: + unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) + + question = q_format.format( + unit + " " + UNITS_TO_BASE_UNITS[unit][0] + ) + answer = a_format.format( + UNITS_TO_BASE_UNITS[unit][1] + ) + + return question, answer + + +DYNAMIC_QUESTIONS_FORMAT_FUNCS = { + 201: linear_system, + 202: mod_arith, + 203: ngonal_prism, + 204: imag_sqrt, + 205: binary_calc, + 301: solar_system, + 302: taxonomic_rank, + 303: base_units_convert, +} + class TriviaQuiz(commands.Cog): """A cog for all quiz commands.""" @@ -412,7 +572,7 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=discord.Colour.red(), - title=f"The correct answer is/are **{', '.join(answers)}**\n", + title=f"The correct answer is/are **`{', '.join(answers)}`**\n", description="", ) -- cgit v1.2.3 From b80588d0c74f78f3d78b0580ba52d0ec8d23aeec Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 14:27:10 -0300 Subject: Fix lint failures: adding docstrings, removing whitespace --- bot/exts/evergreen/trivia_quiz.py | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index d57ddc09..7bbb8a15 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -8,10 +8,10 @@ import discord from discord.ext import commands from fuzzywuzzy import fuzz -from bot.constants import Roles -from bot.constants import NEGATIVE_REPLIES +from typing import List, Optional, Tuple -from typing import Optional, List, Tuple +from bot.constants import NEGATIVE_REPLIES +from bot.constants import Roles logger = logging.getLogger(__name__) @@ -60,6 +60,7 @@ UNITS_TO_BASE_UNITS = { def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a system of linear equations with two unknowns.""" x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) @@ -83,6 +84,7 @@ def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: + """Generate a basic modular arithmetic question.""" quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) ans = random.randint(0, 9) # max 9 because min mod 10 a = quotient * m + ans - b @@ -94,6 +96,7 @@ def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: + """Generate a question regarding vertices on n-gonal prisms.""" n = random.randint(0, len(N_PREFIXES) - 1) question = q_format.format(N_PREFIXES[n]) @@ -103,6 +106,7 @@ def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a negative square root question.""" ans_coeff = random.randint(3, 10) question = q_format.format(ans_coeff ** 2) @@ -112,6 +116,7 @@ def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a binary calculation question.""" a = random.randint(15, 20) b = random.randint(10, a) oper = random.choice( @@ -139,6 +144,7 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a question on the planets of the Solar System.""" planet = random.choice(PLANETS) question = q_format.format(planet[0]) @@ -148,6 +154,7 @@ def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a question on taxonomic classification.""" level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) question = q_format.format(TAXONOMIC_HIERARCHY[level]) @@ -157,6 +164,7 @@ def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: def base_units_convert(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a SI base units conversion question.""" unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) question = q_format.format( @@ -203,18 +211,6 @@ class TriviaQuiz(commands.Cog): "science": "Put your understanding of science to the test!", } - @commands.command() - async def test(self, ctx: commands.Context) -> None: - embed = discord.Embed( - title="yeet", - description="yeet", - ) - - print("yeet") - embed.set_image(url="") - - await ctx.send(embed=embed) - @staticmethod def load_questions() -> dict: """Load the questions from the JSON file.""" @@ -237,7 +233,6 @@ class TriviaQuiz(commands.Cog): (More to come!) """ - if ctx.channel.id not in self.game_status: self.game_status[ctx.channel.id] = False @@ -563,7 +558,6 @@ class TriviaQuiz(commands.Cog): answers: List[str], question_dict: dict, ) -> None: - """Send the correct answer of a question to the game channel.""" if "info" in question_dict: info = question_dict["info"] -- cgit v1.2.3 From c742604f310097339e130688232862f27052cc3b Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 14:28:31 -0300 Subject: Fix wrong import order lint failure --- bot/exts/evergreen/trivia_quiz.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 7bbb8a15..d024f856 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -3,13 +3,12 @@ import json import logging import random from pathlib import Path +from typing import List, Optional, Tuple import discord from discord.ext import commands from fuzzywuzzy import fuzz -from typing import List, Optional, Tuple - from bot.constants import NEGATIVE_REPLIES from bot.constants import Roles -- cgit v1.2.3 From d5f01153aac59cfbc043d894ebf6e1173c1efb48 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Fri, 7 May 2021 13:41:23 -0400 Subject: chore: Reformat the code to follow the style guild --- bot/__init__.py | 2 +- bot/exts/christmas/advent_of_code/_cog.py | 18 ++++++++++------ bot/exts/christmas/hanukkah_embed.py | 34 ++++++++++++++++++++----------- bot/exts/evergreen/cheatsheet.py | 20 ++++++++++-------- bot/exts/evergreen/connect_four.py | 6 ++++-- bot/exts/evergreen/game.py | 15 +++++++------- bot/exts/evergreen/pythonfacts.py | 14 ++++++++----- bot/exts/evergreen/snakes/_snakes_cog.py | 26 ++++++++++++++++------- bot/exts/evergreen/snakes/_utils.py | 7 +++++-- 9 files changed, 92 insertions(+), 50 deletions(-) (limited to 'bot') diff --git a/bot/__init__.py b/bot/__init__.py index 669f9f5d..e5ed9d92 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -69,7 +69,7 @@ logging.basicConfig( level=logging.TRACE if Client.debug else logging.DEBUG, handlers=[console_handler, file_handler], ) -logging.getLogger().info('Logging initialization complete') +logging.getLogger().info("Logging initialization complete") # On Windows, the selector event loop is required for aiodns. diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index da1cf28d..863d2a21 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -72,11 +72,15 @@ class AdventOfCode(commands.Cog): if role not in ctx.author.roles: await ctx.author.add_roles(role) - await ctx.send("Okay! You have been __subscribed__ to notifications about new Advent of Code tasks. " - f"You can run `{unsubscribe_command}` to disable them again for you.") + await ctx.send( + "Okay! You have been __subscribed__ to notifications about new Advent of Code tasks. " + f"You can run `{unsubscribe_command}` to disable them again for you." + ) else: - await ctx.send("Hey, you already are receiving notifications about new Advent of Code tasks. " - f"If you don't want them any more, run `{unsubscribe_command}` instead.") + await ctx.send( + "Hey, you already are receiving notifications about new Advent of Code tasks. " + f"If you don't want them any more, run `{unsubscribe_command}` instead." + ) @in_month(Month.DECEMBER) @adventofcode_group.command(name="unsubscribe", aliases=("unsub",), brief="Notifications for new days") @@ -110,8 +114,10 @@ class AdventOfCode(commands.Cog): else: delta_str = f"{delta.days} days" - await ctx.send(f"The Advent of Code event is not currently running. " - f"The next event will start in {delta_str}.") + await ctx.send( + f"The Advent of Code event is not currently running. " + f"The next event will start in {delta_str}." + ) return tomorrow, time_left = _helpers.time_left_to_est_midnight() diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index 214044b8..af5cfccf 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -17,8 +17,10 @@ class HanukkahEmbed(commands.Cog): def __init__(self, bot: Bot): self.bot = bot - self.url = ("https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&" - "year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3448439&m=50&s=on") + self.url = ( + "https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&" + "year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3448439&m=50&s=on" + ) self.hanukkah_days = [] self.hanukkah_months = [] self.hanukkah_years = [] @@ -64,13 +66,17 @@ class HanukkahEmbed(commands.Cog): hours = now.hour + 4 # using only hours hanukkah_start_hour = 18 if hours < hanukkah_start_hour: - embed.description = (f"Hanukkah hasnt started yet, " - f"it will start in about {hanukkah_start_hour - hours} hour/s.") + embed.description = ( + f"Hanukkah hasnt started yet, " + f"it will start in about {hanukkah_start_hour - hours} hour/s." + ) await ctx.send(embed=embed) return elif hours > hanukkah_start_hour: - embed.description = (f"It is the starting day of Hanukkah ! " - f"Its been {hours - hanukkah_start_hour} hours hanukkah started !") + embed.description = ( + f"It is the starting day of Hanukkah ! " + f"Its been {hours - hanukkah_start_hour} hours hanukkah started !" + ) await ctx.send(embed=embed) return festival_day = self.hanukkah_days.index(day) @@ -87,18 +93,22 @@ class HanukkahEmbed(commands.Cog): message = "" for _ in range(1, festival_day + 1): message += ":menorah:" - embed.description = f"It is the {festival_day}{suffix} day of Hanukkah ! \n {message}" + embed.description = f"It is the {festival_day}{suffix} day of Hanukkah!\n{message}" await ctx.send(embed=embed) else: if today < hanukkah_start: festival_starting_month = hanukkah_start.strftime("%B") - embed.description = (f"Hanukkah has not started yet. " - f"Hanukkah will start at sundown on {hanukkah_start_day}th " - f"of {festival_starting_month}.") + embed.description = ( + f"Hanukkah has not started yet. " + f"Hanukkah will start at sundown on {hanukkah_start_day}th " + f"of {festival_starting_month}." + ) else: festival_end_month = hanukkah_end.strftime("%B") - embed.description = (f"Looks like you missed Hanukkah !" - f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}.") + embed.description = ( + f"Looks like you missed Hanukkah !" + f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}." + ) await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/cheatsheet.py b/bot/exts/evergreen/cheatsheet.py index 86fae167..7ee34b1d 100644 --- a/bot/exts/evergreen/cheatsheet.py +++ b/bot/exts/evergreen/cheatsheet.py @@ -12,7 +12,7 @@ from bot.bot import Bot from bot.constants import Categories, Channels, Colours, ERROR_REPLIES from bot.utils.decorators import whitelist_override -ERROR_MESSAGE = f""" +ERROR_MESSAGE = f"""\ Unknown cheat sheet. Please try to reformulate your query. **Examples**: @@ -61,14 +61,18 @@ class CheatSheet(commands.Cog): body_space = min(1986 - len(url), 1000) if len(body_text) > body_space: - description = (f"**Result Of cht.sh**\n" - f"```python\n{body_text[:body_space]}\n" - f"... (truncated - too many lines)```\n" - f"Full results: {url} ") + description = ( + f"**Result Of cht.sh**\n" + f"```python\n{body_text[:body_space]}\n" + f"... (truncated - too many lines)```\n" + f"Full results: {url} " + ) else: - description = (f"**Result Of cht.sh**\n" - f"```python\n{body_text}```\n" - f"{url}") + description = ( + f"**Result Of cht.sh**\n" + f"```python\n{body_text}```\n" + f"{url}" + ) return False, description @commands.command( diff --git a/bot/exts/evergreen/connect_four.py b/bot/exts/evergreen/connect_four.py index 929a15d8..dc365a70 100644 --- a/bot/exts/evergreen/connect_four.py +++ b/bot/exts/evergreen/connect_four.py @@ -277,8 +277,10 @@ class ConnectFour(commands.Cog): return False if not self.min_board_size <= board_size <= self.max_board_size: - await ctx.send(f"{board_size} is not a valid board size. A valid board size is " - f"between `{self.min_board_size}` and `{self.max_board_size}`.") + await ctx.send( + f"{board_size} is not a valid board size. A valid board size is " + f"between `{self.min_board_size}` and `{self.max_board_size}`." + ) return False return True diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 4da33259..6f01d81c 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -335,13 +335,14 @@ class Games(Cog): return await ctx.send("Successfully refreshed genres.") - async def get_games_list(self, - amount: int, - genre: Optional[str] = None, - sort: Optional[str] = None, - additional_body: str = "", - offset: int = 0 - ) -> List[Dict[str, Any]]: + async def get_games_list( + self, + amount: int, + genre: Optional[str] = None, + sort: Optional[str] = None, + additional_body: str = "", + offset: int = 0 + ) -> List[Dict[str, Any]]: """ Get list of games from IGDB API by parameters that is provided. diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index c0086c20..e162c9bd 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -18,11 +18,15 @@ class PythonFacts(commands.Cog): @commands.command(name="pythonfact", aliases=["pyfact"]) async def get_python_fact(self, ctx: commands.Context) -> None: """Sends a Random fun fact about Python.""" - embed = discord.Embed(title="Python Facts", - description=next(FACTS), - colour=next(COLORS)) - embed.add_field(name="Suggestions", - value="Suggest more facts [here!](https://github.com/python-discord/meta/discussions/93)") + embed = discord.Embed( + title="Python Facts", + description=next(FACTS), + colour=next(COLORS) + ) + embed.add_field( + name="Suggestions", + value="Suggest more facts [here!](https://github.com/python-discord/meta/discussions/93)" + ) await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index 62795aef..6278c883 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -497,9 +497,11 @@ class Snakes(Cog): for i in range(0, 10): page_guess_list.append(f"{HOLE_EMOJI} {HOLE_EMOJI} {HOLE_EMOJI} {HOLE_EMOJI}") page_result_list.append(f"{CROSS_EMOJI} {CROSS_EMOJI} {CROSS_EMOJI} {CROSS_EMOJI}") - board.append(f"`{i+1:02d}` " - f"{page_guess_list[i]} - " - f"{page_result_list[i]}") + board.append( + f"`{i+1:02d}` " + f"{page_guess_list[i]} - " + f"{page_result_list[i]}" + ) board.append(EMPTY_UNICODE) antidote_embed.add_field(name="10 guesses remaining", value="\n".join(board)) board_id = await ctx.send(embed=antidote_embed) # Display board @@ -667,8 +669,14 @@ class Snakes(Cog): ) emoji = "https://emojipedia-us.s3.amazonaws.com/thumbs/60/google/3/snake_1f40d.png" - image = next((url for url in data["image_list"] - if url.endswith(self.valid_image_extensions)), emoji) + + _iter = ( + url + for url in data["image_list"] + if url.endswith(self.valid_image_extensions) + ) + image = next(_iter, emoji) + embed.set_image(url=image) await ctx.send(embed=embed) @@ -693,8 +701,12 @@ class Snakes(Cog): data = await self._get_snek(snake) - image = next((url for url in data["image_list"] - if url.endswith(self.valid_image_extensions)), None) + _iter = ( + url + for url in data["image_list"] + if url.endswith(self.valid_image_extensions) + ) + image = next(_iter, None) embed = Embed( title="Which of the following is the snake in the image?", diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index d58ee279..998c13a9 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -191,8 +191,11 @@ class PerlinNoiseFactory(object): def get_plain_noise(self, *point) -> float: """Get plain noise for a single point, without taking into account either octaves or tiling.""" if len(point) != self.dimension: - raise ValueError("Expected {0} values, got {1}".format( - self.dimension, len(point))) + raise ValueError( + "Expected {0} values, got {1}".format( + self.dimension, len(point) + ) + ) # Build a list of the (min, max) bounds in each dimension grid_coords = [] -- cgit v1.2.3 From 0017b76e914e4963a8556ac768e2b4a176111636 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Fri, 7 May 2021 13:45:57 -0400 Subject: chore: Apply anand's suggested changes --- bot/exts/pride/pride_facts.py | 2 +- bot/exts/valentines/be_my_valentine.py | 5 ++--- bot/exts/valentines/lovecalculator.py | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) (limited to 'bot') diff --git a/bot/exts/pride/pride_facts.py b/bot/exts/pride/pride_facts.py index b2daaab7..6d06cf64 100644 --- a/bot/exts/pride/pride_facts.py +++ b/bot/exts/pride/pride_facts.py @@ -101,5 +101,5 @@ class PrideFacts(commands.Cog): def setup(bot: Bot) -> None: - """Cog loader for pride facts.""" + """Load the Pride Facts Cog.""" bot.add_cog(PrideFacts(bot)) diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index cf6099d2..1ce92203 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -6,7 +6,6 @@ from typing import Tuple import discord from discord.ext import commands -from discord.ext.commands.cooldowns import BucketType from bot.bot import Bot from bot.constants import Channels, Colours, Lovefest, Month @@ -69,7 +68,7 @@ class BeMyValentine(commands.Cog): await user.remove_roles(role) await ctx.send("The lovefest role has been successfully removed!") - @commands.cooldown(1, 1800, BucketType.user) + @commands.cooldown(1, 1800, commands.BucketType.user) @commands.group(name="bemyvalentine", invoke_without_command=True) async def send_valentine( self, ctx: commands.Context, user: discord.Member, *, valentine_type: str = None @@ -108,7 +107,7 @@ class BeMyValentine(commands.Cog): ) await channel.send(user.mention, embed=embed) - @commands.cooldown(1, 1800, BucketType.user) + @commands.cooldown(1, 1800, commands.BucketType.user) @send_valentine.command(name="secret") async def anonymous( self, ctx: commands.Context, user: discord.Member, *, valentine_type: str = None diff --git a/bot/exts/valentines/lovecalculator.py b/bot/exts/valentines/lovecalculator.py index 9096d994..8a4c71eb 100644 --- a/bot/exts/valentines/lovecalculator.py +++ b/bot/exts/valentines/lovecalculator.py @@ -61,7 +61,7 @@ class LoveCalculator(Cog): # Make sure user didn't provide something silly such as 10 spaces if not (who and whom): - raise BadArgument("Arguments be non-empty strings.") + raise BadArgument("Arguments must be non-empty strings.") # Hash inputs to guarantee consistent results (hashing algorithm choice arbitrary) # -- cgit v1.2.3 From ae3ecb3ac46d90ebab1cb556fdc357848f45abb5 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Fri, 7 May 2021 13:47:43 -0400 Subject: chore: Simplify the if statement Co-authored-by: Anand Krishna <40204976+anand2312@users.noreply.github.com> --- bot/exts/valentines/be_my_valentine.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index 1ce92203..b9cf6738 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -51,7 +51,7 @@ class BeMyValentine(commands.Cog): """Adds the lovefest role.""" user = ctx.author role = ctx.guild.get_role(Lovefest.role_id) - if Lovefest.role_id not in [role.id for role in ctx.message.author.roles]: + if role not in ctx.author.roles: await user.add_roles(role) await ctx.send("The Lovefest role has been added !") else: -- cgit v1.2.3 From 92dd10e62dbea4cbed9d12c239ca9f666f69f90a Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 17:51:25 -0300 Subject: fixed weird 8-space indents on lines 556-558 --- bot/exts/evergreen/trivia_quiz.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index d024f856..5553898d 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -553,9 +553,9 @@ class TriviaQuiz(commands.Cog): @staticmethod async def send_answer( - channel: discord.TextChannel, - answers: List[str], - question_dict: dict, + channel: discord.TextChannel, + answers: List[str], + question_dict: dict, ) -> None: """Send the correct answer of a question to the game channel.""" if "info" in question_dict: -- cgit v1.2.3 From 1854cd45dc4b79bed492a95bd00bcadf8ff116af Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 14:00:08 -0400 Subject: use random.sample for more concise expression on line 66 Co-authored-by: Anand Krishna <40204976+anand2312@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 5553898d..620a4377 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -63,8 +63,7 @@ def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) - nums = [i for i in range(1, 6)] - coeffs = [nums.pop(random.randint(0, len(nums) - 1)) for _ in range(4)] + coeffs = random.sample(range(1, 6), 4) question = q_format.format( coeffs[0], -- cgit v1.2.3 From 961e3f788ce4d99782418ec9bc4d33998af42124 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 16:31:32 -0400 Subject: use dict.get for retrieving a default value instead of a condition Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 620a4377..6f39d9f2 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -557,10 +557,7 @@ class TriviaQuiz(commands.Cog): question_dict: dict, ) -> None: """Send the correct answer of a question to the game channel.""" - if "info" in question_dict: - info = question_dict["info"] - else: - info = "" + info = question_dict.get("info", "") embed = discord.Embed( color=discord.Colour.red(), -- cgit v1.2.3 From c57a8557f0f52ab35c9ef79c6894bad04f73c8d2 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:36:27 -0300 Subject: use `operator` module instead of lambda functions --- bot/exts/evergreen/trivia_quiz.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 6f39d9f2..10237be9 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -2,6 +2,7 @@ import asyncio import json import logging import random +import operator from pathlib import Path from typing import List, Optional, Tuple @@ -119,9 +120,9 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: b = random.randint(10, a) oper = random.choice( ( - ("+", lambda x, y: x + y), - ("-", lambda x, y: x - y), - ("*", lambda x, y: x * y), + ("+", operator.add), + ("-", operator.sub), + ("*", operator.mul), ) ) -- cgit v1.2.3 From bfc7c4335a4e7156f877607b62491b7aaf2faa58 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:37:42 -0300 Subject: lint failure fix, imported in alphabetical order --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 10237be9..7a498ebd 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -1,8 +1,8 @@ import asyncio import json import logging -import random import operator +import random from pathlib import Path from typing import List, Optional, Tuple -- cgit v1.2.3 From 66480996e0a227506c01260e8899ea4256db6eb9 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:41:34 -0300 Subject: use binary formatting instead of `bin()` in function --- bot/resources/evergreen/trivia_quiz.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index ce33e8c9..79e79d00 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -423,8 +423,8 @@ { "id": 226, "dynamic_id": 205, - "question": "BASE TWO QUESTION: Calculate {} {} {}", - "answer": "{}" + "question": "BASE TWO QUESTION: Calculate {:b} {} {:b}", + "answer": "{:b}" }, { "id": 227, -- cgit v1.2.3 From 8b0eb4aa07fbc9c20f7748888d0db00f2264b774 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:43:33 -0300 Subject: delete `bin()`s --- bot/exts/evergreen/trivia_quiz.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 7a498ebd..03aadd19 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -131,12 +131,12 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: b -= 5 question = q_format.format( - bin(a)[2:], + a, oper[0], - bin(b)[2:], + b, ) answer = a_format.format( - bin(oper[1](a, b))[2:] + oper[1](a, b) ) return question, answer -- cgit v1.2.3 From f8e5ec95028f8a73cf0e9d96356696a047001c41 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 16:45:30 -0400 Subject: add space at the end of string on line 435 Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 03aadd19..1e1c973c 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -432,7 +432,7 @@ class TriviaQuiz(commands.Cog): start_embed.set_footer( text=( - "Points for each question reduces by 25 after 10s or after a hint." + "Points for each question reduces by 25 after 10s or after a hint. " "Total time is 30s per question" ) ) -- cgit v1.2.3 From 9d5ea922a5a9d045b15610a66ebc07cd5b4424b1 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 16:47:30 -0400 Subject: remove redundant `description` kwarg pass Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 1 - 1 file changed, 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 1e1c973c..d3def4f2 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -563,7 +563,6 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=discord.Colour.red(), title=f"The correct answer is/are **`{', '.join(answers)}`**\n", - description="", ) if info != "": -- cgit v1.2.3 From af709306d716d2d1c19c288cec08a3fa74a20a5c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 16:48:47 -0400 Subject: use walrus so dict lookup is only performed once Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index d3def4f2..88c44971 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -336,8 +336,8 @@ class TriviaQuiz(commands.Cog): description=q, ) - if "img_url" in question_dict: - embed.set_image(url=question_dict["img_url"]) + if img_url := question_dict.get("image_url"): + embed.set_image(url=img_url) await ctx.send(embed=embed) # Send question embed. -- cgit v1.2.3 From 17aee2141770085bc66c04d948249de954359f6a Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:53:01 -0300 Subject: changed error embed color to `bot.constants.Colours.soft_red` --- bot/exts/evergreen/trivia_quiz.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 88c44971..4496082e 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -10,6 +10,7 @@ import discord from discord.ext import commands from fuzzywuzzy import fuzz +from bot.constants import Colours from bot.constants import NEGATIVE_REPLIES from bot.constants import Roles @@ -443,7 +444,7 @@ class TriviaQuiz(commands.Cog): def make_error_embed(desc: str) -> discord.Embed: """Generate an error embed with the given description.""" error_embed = discord.Embed( - colour=discord.Colour.red(), + colour=Colours.soft_red, title=random.choice(NEGATIVE_REPLIES), description=desc, ) -- cgit v1.2.3 From 84f2b8783a28e2d90d601cbab33c6c3a439040bf Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:05:01 -0300 Subject: add a space at end of string on line 245 --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 4496082e..2bd8f7d4 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -242,7 +242,7 @@ class TriviaQuiz(commands.Cog): # Stop game if running. if self.game_status[ctx.channel.id] is True: await ctx.send( - "Game is already running..." + "Game is already running... " f"do `{self.bot.command_prefix}quiz stop`" ) -- cgit v1.2.3 From 21282d531208a613083362a2e5b22aebb8c53573 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:35:58 -0300 Subject: reverted all undesired black formatting changes --- bot/exts/evergreen/trivia_quiz.py | 47 +++++++++++---------------------------- 1 file changed, 13 insertions(+), 34 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 2bd8f7d4..79cf1318 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -224,13 +224,11 @@ class TriviaQuiz(commands.Cog): async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! - Questions for the quiz can be selected from the following categories: - general: Test your general knowledge. (default) - retro: Questions related to retro gaming. - math: General questions about mathematics ranging from grade 8 to grade 12. - science: Put your understanding of science to the test! - (More to come!) """ if ctx.channel.id not in self.game_status: @@ -299,9 +297,7 @@ class TriviaQuiz(commands.Cog): # Exit quiz if number of questions for a round are already sent. if len(done_question) > self.question_limit and hint_no == 0: await ctx.send("The round has ended.") - await self.declare_winner( - ctx.channel, self.game_player_scores[ctx.channel.id] - ) + await self.declare_winner(ctx.channel, self.game_player_scores[ctx.channel.id]) self.game_status[ctx.channel.id] = False del self.game_owners[ctx.channel.id] @@ -319,12 +315,12 @@ class TriviaQuiz(commands.Cog): break if "dynamic_id" not in question_dict: - q = question_dict["question"] + question = question_dict["question"] answers = question_dict["answer"].split(", ") else: - q, answers = DYNAMIC_QUESTIONS_FORMAT_FUNCS[ - question_dict["dynamic_id"] - ]( + format_func = DYNAMIC_QUESTIONS_FORMAT_FUNCS[question_dict["dynamic_id"]] + + question, answers = format_func( question_dict["question"], question_dict["answer"], ) @@ -334,7 +330,7 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( colour=discord.Colour.gold(), title=f"Question #{len(done_question)}", - description=q, + description=question, ) if img_url := question_dict.get("image_url"): @@ -363,10 +359,7 @@ class TriviaQuiz(commands.Cog): if "hints" in question_dict: hints = question_dict["hints"] - await ctx.send( - f"**Hint #{hint_no}\n**" - f"{hints[hint_no - 1]}" - ) + await ctx.send(f"**Hint #{hint_no}\n**{hints[hint_no - 1]}") else: await ctx.send(f"{30 - hint_no * 10}s left!") @@ -384,10 +377,7 @@ class TriviaQuiz(commands.Cog): hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. - await self.send_score( - ctx.channel, self.game_player_scores[ctx.channel.id] - ) - + await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) else: if self.game_status[ctx.channel.id] is False: @@ -408,14 +398,10 @@ class TriviaQuiz(commands.Cog): hint_no = 0 - await ctx.send( - f"{msg.author.mention} got the correct answer :tada: {points} points!" - ) + await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") await self.send_answer(ctx.channel, answers, question_dict) - await self.send_score( - ctx.channel, self.game_player_scores[ctx.channel.id] - ) + await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) @@ -455,7 +441,6 @@ class TriviaQuiz(commands.Cog): async def stop_quiz(self, ctx: commands.Context) -> None: """ Stop a quiz game if its running in the channel. - Note: Only mods or the owner of the quiz can stop it. """ if self.game_status[ctx.channel.id] is True: @@ -465,18 +450,14 @@ class TriviaQuiz(commands.Cog): ): await ctx.send("Quiz stopped.") - await self.declare_winner( - ctx.channel, self.game_player_scores[ctx.channel.id] - ) + await self.declare_winner(ctx.channel, self.game_player_scores[ctx.channel.id]) self.game_status[ctx.channel.id] = False del self.game_owners[ctx.channel.id] self.game_player_scores[ctx.channel.id] = {} else: - await ctx.send( - f"{ctx.author.mention}, you are not authorised to stop this game :ghost:!" - ) + await ctx.send(f"{ctx.author.mention}, you are not authorised to stop this game :ghost:!") else: await ctx.send("No quiz running.") @@ -540,9 +521,7 @@ class TriviaQuiz(commands.Cog): description="", ) - embed.set_footer( - text="If a category is not chosen, a random one will be selected." - ) + embed.set_footer(text="If a category is not chosen, a random one will be selected.") for cat, description in self.categories.items(): embed.description += ( -- cgit v1.2.3 From 675d2a03ececa926b5e3f7c129afb3f51b2a8213 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:40:49 -0300 Subject: fix lint failure; add a newline at line 444 --- bot/exts/evergreen/trivia_quiz.py | 1 + 1 file changed, 1 insertion(+) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 79cf1318..f20a21f5 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -441,6 +441,7 @@ class TriviaQuiz(commands.Cog): async def stop_quiz(self, ctx: commands.Context) -> None: """ Stop a quiz game if its running in the channel. + Note: Only mods or the owner of the quiz can stop it. """ if self.game_status[ctx.channel.id] is True: -- cgit v1.2.3 From 2cd8c03c9d9daf410624589f8a94dfe4348c063c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:42:43 -0300 Subject: fix another linting fail regarding newlines in docstrings --- bot/exts/evergreen/trivia_quiz.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index f20a21f5..60dc2d0c 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -224,11 +224,13 @@ class TriviaQuiz(commands.Cog): async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! + Questions for the quiz can be selected from the following categories: - general: Test your general knowledge. (default) - retro: Questions related to retro gaming. - math: General questions about mathematics ranging from grade 8 to grade 12. - science: Put your understanding of science to the test! + (More to come!) """ if ctx.channel.id not in self.game_status: -- cgit v1.2.3 From 9c1dc83992cddca8aaa59d38afc55b1b8df34143 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:46:22 -0300 Subject: docstring tweaks; consistency and imperative mood --- bot/exts/evergreen/trivia_quiz.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 60dc2d0c..9d6e695f 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -61,7 +61,7 @@ UNITS_TO_BASE_UNITS = { def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a system of linear equations with two unknowns.""" + """Generate a system of linear equations with two unknowns.""" x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) @@ -106,7 +106,7 @@ def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a negative square root question.""" + """Generate a negative square root question.""" ans_coeff = random.randint(3, 10) question = q_format.format(ans_coeff ** 2) @@ -116,7 +116,7 @@ def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a binary calculation question.""" + """Generate a binary calculation question.""" a = random.randint(15, 20) b = random.randint(10, a) oper = random.choice( @@ -144,7 +144,7 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a question on the planets of the Solar System.""" + """Generate a question on the planets of the Solar System.""" planet = random.choice(PLANETS) question = q_format.format(planet[0]) @@ -154,7 +154,7 @@ def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a question on taxonomic classification.""" + """Generate a question on taxonomic classification.""" level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) question = q_format.format(TAXONOMIC_HIERARCHY[level]) @@ -164,7 +164,7 @@ def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: def base_units_convert(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a SI base units conversion question.""" + """Generate a SI base units conversion question.""" unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) question = q_format.format( @@ -556,5 +556,5 @@ class TriviaQuiz(commands.Cog): def setup(bot: commands.Bot) -> None: - """Load the cog.""" + """Load the TriviaQuiz cog.""" bot.add_cog(TriviaQuiz(bot)) -- cgit v1.2.3 From 4503a3307b989b251826f36e9370bda7471640b3 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sun, 9 May 2021 17:49:53 -0400 Subject: fix: Use str.isdecimal instead of str.isdigit --- bot/utils/__init__.py | 4 ++-- bot/utils/converters.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'bot') diff --git a/bot/utils/__init__.py b/bot/utils/__init__.py index 2fac2086..09a4dfc3 100644 --- a/bot/utils/__init__.py +++ b/bot/utils/__init__.py @@ -51,7 +51,7 @@ async def disambiguate( choices = (f"{index}: {entry}" for index, entry in enumerate(entries, start=1)) def check(message: discord.Message) -> bool: - return (message.content.isdigit() + return (message.content.isdecimal() and message.author == ctx.author and message.channel == ctx.channel) @@ -87,7 +87,7 @@ async def disambiguate( except asyncio.TimeoutError: raise BadArgument("Timed out.") - # Guaranteed to not error because of isdigit() in check + # Guaranteed to not error because of isdecimal() in check index = int(result.content) try: diff --git a/bot/utils/converters.py b/bot/utils/converters.py index 98607087..72b64848 100644 --- a/bot/utils/converters.py +++ b/bot/utils/converters.py @@ -37,7 +37,7 @@ class CoordinateConverter(commands.Converter): digit = coordinate[:-1] letter = coordinate[-1] - if not digit.isdigit(): + if not digit.isdecimal(): raise commands.BadArgument x = ord(letter) - ord("a") @@ -76,7 +76,7 @@ class DateConverter(commands.Converter): @staticmethod async def convert(ctx: commands.Context, argument: str) -> Union[int, datetime]: """Parse date (SOL or earth) into `datetime` or `int`. When invalid value, raise error.""" - if argument.isdigit(): + if argument.isdecimal(): return int(argument) try: date = datetime.strptime(argument, "%Y-%m-%d") -- cgit v1.2.3 From cb49ea232cd9d4d3c54637b386b89dd0f1b21a90 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:05:31 -0300 Subject: did some changes per the new reviews and suggestions implemented all suggested changes from vcokltfre and almost all from decorator-factory --- bot/exts/evergreen/trivia_quiz.py | 49 ++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 27 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 9d6e695f..f2dfe6a9 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -16,6 +16,8 @@ from bot.constants import Roles logger = logging.getLogger(__name__) +QAndA = Tuple[str, str] + VARIATION_TOLERANCE = 83 WRONG_ANS_RESPONSE = [ @@ -60,7 +62,7 @@ UNITS_TO_BASE_UNITS = { } -def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: +def linear_system(q_format: str, a_format: str) -> QAndA: """Generate a system of linear equations with two unknowns.""" x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) @@ -83,7 +85,7 @@ def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: +def mod_arith(q_format: str, a_format: str) -> QAndA: """Generate a basic modular arithmetic question.""" quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) ans = random.randint(0, 9) # max 9 because min mod 10 @@ -95,7 +97,7 @@ def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: +def ngonal_prism(q_format: str, a_format: str) -> QAndA: """Generate a question regarding vertices on n-gonal prisms.""" n = random.randint(0, len(N_PREFIXES) - 1) @@ -105,7 +107,7 @@ def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: +def imag_sqrt(q_format: str, a_format: str) -> QAndA: """Generate a negative square root question.""" ans_coeff = random.randint(3, 10) @@ -115,7 +117,7 @@ def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: +def binary_calc(q_format: str, a_format: str) -> QAndA: """Generate a binary calculation question.""" a = random.randint(15, 20) b = random.randint(10, a) @@ -136,14 +138,12 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: oper[0], b, ) - answer = a_format.format( - oper[1](a, b) - ) + answer = a_format.format(oper[1](a, b)) return question, answer -def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: +def solar_system(q_format: str, a_format: str) -> QAndA: """Generate a question on the planets of the Solar System.""" planet = random.choice(PLANETS) @@ -153,7 +153,7 @@ def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: +def taxonomic_rank(q_format: str, a_format: str) -> QAndA: """Generate a question on taxonomic classification.""" level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) @@ -163,7 +163,7 @@ def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def base_units_convert(q_format: str, a_format: str) -> Tuple[str, str]: +def base_units_convert(q_format: str, a_format: str) -> QAndA: """Generate a SI base units conversion question.""" unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) @@ -216,9 +216,7 @@ class TriviaQuiz(commands.Cog): """Load the questions from the JSON file.""" p = Path("bot", "resources", "evergreen", "trivia_quiz.json") - with p.open(encoding="utf8") as json_data: - questions = json.load(json_data) - return questions + return json.loads(p.read_text()) @commands.group(name="quiz", aliases=["trivia"], invoke_without_command=True) async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: @@ -274,7 +272,7 @@ class TriviaQuiz(commands.Cog): elif questions < 1: await ctx.send( embed=self.make_error_embed( - "Please do at least one question." + "You must choose to complete at least one question." ) ) return @@ -283,7 +281,7 @@ class TriviaQuiz(commands.Cog): self.question_limit = questions - 1 # Start game if not running. - if self.game_status[ctx.channel.id] is False: + if not self.game_status[ctx.channel.id]: self.game_owners[ctx.channel.id] = ctx.author self.game_status[ctx.channel.id] = True start_embed = self.make_start_embed(category) @@ -338,23 +336,21 @@ class TriviaQuiz(commands.Cog): if img_url := question_dict.get("image_url"): embed.set_image(url=img_url) - await ctx.send(embed=embed) # Send question embed. + await ctx.send(embed=embed) - # A function to check whether user input is the correct answer(close to the right answer) - def check(m: discord.Message) -> bool: + def contains_correct_answer(m: discord.Message) -> bool: return m.channel == ctx.channel and any( fuzz.ratio(answer.lower(), m.content.lower()) > VARIATION_TOLERANCE for answer in answers ) try: - msg = await self.bot.wait_for("message", check=check, timeout=10) + msg = await self.bot.wait_for("message", check=contains_correct_answer, timeout=10) except asyncio.TimeoutError: # In case of TimeoutError and the game has been stopped, then do nothing. - if self.game_status[ctx.channel.id] is False: + if not self.game_status[ctx.channel.id]: break - # if number of hints sent or time alerts sent is less than 2, then send one. if hint_no < 2: hint_no += 1 @@ -385,7 +381,6 @@ class TriviaQuiz(commands.Cog): if self.game_status[ctx.channel.id] is False: break - # Reduce points by 25 for every hint/time alert that has been sent. points = 100 - 25 * hint_no if msg.author in self.game_player_scores[ctx.channel.id]: self.game_player_scores[ctx.channel.id][msg.author] += points @@ -471,13 +466,13 @@ class TriviaQuiz(commands.Cog): @staticmethod async def send_score(channel: discord.TextChannel, player_data: dict) -> None: - """A function which sends the score.""" + """Send the score.""" if len(player_data) == 0: await channel.send("No one has made it onto the leaderboard yet.") return embed = discord.Embed( - colour=discord.Colour.blue(), + colour=Colours.blue, title="Score Board", description="", ) @@ -519,7 +514,7 @@ class TriviaQuiz(commands.Cog): def category_embed(self) -> discord.Embed: """Build an embed showing all available trivia categories.""" embed = discord.Embed( - colour=discord.Colour.blue(), + colour=Colours.blue, title="The available question categories are:", description="", ) @@ -544,7 +539,7 @@ class TriviaQuiz(commands.Cog): info = question_dict.get("info", "") embed = discord.Embed( - color=discord.Colour.red(), + color=Colours.bright_green, title=f"The correct answer is/are **`{', '.join(answers)}`**\n", ) -- cgit v1.2.3 From 1f0231d725deb44b3d1ab603448680228b1942a2 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:13:53 -0300 Subject: add gold colour --- bot/constants.py | 1 + 1 file changed, 1 insertion(+) (limited to 'bot') diff --git a/bot/constants.py b/bot/constants.py index 6cbfa8db..884cf3a8 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -151,6 +151,7 @@ class Colours: python_blue = 0x4B8BBE python_yellow = 0xFFD43B grass_green = 0x66ff00 + gold = 0xE6C200 easter_like_colours = [ (255, 247, 0), -- cgit v1.2.3 From a3cf147787058832740316df03a358e3f1039bc9 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:15:45 -0300 Subject: use gold colour from constants.py for consistency --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index f2dfe6a9..31d9dbce 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -328,7 +328,7 @@ class TriviaQuiz(commands.Cog): answers = [answers] embed = discord.Embed( - colour=discord.Colour.gold(), + colour=Colours.gold, title=f"Question #{len(done_question)}", description=question, ) -- cgit v1.2.3 From 5320a38afe1810ccb445f61e74a7facf5b0e9e5a Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:45:13 -0300 Subject: minor tweaks as suggested by vcokltfre see their five change requests for details --- bot/exts/evergreen/trivia_quiz.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 31d9dbce..51e24226 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -88,7 +88,7 @@ def linear_system(q_format: str, a_format: str) -> QAndA: def mod_arith(q_format: str, a_format: str) -> QAndA: """Generate a basic modular arithmetic question.""" quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) - ans = random.randint(0, 9) # max 9 because min mod 10 + ans = random.randint(0, 9) # max remainder is 9, since the minimum modulus is 10 a = quotient * m + ans - b question = q_format.format(a, b, m) @@ -133,11 +133,7 @@ def binary_calc(q_format: str, a_format: str) -> QAndA: a -= 5 b -= 5 - question = q_format.format( - a, - oper[0], - b, - ) + question = q_format.format(a, oper[0], b) answer = a_format.format(oper[1](a, b)) return question, answer @@ -165,7 +161,7 @@ def taxonomic_rank(q_format: str, a_format: str) -> QAndA: def base_units_convert(q_format: str, a_format: str) -> QAndA: """Generate a SI base units conversion question.""" - unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) + unit = random.choice(list(UNITS_TO_BASE_UNITS)) question = q_format.format( unit + " " + UNITS_TO_BASE_UNITS[unit][0] @@ -405,7 +401,7 @@ class TriviaQuiz(commands.Cog): def make_start_embed(self, category: str) -> discord.Embed: """Generate a starting/introduction embed for the quiz.""" start_embed = discord.Embed( - colour=discord.Colour.red(), + colour=Colours.blue, title="Quiz game starting!", description=( f"Each game consists of {self.question_limit + 1} questions.\n" @@ -538,9 +534,11 @@ class TriviaQuiz(commands.Cog): """Send the correct answer of a question to the game channel.""" info = question_dict.get("info", "") + word = "is" if len(answers) == 1 else "are" + embed = discord.Embed( color=Colours.bright_green, - title=f"The correct answer is/are **`{', '.join(answers)}`**\n", + title=f"The correct answer {word} **`{', '.join(answers)}`**\n", ) if info != "": -- cgit v1.2.3 From 7bbf7b18a5066b17475bcd2b8c1dc87417692f75 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:57:03 -0300 Subject: fixed no description embed error --- bot/exts/evergreen/trivia_quiz.py | 1 + 1 file changed, 1 insertion(+) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 51e24226..23aac5fa 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -539,6 +539,7 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=Colours.bright_green, title=f"The correct answer {word} **`{', '.join(answers)}`**\n", + description="", ) if info != "": -- cgit v1.2.3 From 2e58fca5d444e8eb8adf7eba1223daff2f5fc14c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:09:23 -0300 Subject: reduce default no of questions to 7, add actual content to "Remaining questions: " --- bot/exts/evergreen/trivia_quiz.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 23aac5fa..8d1a27ba 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -195,7 +195,7 @@ class TriviaQuiz(commands.Cog): self.game_owners = {} # A variable to store the person's ID who started the quiz game in a channel. self.questions = self.load_questions() - self.question_limit = 7 + self.question_limit = 6 self.player_scores = {} # A variable to store all player's scores for a bot session. self.game_player_scores = {} # A variable to store temporary game player's scores. @@ -366,7 +366,7 @@ class TriviaQuiz(commands.Cog): response = random.choice(WRONG_ANS_RESPONSE) await ctx.send(response) - await self.send_answer(ctx.channel, answers, question_dict) + await self.send_answer(ctx.channel, answers, question_dict, len(done_question)) await asyncio.sleep(1) hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. @@ -393,7 +393,7 @@ class TriviaQuiz(commands.Cog): await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") - await self.send_answer(ctx.channel, answers, question_dict) + await self.send_answer(ctx.channel, answers, question_dict, len(done_question)) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) @@ -530,6 +530,7 @@ class TriviaQuiz(commands.Cog): channel: discord.TextChannel, answers: List[str], question_dict: dict, + q_left: int, ) -> None: """Send the correct answer of a question to the game channel.""" info = question_dict.get("info", "") @@ -545,7 +546,7 @@ class TriviaQuiz(commands.Cog): if info != "": embed.description += f"**Information**\n{info}\n\n" - embed.description += "Let's move to the next question.\nRemaining questions: " + embed.description += f"Let's move to the next question.\nRemaining questions: {q_left}" await channel.send(embed=embed) -- cgit v1.2.3 From 119f08411eeb9ec205b4678959feb270ff76548c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:23:01 -0300 Subject: fix bug where remaining questions go up instead of down --- bot/exts/evergreen/trivia_quiz.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 8d1a27ba..5ec37b25 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -366,7 +366,7 @@ class TriviaQuiz(commands.Cog): response = random.choice(WRONG_ANS_RESPONSE) await ctx.send(response) - await self.send_answer(ctx.channel, answers, question_dict, len(done_question)) + await self.send_answer(ctx.channel, answers, question_dict, self.question_limit - len(done_question)) await asyncio.sleep(1) hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. @@ -393,7 +393,7 @@ class TriviaQuiz(commands.Cog): await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") - await self.send_answer(ctx.channel, answers, question_dict, len(done_question)) + await self.send_answer(ctx.channel, answers, question_dict, self.question_limit - len(done_question)) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) -- cgit v1.2.3 From f22cebc139e03cd965e5b1d470795126d02250fd Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:25:40 -0300 Subject: increase readability, fix lint failure --- bot/exts/evergreen/trivia_quiz.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 5ec37b25..43d786bc 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -366,7 +366,13 @@ class TriviaQuiz(commands.Cog): response = random.choice(WRONG_ANS_RESPONSE) await ctx.send(response) - await self.send_answer(ctx.channel, answers, question_dict, self.question_limit - len(done_question)) + + await self.send_answer( + ctx.channel, + answers, + question_dict, + self.question_limit - len(done_question) + ) await asyncio.sleep(1) hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. @@ -393,7 +399,12 @@ class TriviaQuiz(commands.Cog): await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") - await self.send_answer(ctx.channel, answers, question_dict, self.question_limit - len(done_question)) + await self.send_answer( + ctx.channel, + answers, + question_dict, + self.question_limit - len(done_question) + ) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) -- cgit v1.2.3 From d2e1d52c762b73e240dabdbee1004e73315a5b4e Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:31:10 -0300 Subject: forgot to increment by one, fixed --- bot/exts/evergreen/trivia_quiz.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 43d786bc..bd3b136e 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -371,7 +371,7 @@ class TriviaQuiz(commands.Cog): ctx.channel, answers, question_dict, - self.question_limit - len(done_question) + self.question_limit - len(done_question) + 1 ) await asyncio.sleep(1) @@ -403,7 +403,7 @@ class TriviaQuiz(commands.Cog): ctx.channel, answers, question_dict, - self.question_limit - len(done_question) + self.question_limit - len(done_question) + 1 ) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) -- cgit v1.2.3 From 1012c8b7421b30cf80ff26798308f9ee1586e0f7 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:50:33 -0300 Subject: final minor refinery as requested by vcokltfre --- bot/exts/evergreen/trivia_quiz.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index bd3b136e..56929fe7 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -370,8 +370,9 @@ class TriviaQuiz(commands.Cog): await self.send_answer( ctx.channel, answers, + False, question_dict, - self.question_limit - len(done_question) + 1 + self.question_limit - len(done_question) + 1, ) await asyncio.sleep(1) @@ -402,8 +403,9 @@ class TriviaQuiz(commands.Cog): await self.send_answer( ctx.channel, answers, + True, question_dict, - self.question_limit - len(done_question) + 1 + self.question_limit - len(done_question) + 1, ) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) @@ -540,6 +542,7 @@ class TriviaQuiz(commands.Cog): async def send_answer( channel: discord.TextChannel, answers: List[str], + answer_is_correct: bool, question_dict: dict, q_left: int, ) -> None: @@ -550,14 +553,20 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=Colours.bright_green, - title=f"The correct answer {word} **`{', '.join(answers)}`**\n", + title=( + "You got it! " if answer_is_correct else "" + f"The correct answer {word} **`{', '.join(answers)}`**\n" + ), description="", ) if info != "": embed.description += f"**Information**\n{info}\n\n" - embed.description += f"Let's move to the next question.\nRemaining questions: {q_left}" + embed.description += ( + "Let's move to the next question." if q_left > 0 else "" + f"\nRemaining questions: {q_left}" + ) await channel.send(embed=embed) -- cgit v1.2.3 From d7e3937d019025578b09fed0bfc59bb0e174ed84 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 08:43:40 -0400 Subject: Update bot/exts/evergreen/trivia_quiz.py Co-authored-by: Shivansh-007 --- bot/exts/evergreen/trivia_quiz.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 56929fe7..bd319910 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -72,9 +72,7 @@ def linear_system(q_format: str, a_format: str) -> QAndA: question = q_format.format( coeffs[0], coeffs[1], - ( - coeffs[0] * x + coeffs[1] * y - ), + coeffs[0] * x + coeffs[1] * y, coeffs[2], coeffs[3], ( -- cgit v1.2.3 From f8ea21fd364adb09f26b092aa4ef0cbbeeca0430 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 08:44:16 -0400 Subject: remove redundant parentheses Co-authored-by: Shivansh-007 --- bot/exts/evergreen/trivia_quiz.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index bd319910..045fedbf 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -75,9 +75,7 @@ def linear_system(q_format: str, a_format: str) -> QAndA: coeffs[0] * x + coeffs[1] * y, coeffs[2], coeffs[3], - ( - coeffs[2] * x + coeffs[3] * y - ), + coeffs[2] * x + coeffs[3] * y, ) return question, answer -- cgit v1.2.3 From 5f9242749db72912abc7c52a8e1da90ca09c6848 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 09:52:59 -0300 Subject: apply some changes suggested by Shivansh-007 made send_score docstring more precise, added a comment for better understanding, and changed an error embed description --- bot/exts/evergreen/trivia_quiz.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 045fedbf..2620dea1 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -125,6 +125,7 @@ def binary_calc(q_format: str, a_format: str) -> QAndA: ) ) + # if the operator is multiplication, lower the values of the two operands to make it easier if oper[0] == "*": a -= 5 b -= 5 @@ -264,7 +265,8 @@ class TriviaQuiz(commands.Cog): elif questions < 1: await ctx.send( embed=self.make_error_embed( - "You must choose to complete at least one question." + "You must choose to complete at least one question. " + "(or enter 0 for the default value of 7 questions)" ) ) return @@ -471,7 +473,7 @@ class TriviaQuiz(commands.Cog): @staticmethod async def send_score(channel: discord.TextChannel, player_data: dict) -> None: - """Send the score.""" + """Send the current scores of players in the game channel.""" if len(player_data) == 0: await channel.send("No one has made it onto the leaderboard yet.") return -- cgit v1.2.3 From 4ba9c941fc8ceb50cf61cfcb5ae15afc6216c7b2 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Mon, 10 May 2021 09:28:43 -0400 Subject: chore: Apply more suggested changes --- bot/exts/easter/bunny_name_generator.py | 1 + bot/exts/evergreen/help.py | 12 +++++++++--- bot/exts/evergreen/snakes/_utils.py | 4 +--- bot/exts/valentines/be_my_valentine.py | 18 ++++++------------ 4 files changed, 17 insertions(+), 18 deletions(-) (limited to 'bot') diff --git a/bot/exts/easter/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index 19a0b0f6..b6523ff6 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -23,6 +23,7 @@ class BunnyNameGenerator(commands.Cog): 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: """ diff --git a/bot/exts/evergreen/help.py b/bot/exts/evergreen/help.py index bfaf25f1..7e3fdad4 100644 --- a/bot/exts/evergreen/help.py +++ b/bot/exts/evergreen/help.py @@ -2,9 +2,8 @@ import asyncio import itertools import logging -from collections import namedtuple from contextlib import suppress -from typing import Union +from typing import List, NamedTuple, Union from discord import Colour, Embed, HTTPException, Message, Reaction, User from discord.ext import commands @@ -29,7 +28,14 @@ REACTIONS = { DELETE_EMOJI: "stop", } -Cog = namedtuple("Cog", ["name", "description", "commands"]) + +class Cog(NamedTuple): + """Show information about a Cog's name, description and commands.""" + + name: str + description: str + commands: List[Command] + log = logging.getLogger(__name__) diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index 998c13a9..9b38ffa2 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -192,9 +192,7 @@ class PerlinNoiseFactory(object): """Get plain noise for a single point, without taking into account either octaves or tiling.""" if len(point) != self.dimension: raise ValueError( - "Expected {0} values, got {1}".format( - self.dimension, len(point) - ) + f"Expected {self.dimension} values, got {len(point)}" ) # Build a list of the (min, max) bounds in each dimension diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index b9cf6738..d1eea388 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -151,21 +151,17 @@ class BeMyValentine(commands.Cog): def valentine_check(self, valentine_type: str) -> Tuple[str, str]: """Return the appropriate Valentine type & title based on the invoking user's input.""" if valentine_type is None: - valentine, title = self.random_valentine() + return self.random_valentine() elif valentine_type.lower() in ["p", "poem"]: - valentine = self.valentine_poem() - title = "A poem dedicated to" + return self.valentine_poem(), "A poem dedicated to" elif valentine_type.lower() in ["c", "compliment"]: - valentine = self.valentine_compliment() - title = "A compliment for" + return self.valentine_compliment(), "A compliment for" else: # in this case, the user decides to type his own valentine. - valentine = valentine_type - title = "A message for" - return valentine, title + return valentine_type, "A message for" @staticmethod def random_emoji() -> Tuple[str, str]: @@ -187,13 +183,11 @@ class BeMyValentine(commands.Cog): def valentine_poem(self) -> str: """Grabs a random poem.""" - valentine_poem = random.choice(self.valentines["valentine_poems"]) - return valentine_poem + return random.choice(self.valentines["valentine_poems"]) def valentine_compliment(self) -> str: """Grabs a random compliment.""" - valentine_compliment = random.choice(self.valentines["valentine_compliments"]) - return valentine_compliment + return random.choice(self.valentines["valentine_compliments"]) def setup(bot: Bot) -> None: -- cgit v1.2.3 From 52aa6dcd499fc3e757a226c1192755888a6d88ef Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Mon, 10 May 2021 09:30:46 -0400 Subject: chore: ctx.message.author -> ctx.author --- bot/exts/easter/bunny_name_generator.py | 2 +- bot/exts/evergreen/snakes/_snakes_cog.py | 6 +++--- bot/exts/halloween/monsterbio.py | 2 +- bot/exts/internal_eval/_internal_eval.py | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) (limited to 'bot') diff --git a/bot/exts/easter/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index b6523ff6..5e3b014d 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -62,7 +62,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) diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index 6278c883..b844960a 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -746,7 +746,7 @@ class Snakes(Cog): my_snake_embed = Embed(description=":tada: Congrats! You hatched: **{0}**".format(snake_name)) my_snake_embed.set_thumbnail(url=snake_image) my_snake_embed.set_footer( - text=" Owner: {0}#{1}".format(ctx.message.author.name, ctx.message.author.discriminator) + text=" Owner: {0}#{1}".format(ctx.author.name, ctx.author.discriminator) ) await ctx.send(embed=my_snake_embed) @@ -1046,14 +1046,14 @@ class Snakes(Cog): """ with ctx.typing(): embed = Embed() - user = ctx.message.author + user = ctx.author if not message: # Get a random message from the users history messages = [] async for message in ctx.channel.history(limit=500).filter( - lambda msg: msg.author == ctx.message.author # Message was sent by author. + lambda msg: msg.author == ctx.author # Message was sent by author. ): messages.append(message.content) diff --git a/bot/exts/halloween/monsterbio.py b/bot/exts/halloween/monsterbio.py index dbafa43f..1aaba7bb 100644 --- a/bot/exts/halloween/monsterbio.py +++ b/bot/exts/halloween/monsterbio.py @@ -26,7 +26,7 @@ class MonsterBio(commands.Cog): @commands.command(brief="Sends your monster bio!") async def monsterbio(self, ctx: commands.Context) -> None: """Sends a description of a monster.""" - seeded_random = random.Random(ctx.message.author.id) # Seed a local Random instance rather than the system one + seeded_random = random.Random(ctx.author.id) # Seed a local Random instance rather than the system one name = self.generate_name(seeded_random) species = self.generate_name(seeded_random) diff --git a/bot/exts/internal_eval/_internal_eval.py b/bot/exts/internal_eval/_internal_eval.py index 4fe3bc09..56bf5add 100644 --- a/bot/exts/internal_eval/_internal_eval.py +++ b/bot/exts/internal_eval/_internal_eval.py @@ -114,7 +114,7 @@ class InternalEval(commands.Cog): """Evaluate the `code` in the current evaluation context.""" context_vars = { "message": ctx.message, - "author": ctx.message.author, + "author": ctx.author, "channel": ctx.channel, "guild": ctx.guild, "ctx": ctx, -- cgit v1.2.3 From b17a60a83edc98405e75ae84de23bbd1c7f4bf6c Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Mon, 10 May 2021 09:35:48 -0400 Subject: chore: Use ctx instead of ctx.channel --- bot/exts/easter/egghead_quiz.py | 2 +- bot/exts/evergreen/error_handler.py | 5 +---- bot/exts/evergreen/snakes/_snakes_cog.py | 2 +- bot/exts/evergreen/wolfram.py | 6 +++--- 4 files changed, 6 insertions(+), 9 deletions(-) (limited to 'bot') diff --git a/bot/exts/easter/egghead_quiz.py b/bot/exts/easter/egghead_quiz.py index 59c1f6f8..b6b1593d 100644 --- a/bot/exts/easter/egghead_quiz.py +++ b/bot/exts/easter/egghead_quiz.py @@ -64,7 +64,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 diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index faaf1386..de8e53d0 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -125,10 +125,7 @@ class CommandErrorHandler(commands.Cog): scope.set_extra("full_message", ctx.message.content) if ctx.guild is not None: - scope.set_extra( - "jump_to", - f"https://discordapp.com/channels/{ctx.guild.id}/{ctx.channel.id}/{ctx.message.id}" - ) + scope.set_extra("jump_to", ctx.message.jump_url) log.exception(f"Unhandled command error: {str(error)}", exc_info=error) diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index b844960a..c50b23c5 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -1052,7 +1052,7 @@ class Snakes(Cog): # Get a random message from the users history messages = [] - async for message in ctx.channel.history(limit=500).filter( + async for message in ctx.history(limit=500).filter( lambda msg: msg.author == ctx.author # Message was sent by author. ): messages.append(message.content) diff --git a/bot/exts/evergreen/wolfram.py b/bot/exts/evergreen/wolfram.py index 3cc12c03..ca7d8454 100644 --- a/bot/exts/evergreen/wolfram.py +++ b/bot/exts/evergreen/wolfram.py @@ -105,7 +105,7 @@ def custom_cooldown(*ignore: List[int]) -> Callable: async def get_pod_pages(ctx: Context, bot: Bot, query: str) -> Optional[List[Tuple]]: """Get the Wolfram API pod pages for the provided query.""" - async with ctx.channel.typing(): + async with ctx.typing(): url_str = parse.urlencode({ "input": query, "appid": APPID, @@ -180,7 +180,7 @@ class Wolfram(Cog): query = QUERY.format(request="simple", data=url_str) # Give feedback that the bot is working. - async with ctx.channel.typing(): + async with ctx.typing(): async with self.bot.http_session.get(query) as response: status = response.status image_bytes = await response.read() @@ -263,7 +263,7 @@ class Wolfram(Cog): query = QUERY.format(request="result", data=url_str) # Give feedback that the bot is working. - async with ctx.channel.typing(): + async with ctx.typing(): async with self.bot.http_session.get(query) as response: status = response.status response_text = await response.text() -- cgit v1.2.3 From 6040e351403c5a708e77a26d1f8167f767988c56 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 12:06:19 -0300 Subject: make vartol stricter when it's a generated question also fixed image not displaying bug --- bot/exts/evergreen/trivia_quiz.py | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 2620dea1..c00d91ae 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -4,7 +4,7 @@ import logging import operator import random from pathlib import Path -from typing import List, Optional, Tuple +from typing import Callable, List, Optional, Tuple import discord from discord.ext import commands @@ -18,7 +18,8 @@ logger = logging.getLogger(__name__) QAndA = Tuple[str, str] -VARIATION_TOLERANCE = 83 +STANDARD_VARIATION_TOLERANCE = 83 +DYNAMICALLY_GEN_VARIATION_TOLERANCE = 95 WRONG_ANS_RESPONSE = [ "No one answered correctly!", @@ -215,13 +216,11 @@ class TriviaQuiz(commands.Cog): async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! - Questions for the quiz can be selected from the following categories: - general: Test your general knowledge. (default) - retro: Questions related to retro gaming. - math: General questions about mathematics ranging from grade 8 to grade 12. - science: Put your understanding of science to the test! - (More to come!) """ if ctx.channel.id not in self.game_status: @@ -311,6 +310,8 @@ class TriviaQuiz(commands.Cog): if "dynamic_id" not in question_dict: question = question_dict["question"] answers = question_dict["answer"].split(", ") + + var_tol = STANDARD_VARIATION_TOLERANCE else: format_func = DYNAMIC_QUESTIONS_FORMAT_FUNCS[question_dict["dynamic_id"]] @@ -318,28 +319,32 @@ class TriviaQuiz(commands.Cog): question_dict["question"], question_dict["answer"], ) - answers = [answers] + var_tol = DYNAMICALLY_GEN_VARIATION_TOLERANCE + embed = discord.Embed( colour=Colours.gold, title=f"Question #{len(done_question)}", description=question, ) - if img_url := question_dict.get("image_url"): + if img_url := question_dict.get("img_url"): embed.set_image(url=img_url) await ctx.send(embed=embed) - def contains_correct_answer(m: discord.Message) -> bool: - return m.channel == ctx.channel and any( - fuzz.ratio(answer.lower(), m.content.lower()) > VARIATION_TOLERANCE - for answer in answers - ) + def check_func(variation_tolerance: int) -> Callable[[discord.Message], bool]: + def contains_correct_answer(m: discord.Message) -> bool: + return m.channel == ctx.channel and any( + fuzz.ratio(answer.lower(), m.content.lower()) > variation_tolerance + for answer in answers + ) + + return contains_correct_answer try: - msg = await self.bot.wait_for("message", check=contains_correct_answer, timeout=10) + msg = await self.bot.wait_for("message", check=check_func(var_tol), timeout=10) except asyncio.TimeoutError: # In case of TimeoutError and the game has been stopped, then do nothing. if not self.game_status[ctx.channel.id]: @@ -445,7 +450,6 @@ class TriviaQuiz(commands.Cog): async def stop_quiz(self, ctx: commands.Context) -> None: """ Stop a quiz game if its running in the channel. - Note: Only mods or the owner of the quiz can stop it. """ if self.game_status[ctx.channel.id] is True: @@ -552,7 +556,7 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=Colours.bright_green, title=( - "You got it! " if answer_is_correct else "" + ("You got it! " if answer_is_correct else "") + f"The correct answer {word} **`{', '.join(answers)}`**\n" ), description="", @@ -562,7 +566,7 @@ class TriviaQuiz(commands.Cog): embed.description += f"**Information**\n{info}\n\n" embed.description += ( - "Let's move to the next question." if q_left > 0 else "" + ("Let's move to the next question." if q_left > 0 else "") + f"\nRemaining questions: {q_left}" ) await channel.send(embed=embed) -- cgit v1.2.3 From aab59b138e877fab349314b4b326ede914ea56c3 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 12:10:54 -0300 Subject: lint failure fixes --- bot/exts/evergreen/trivia_quiz.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index c00d91ae..94dc9f06 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -216,11 +216,13 @@ class TriviaQuiz(commands.Cog): async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! + Questions for the quiz can be selected from the following categories: - general: Test your general knowledge. (default) - retro: Questions related to retro gaming. - math: General questions about mathematics ranging from grade 8 to grade 12. - science: Put your understanding of science to the test! + (More to come!) """ if ctx.channel.id not in self.game_status: @@ -450,6 +452,7 @@ class TriviaQuiz(commands.Cog): async def stop_quiz(self, ctx: commands.Context) -> None: """ Stop a quiz game if its running in the channel. + Note: Only mods or the owner of the quiz can stop it. """ if self.game_status[ctx.channel.id] is True: @@ -556,8 +559,8 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=Colours.bright_green, title=( - ("You got it! " if answer_is_correct else "") + - f"The correct answer {word} **`{', '.join(answers)}`**\n" + ("You got it! " if answer_is_correct else "") + + f"The correct answer {word} **`{', '.join(answers)}`**\n" ), description="", ) @@ -566,8 +569,8 @@ class TriviaQuiz(commands.Cog): embed.description += f"**Information**\n{info}\n\n" embed.description += ( - ("Let's move to the next question." if q_left > 0 else "") + - f"\nRemaining questions: {q_left}" + ("Let's move to the next question." if q_left > 0 else "") + + f"\nRemaining questions: {q_left}" ) await channel.send(embed=embed) -- cgit v1.2.3 From 8c9298495a86da7c7b67b0a5d7557819ce0057e7 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 10 May 2021 20:52:13 +0100 Subject: Remove redundant comments in bookmark cog --- bot/exts/evergreen/bookmark.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 5f550a4a..7a97a40d 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -24,7 +24,7 @@ class Bookmark(commands.Cog): @staticmethod def build_bookmark_dm(target_message: discord.Message, title: str) -> discord.Embed: - """Builds the embed to DM the bookmark requester.""" + """Build the embed to DM the bookmark requester.""" embed = discord.Embed( title=title, description=target_message.content, @@ -131,13 +131,11 @@ class Bookmark(commands.Cog): _, user = await self.bot.wait_for("reaction_add", timeout=TIMEOUT, check=event_check) except asyncio.TimeoutError: log.debug("Timed out waiting for a reaction") - # No reactions for the last `TIMEOUT` seconds break log.trace(f"{user} has successfully bookmarked from a reaction, attempting to DM them.") await self.action_bookmark(ctx.channel, user, target_message, title) bookmarked_users.append(user.id) - # Delete the message now that the bot isn't listening to it to save screen space await reaction_message.delete() -- cgit v1.2.3 From 3f0388556c886d9d8e26b7a0373e3a6d2d9ba5ad Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 09:05:09 -0400 Subject: fix original copy paste error in math question Co-authored-by: Matteo Bertucci --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 79e79d00..1e85542f 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -301,7 +301,7 @@ }, { "id": 203, - "question": "Which theorem states that hypotenuse2 = base2 + height2?", + "question": "Which theorem states that hypotenuse^2 = base^2 + height^2?", "answer": "Pythagorean's, Pythagorean's theorem" }, { -- cgit v1.2.3 From fa0f365acebfdef1130330dc2835945e9da3a69b Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 10:08:40 -0300 Subject: add one more correct answer to science (q328) --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 1e85542f..774c235a 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -592,7 +592,7 @@ { "id": 328, "question": "Which law states that the global entropy in a closed system can only increase?", - "answer": "second law of thermodynamics" + "answer": "second law, second law of thermodynamics" }, { "id": 329, -- cgit v1.2.3 From d2754ce38232955e17322264e78ca90b0a3d7cb7 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 10:57:36 -0300 Subject: made comment more precise as described by decorator-factory --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 94dc9f06..94d9e374 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -381,7 +381,7 @@ class TriviaQuiz(commands.Cog): ) await asyncio.sleep(1) - hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. + hint_no = 0 # Reset the hint counter so that on the next round, it's in the initial state await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) -- cgit v1.2.3 From 5241fc893d1d378f6a4dcae32925f672ce8f87a7 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 15:29:13 -0300 Subject: change weird google docs unicode to standard ones --- bot/resources/evergreen/trivia_quiz.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 774c235a..e2054f43 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -301,7 +301,7 @@ }, { "id": 203, - "question": "Which theorem states that hypotenuse^2 = base^2 + height^2?", + "question": "Which theorem states that hypotenuse2 = base2 + height2?", "answer": "Pythagorean's, Pythagorean's theorem" }, { @@ -360,7 +360,7 @@ }, { "id": 214, - "question": "⅓πr2h is the volume of which 3 dimensional figure?", + "question": "⅓πr^2h is the volume of which 3 dimensional figure?", "answer": "cone" }, { @@ -452,7 +452,7 @@ "science": [ { "id": 301, - "question": "The three main components of a normal atom are: protons, neutrons, and…", + "question": "The three main components of a normal atom are: protons, neutrons, and...", "answer": "electrons" }, { @@ -472,7 +472,7 @@ }, { "id": 305, - "question": "The Heisenberg’s Uncertainty Principle states that the position and ________ of a quantum object can’t be both exactly measured at the same time.", + "question": "The Heisenberg's Uncertainty Principle states that the position and ________ of a quantum object can't be both exactly measured at the same time.", "answer": "velocity, momentum" }, { @@ -500,9 +500,9 @@ { "id": 310, "dynamic_id": 303, - "question": "How does one describe the unit {} in SI base units?\n**IMPORTANT:** use * for multiplication, ^ for exponentiation, and place your base units in this order: m - kg - s - A", + "question": "How does one describe the unit {} in SI base units?\n**IMPORTANT:** enclose answer in backticks, use \\* for multiplication, ^ for exponentiation, and place your base units in this order: m - kg - s - A", "img_url": "https://i.imgur.com/NRzU6tf.png", - "answer": "{}" + "answer": "`{}`" }, { "id": 311, -- cgit v1.2.3 From 91db03e5fde06efb41341d595d75424b9ff759b2 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 15:30:34 -0300 Subject: fix copy paste error --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index e2054f43..1ba5ea7b 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -301,7 +301,7 @@ }, { "id": 203, - "question": "Which theorem states that hypotenuse2 = base2 + height2?", + "question": "Which theorem states that hypotenuse^2 = base^2 + height2^?", "answer": "Pythagorean's, Pythagorean's theorem" }, { -- cgit v1.2.3 From febe3e7d5fea74ed939b903306e552177b2c61c2 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 15:32:30 -0300 Subject: fix unicode corruption errors by encoding to utf-8 --- bot/exts/evergreen/trivia_quiz.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 94d9e374..7fdd3f5f 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -10,9 +10,7 @@ import discord from discord.ext import commands from fuzzywuzzy import fuzz -from bot.constants import Colours -from bot.constants import NEGATIVE_REPLIES -from bot.constants import Roles +from bot.constants import Colours, NEGATIVE_REPLIES, Roles logger = logging.getLogger(__name__) @@ -210,7 +208,7 @@ class TriviaQuiz(commands.Cog): """Load the questions from the JSON file.""" p = Path("bot", "resources", "evergreen", "trivia_quiz.json") - return json.loads(p.read_text()) + return json.loads(p.read_text(encoding="utf-8")) @commands.group(name="quiz", aliases=["trivia"], invoke_without_command=True) async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: -- cgit v1.2.3 From 8ee99da88cb5d2b0fc9b1e3dcf24f72bca5679a4 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 08:38:53 -0400 Subject: fix ANOTHER copy paste error 3rd copy paste error- smh Co-authored-by: Shivansh-007 --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 1ba5ea7b..acf7375a 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -301,7 +301,7 @@ }, { "id": 203, - "question": "Which theorem states that hypotenuse^2 = base^2 + height2^?", + "question": "Which theorem states that hypotenuse^2 = base^2 + height^2?", "answer": "Pythagorean's, Pythagorean's theorem" }, { -- cgit v1.2.3 From 4448f0d04987ac2628f74e43f6262a5856509f9d Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 09:41:05 -0300 Subject: add one more possible answer to math q208 --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index acf7375a..3a907de1 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -328,7 +328,7 @@ "id": 208, "question": "What's the following formula that finds the area of a triangle called?", "img_url": "https://wikimedia.org/api/rest_v1/media/math/render/png/d22b8566e8187542966e8d166e72e93746a1a6fc", - "answer": "Heron's formula" + "answer": "Heron's formula, Heron" }, { "id": 209, -- cgit v1.2.3 From 358e5641d16ac27ca68c73f52cbccf12299818d6 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 10:56:18 -0300 Subject: fix inconsistency of hexadecimal letter cases in Colours class --- bot/constants.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'bot') diff --git a/bot/constants.py b/bot/constants.py index 9b45b89a..28ec477d 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -140,19 +140,19 @@ class Client(NamedTuple): class Colours: - blue = 0x0279fd - bright_green = 0x01d277 - dark_green = 0x1f8b4c - orange = 0xe67e22 - pink = 0xcf84e0 - purple = 0xb734eb - soft_green = 0x68c290 - soft_orange = 0xf9cb54 - soft_red = 0xcd6d6d - yellow = 0xf9f586 + blue = 0x0279FD + bright_green = 0x01D277 + dark_green = 0x1F8B4C + orange = 0xE67E22 + pink = 0xCF84E0 + purple = 0xB734EB + soft_green = 0x68C290 + soft_orange = 0xF9CB54 + soft_red = 0xCD6D6D + yellow = 0xF9F586 python_blue = 0x4B8BBE python_yellow = 0xFFD43B - grass_green = 0x66ff00 + grass_green = 0x66FF00 gold = 0xE6C200 easter_like_colours = [ @@ -180,7 +180,7 @@ class Emojis: envelope = "\U0001F4E8" trashcan = environ.get("TRASHCAN_EMOJI", "<:trashcan:637136429717389331>") ok_hand = ":ok_hand:" - hand_raised = "\U0001f64b" + hand_raised = "\U0001F64B" dice_1 = "<:dice_1:755891608859443290>" dice_2 = "<:dice_2:755891608741740635>" -- cgit v1.2.3 From 4430760c56f71046040369b3b1f248d8344bf968 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 11:45:06 -0300 Subject: 0 as an input to `questions` would now also raise an error before it would go to the default of 7 --- bot/exts/evergreen/trivia_quiz.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 7fdd3f5f..c2f891e2 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -16,6 +16,7 @@ logger = logging.getLogger(__name__) QAndA = Tuple[str, str] +DEFAULT_QUESTION_LIMIT = 6 STANDARD_VARIATION_TOLERANCE = 83 DYNAMICALLY_GEN_VARIATION_TOLERANCE = 95 @@ -191,7 +192,7 @@ class TriviaQuiz(commands.Cog): self.game_owners = {} # A variable to store the person's ID who started the quiz game in a channel. self.questions = self.load_questions() - self.question_limit = 6 + self.question_limit = 0 self.player_scores = {} # A variable to store all player's scores for a bot session. self.game_player_scores = {} # A variable to store temporary game player's scores. @@ -251,7 +252,9 @@ class TriviaQuiz(commands.Cog): topic = self.questions[category] topic_length = len(topic) - if questions: + if questions is None: + self.question_limit = DEFAULT_QUESTION_LIMIT + else: if questions > topic_length: await ctx.send( embed=self.make_error_embed( @@ -265,7 +268,7 @@ class TriviaQuiz(commands.Cog): await ctx.send( embed=self.make_error_embed( "You must choose to complete at least one question. " - "(or enter 0 for the default value of 7 questions)" + "(or enter nothing for the default value of 7 questions)" ) ) return -- cgit v1.2.3 From cb3b7a394f5fe60f75279d7ac9e4cdb47b267a20 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 11:53:04 -0300 Subject: make the error embed change accordingly if DQL constant is modified --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index c2f891e2..0b242947 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -268,7 +268,7 @@ class TriviaQuiz(commands.Cog): await ctx.send( embed=self.make_error_embed( "You must choose to complete at least one question. " - "(or enter nothing for the default value of 7 questions)" + f"(or enter nothing for the default value of {DEFAULT_QUESTION_LIMIT + 1} questions)" ) ) return -- cgit v1.2.3 From 8f4911ad75d0860c8710e977a3d6928378fd703e Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 14:23:24 -0300 Subject: quality-of-life refinery --- bot/exts/evergreen/trivia_quiz.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 0b242947..cc1bb0bb 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -423,7 +423,7 @@ class TriviaQuiz(commands.Cog): colour=Colours.blue, title="Quiz game starting!", description=( - f"Each game consists of {self.question_limit + 1} questions.\n" + f"This game consists of {self.question_limit + 1} questions.\n" "**Rules: **No cheating and have fun!\n" f"**Category**: {category}" ), @@ -555,13 +555,13 @@ class TriviaQuiz(commands.Cog): """Send the correct answer of a question to the game channel.""" info = question_dict.get("info", "") - word = "is" if len(answers) == 1 else "are" + plurality = " is" if len(answers) == 1 else "s are" embed = discord.Embed( color=Colours.bright_green, title=( ("You got it! " if answer_is_correct else "") - + f"The correct answer {word} **`{', '.join(answers)}`**\n" + + f"The correct answer{word} **`{', '.join(answers)}`**\n" ), description="", ) -- cgit v1.2.3 From 7df1d38400a275fb6c2d079f27ffaedad5bd4453 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 14:24:41 -0300 Subject: fix 4th copy paste error --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index cc1bb0bb..e1a06aa5 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -561,7 +561,7 @@ class TriviaQuiz(commands.Cog): color=Colours.bright_green, title=( ("You got it! " if answer_is_correct else "") - + f"The correct answer{word} **`{', '.join(answers)}`**\n" + + f"The correct answer{plurality} **`{', '.join(answers)}`**\n" ), description="", ) -- cgit v1.2.3 From b125a1ab1cdb8355d6c4c5225f1b048ca760e957 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 08:49:41 -0400 Subject: change the unsolvable math question to a linalg question --- bot/resources/evergreen/trivia_quiz.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 3a907de1..94082849 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -417,8 +417,8 @@ }, { "id": 225, - "question": "Prove or disprove the Riemann Hypothesis", - "answer": "" + "question": "A matrix multiplied by its inverse matrix equals...", + "answer": "the identity matrix, identity matrix" }, { "id": 226, -- cgit v1.2.3 From 2aa1916d5c8e4832f26f6da4094238e9a0021d1c Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Thu, 13 May 2021 13:34:06 -0400 Subject: chore: Use pathlib.Path.read_text & write_text over open --- bot/exts/christmas/advent_of_code/_cog.py | 3 +-- bot/exts/easter/april_fools_vids.py | 6 +++--- bot/exts/easter/bunny_name_generator.py | 3 +-- bot/exts/easter/easter_riddle.py | 5 ++--- bot/exts/easter/egg_decorating.py | 6 ++---- bot/exts/easter/egg_facts.py | 5 ++--- bot/exts/easter/egghead_quiz.py | 5 ++--- bot/exts/easter/save_the_planet.py | 4 +--- bot/exts/easter/traditions.py | 3 +-- bot/exts/evergreen/avatar_modification/avatar_modify.py | 4 ++-- bot/exts/evergreen/fun.py | 3 +-- bot/exts/evergreen/magic_8ball.py | 3 +-- bot/exts/evergreen/recommend_game.py | 3 +-- bot/exts/evergreen/snakes/_converter.py | 7 ++----- bot/exts/evergreen/snakes/_utils.py | 5 ++--- bot/exts/evergreen/speedrun.py | 4 ++-- bot/exts/evergreen/trivia_quiz.py | 4 +--- bot/exts/halloween/8ball.py | 3 +-- bot/exts/halloween/halloween_facts.py | 3 +-- bot/exts/halloween/halloweenify.py | 5 ++--- bot/exts/halloween/monsterbio.py | 5 +++-- bot/exts/halloween/monstersurvey.py | 6 ++---- bot/exts/halloween/spookynamerate.py | 3 +-- bot/exts/halloween/spookyrating.py | 6 +++--- bot/exts/pride/drag_queen_name.py | 3 +-- bot/exts/pride/pride_anthem.py | 4 +--- bot/exts/pride/pride_facts.py | 3 +-- bot/exts/valentines/be_my_valentine.py | 6 ++---- bot/exts/valentines/lovecalculator.py | 5 ++--- bot/exts/valentines/myvalenstate.py | 3 +-- bot/exts/valentines/pickuplines.py | 9 ++++----- bot/exts/valentines/savethedate.py | 5 ++--- bot/exts/valentines/valentine_zodiac.py | 16 ++++++++-------- bot/exts/valentines/whoisvalentine.py | 3 +-- 34 files changed, 63 insertions(+), 98 deletions(-) (limited to 'bot') diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index 863d2a21..ce6a4cb6 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -279,8 +279,7 @@ class AdventOfCode(commands.Cog): def _build_about_embed(self) -> discord.Embed: """Build and return the informational "About AoC" embed from the resources file.""" - with self.about_aoc_filepath.open("r", encoding="utf8") as f: - embed_fields = json.load(f) + embed_fields = json.loads(self.about_aoc_filepath.read_text("utf8")) about_embed = discord.Embed( title=self._base_url, diff --git a/bot/exts/easter/april_fools_vids.py b/bot/exts/easter/april_fools_vids.py index 3ce1f72a..5ef40704 100644 --- a/bot/exts/easter/april_fools_vids.py +++ b/bot/exts/easter/april_fools_vids.py @@ -1,6 +1,7 @@ import logging import random -from json import load +from json import loads +from pathlib import Path from discord.ext import commands @@ -8,8 +9,7 @@ from bot.bot import Bot log = logging.getLogger(__name__) -with open("bot/resources/easter/april_fools_vids.json", encoding="utf-8") as f: - ALL_VIDS = load(f) +ALL_VIDS = loads(Path("bot/resources/easter/april_fools_vids.json").read_text("utf-8")) class AprilFoolVideos(commands.Cog): diff --git a/bot/exts/easter/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index 5e3b014d..adde8704 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -11,8 +11,7 @@ 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): diff --git a/bot/exts/easter/easter_riddle.py b/bot/exts/easter/easter_riddle.py index 9a253a6a..01b956f1 100644 --- a/bot/exts/easter/easter_riddle.py +++ b/bot/exts/easter/easter_riddle.py @@ -1,7 +1,7 @@ import asyncio import logging import random -from json import load +from json import loads from pathlib import Path import discord @@ -12,8 +12,7 @@ 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 diff --git a/bot/exts/easter/egg_decorating.py b/bot/exts/easter/egg_decorating.py index 3744989d..7448f702 100644 --- a/bot/exts/easter/egg_decorating.py +++ b/bot/exts/easter/egg_decorating.py @@ -15,11 +15,9 @@ 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), diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index 8c93ca7b..c1c43f80 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 @@ -30,8 +30,7 @@ class EasterFacts(commands.Cog): 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) + return loads(p.read_text("utf8")) @seasonal_task(Month.APRIL) async def send_egg_fact_daily(self) -> None: diff --git a/bot/exts/easter/egghead_quiz.py b/bot/exts/easter/egghead_quiz.py index b6b1593d..4b67310f 100644 --- a/bot/exts/easter/egghead_quiz.py +++ b/bot/exts/easter/egghead_quiz.py @@ -1,7 +1,7 @@ import asyncio import logging import random -from json import load +from json import loads from pathlib import Path from typing import Union @@ -13,8 +13,7 @@ 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 = [ diff --git a/bot/exts/easter/save_the_planet.py b/bot/exts/easter/save_the_planet.py index 444bb030..1bd515f2 100644 --- a/bot/exts/easter/save_the_planet.py +++ b/bot/exts/easter/save_the_planet.py @@ -7,9 +7,7 @@ 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): diff --git a/bot/exts/easter/traditions.py b/bot/exts/easter/traditions.py index cb70f2d0..93404f3e 100644 --- a/bot/exts/easter/traditions.py +++ b/bot/exts/easter/traditions.py @@ -9,8 +9,7 @@ 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): diff --git a/bot/exts/evergreen/avatar_modification/avatar_modify.py b/bot/exts/evergreen/avatar_modification/avatar_modify.py index 5685b2c1..199b6dcb 100644 --- a/bot/exts/evergreen/avatar_modification/avatar_modify.py +++ b/bot/exts/evergreen/avatar_modification/avatar_modify.py @@ -6,6 +6,7 @@ import string import typing as t import unicodedata from concurrent.futures import ThreadPoolExecutor +from pathlib import Path import discord from aiohttp import client_exceptions @@ -27,8 +28,7 @@ MAX_SQUARES = 10_000 T = t.TypeVar("T") -with open("bot/resources/pride/gender_options.json") as f: - GENDER_OPTIONS = json.load(f) +GENDER_OPTIONS = json.loads(Path("bot/resources/pride/gender_options.json").read_text("utf8")) async def in_executor(func: t.Callable[..., T], *args) -> T: diff --git a/bot/exts/evergreen/fun.py b/bot/exts/evergreen/fun.py index ed51358c..3b266e1b 100644 --- a/bot/exts/evergreen/fun.py +++ b/bot/exts/evergreen/fun.py @@ -56,8 +56,7 @@ class Fun(Cog): def __init__(self, bot: Bot) -> None: self.bot = bot - with Path("bot/resources/evergreen/caesar_info.json").open("r", encoding="UTF-8") as f: - self._caesar_cipher_embed = json.load(f) + self._caesar_cipher_embed = json.loads(Path("bot/resources/evergreen/caesar_info.json").read_text("UTF-8")) @staticmethod def _get_random_die() -> str: diff --git a/bot/exts/evergreen/magic_8ball.py b/bot/exts/evergreen/magic_8ball.py index 7c9b929d..4b3ed2a4 100644 --- a/bot/exts/evergreen/magic_8ball.py +++ b/bot/exts/evergreen/magic_8ball.py @@ -14,8 +14,7 @@ class Magic8ball(commands.Cog): """A Magic 8ball command to respond to a user's question.""" def __init__(self): - with open(Path("bot/resources/evergreen/magic8ball.json"), "r", encoding="utf8") as file: - self.answers = json.load(file) + self.answers = json.loads(Path("bot/resources/evergreen/magic8ball.json").read_text("utf8")) @commands.command(name="8ball") async def output_answer(self, ctx: commands.Context, *, question: str) -> None: diff --git a/bot/exts/evergreen/recommend_game.py b/bot/exts/evergreen/recommend_game.py index 340a42d3..56596020 100644 --- a/bot/exts/evergreen/recommend_game.py +++ b/bot/exts/evergreen/recommend_game.py @@ -13,8 +13,7 @@ game_recs = [] # Populate the list `game_recs` with resource files for rec_path in Path("bot/resources/evergreen/game_recs").glob("*.json"): - with rec_path.open(encoding="utf8") as file: - data = json.load(file) + data = json.loads(rec_path.read_text("utf8")) game_recs.append(data) shuffle(game_recs) diff --git a/bot/exts/evergreen/snakes/_converter.py b/bot/exts/evergreen/snakes/_converter.py index 0ca10d6c..26bde611 100644 --- a/bot/exts/evergreen/snakes/_converter.py +++ b/bot/exts/evergreen/snakes/_converter.py @@ -63,13 +63,10 @@ class Snake(Converter): """Build list of snakes from the static snake resources.""" # Get all the snakes if cls.snakes is None: - with (SNAKE_RESOURCES / "snake_names.json").open(encoding="utf8") as snakefile: - cls.snakes = json.load(snakefile) - + cls.snakes = json.loads((SNAKE_RESOURCES / "snake_names.json").read_text("utf8")) # Get the special cases if cls.special_cases is None: - with (SNAKE_RESOURCES / "special_snakes.json").open(encoding="utf8") as snakefile: - special_cases = json.load(snakefile) + special_cases = json.loads((SNAKE_RESOURCES / "special_snakes.json").read_text("utf8")) cls.special_cases = {snake["name"].lower(): snake for snake in special_cases} @classmethod diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index 9b38ffa2..8b39f217 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -114,8 +114,7 @@ ANGLE_RANGE = math.pi * 2 def get_resource(file: str) -> List[dict]: """Load Snake resources JSON.""" - with (SNAKE_RESOURCES / f"{file}.json").open(encoding="utf-8") as snakefile: - return json.load(snakefile) + return json.loads((SNAKE_RESOURCES / f"{file}.json").read_text("utf-8")) def smoothstep(t: float) -> float: @@ -560,7 +559,7 @@ class SnakeAndLaddersGame: self.state = "roll" for user in self.players: self.round_has_rolled[user.id] = False - board_img = Image.open(str(SNAKE_RESOURCES / "snakes_and_ladders" / "board.jpg")) + board_img = Image.open(SNAKE_RESOURCES / "snakes_and_ladders" / "board.jpg") player_row_size = math.ceil(MAX_PLAYERS / 2) for i, player in enumerate(self.players): diff --git a/bot/exts/evergreen/speedrun.py b/bot/exts/evergreen/speedrun.py index d9820287..774eff81 100644 --- a/bot/exts/evergreen/speedrun.py +++ b/bot/exts/evergreen/speedrun.py @@ -8,8 +8,8 @@ from discord.ext import commands from bot.bot import Bot log = logging.getLogger(__name__) -with Path("bot/resources/evergreen/speedrun_links.json").open(encoding="utf8") as file: - LINKS = json.load(file) + +LINKS = json.loads(Path("bot/resources/evergreen/speedrun_links.json").read_text("utf8")) class Speedrun(commands.Cog): diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 1953253b..9db201ef 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -41,9 +41,7 @@ class TriviaQuiz(commands.Cog): def load_questions() -> dict: """Load the questions from the JSON file.""" p = Path("bot", "resources", "evergreen", "trivia_quiz.json") - with p.open(encoding="utf8") as json_data: - questions = json.load(json_data) - return questions + return json.loads(p.read_text("utf8")) @commands.group(name="quiz", aliases=["trivia"], invoke_without_command=True) async def quiz_game(self, ctx: commands.Context, category: str = None) -> None: diff --git a/bot/exts/halloween/8ball.py b/bot/exts/halloween/8ball.py index d6c5a299..a2431190 100644 --- a/bot/exts/halloween/8ball.py +++ b/bot/exts/halloween/8ball.py @@ -10,8 +10,7 @@ from bot.bot import Bot log = logging.getLogger(__name__) -with Path("bot/resources/halloween/responses.json").open("r", encoding="utf8") as f: - RESPONSES = json.load(f) +RESPONSES = json.loads(Path("bot/resources/halloween/responses.json").read_text("utf8")) class SpookyEightBall(commands.Cog): diff --git a/bot/exts/halloween/halloween_facts.py b/bot/exts/halloween/halloween_facts.py index 3a89b5aa..98cc2db0 100644 --- a/bot/exts/halloween/halloween_facts.py +++ b/bot/exts/halloween/halloween_facts.py @@ -30,8 +30,7 @@ class HalloweenFacts(commands.Cog): """A Cog for displaying interesting facts about Halloween.""" def __init__(self): - with Path("bot/resources/halloween/halloween_facts.json").open("r", encoding="utf8") as file: - self.halloween_facts = json.load(file) + self.halloween_facts = json.loads(Path("bot/resources/halloween/halloween_facts.json").read_text("utf8")) self.facts = list(enumerate(self.halloween_facts)) def random_fact(self) -> Tuple[int, str]: diff --git a/bot/exts/halloween/halloweenify.py b/bot/exts/halloween/halloweenify.py index df55b55d..e839950a 100644 --- a/bot/exts/halloween/halloweenify.py +++ b/bot/exts/halloween/halloweenify.py @@ -1,5 +1,5 @@ import logging -from json import load +from json import loads from pathlib import Path from random import choice @@ -21,8 +21,7 @@ class Halloweenify(commands.Cog): async def halloweenify(self, ctx: commands.Context) -> None: """Change your nickname into a much spookier one!""" async with ctx.typing(): - with open(Path("bot/resources/halloween/halloweenify.json"), "r", encoding="utf8") as f: - data = load(f) + data = loads(Path("bot/resources/halloween/halloweenify.json").read_text("utf8")) # Choose a random character from our list we loaded above and set apart the nickname and image url. character = choice(data["characters"]) diff --git a/bot/exts/halloween/monsterbio.py b/bot/exts/halloween/monsterbio.py index 1aaba7bb..69e898cb 100644 --- a/bot/exts/halloween/monsterbio.py +++ b/bot/exts/halloween/monsterbio.py @@ -11,8 +11,9 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with open(Path("bot/resources/halloween/monster.json"), "r", encoding="utf8") as f: - TEXT_OPTIONS = json.load(f) # Data for a mad-lib style generation of text +TEXT_OPTIONS = json.loads( + Path("bot/resources/halloween/monster.json").read_text("utf8") +) # Data for a mad-lib style generation of text class MonsterBio(commands.Cog): diff --git a/bot/exts/halloween/monstersurvey.py b/bot/exts/halloween/monstersurvey.py index 231454ea..240a97db 100644 --- a/bot/exts/halloween/monstersurvey.py +++ b/bot/exts/halloween/monstersurvey.py @@ -26,14 +26,12 @@ class MonsterSurvey(Cog): def __init__(self): """Initializes values for the bot to use within the voting commands.""" self.registry_path = pathlib.Path("bot", "resources", "halloween", "monstersurvey.json") - with self.registry_path.open(encoding="utf8") as data: - self.voter_registry = json.load(data) + self.voter_registry = json.loads(self.registry_path.read_text("utf8")) def json_write(self) -> None: """Write voting results to a local JSON file.""" log.info("Saved Monster Survey Results") - with self.registry_path.open("w", encoding="utf8") as data: - json.dump(self.voter_registry, data, indent=2) + self.registry_path.write_text(json.dumps(self.voter_registry, indent=2)) def cast_vote(self, id: int, monster: str) -> None: """ diff --git a/bot/exts/halloween/spookynamerate.py b/bot/exts/halloween/spookynamerate.py index 87172922..63040289 100644 --- a/bot/exts/halloween/spookynamerate.py +++ b/bot/exts/halloween/spookynamerate.py @@ -371,8 +371,7 @@ class SpookyNameRate(Cog): @staticmethod def load_json(file: Path) -> Dict[str, str]: """Loads a JSON file and returns its contents.""" - with file.open("r", encoding="utf-8") as f: - return json.load(f) + return json.loads(file.read_text("utf8")) @staticmethod def in_allowed_month() -> bool: diff --git a/bot/exts/halloween/spookyrating.py b/bot/exts/halloween/spookyrating.py index 6c79fbed..105d2164 100644 --- a/bot/exts/halloween/spookyrating.py +++ b/bot/exts/halloween/spookyrating.py @@ -3,6 +3,7 @@ import json import logging import random from pathlib import Path +from typing import Dict import discord from discord.ext import commands @@ -12,9 +13,8 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with Path("bot/resources/halloween/spooky_rating.json").open(encoding="utf8") as file: - data = json.load(file) - SPOOKY_DATA = sorted((int(key), value) for key, value in data.items()) +data: Dict[str, Dict[str, str]] = json.loads(Path("bot/resources/halloween/spooky_rating.json").read_text("utf8")) +SPOOKY_DATA = sorted((int(key), value) for key, value in data.items()) class SpookyRating(commands.Cog): diff --git a/bot/exts/pride/drag_queen_name.py b/bot/exts/pride/drag_queen_name.py index d9424001..6bf43913 100644 --- a/bot/exts/pride/drag_queen_name.py +++ b/bot/exts/pride/drag_queen_name.py @@ -19,8 +19,7 @@ class DragNames(commands.Cog): @staticmethod def load_names() -> list: """Loads a list of drag queen names.""" - with Path("bot/resources/pride/drag_queen_names.json").open(encoding="utf8") as f: - return json.load(f) + return json.loads(Path("bot/resources/pride/drag_queen_names.json").read_text("utf8")) @commands.command(name="dragname", aliases=["dragqueenname", "queenme"]) async def dragname(self, ctx: commands.Context) -> None: diff --git a/bot/exts/pride/pride_anthem.py b/bot/exts/pride/pride_anthem.py index a7f8d7ef..21b7e468 100644 --- a/bot/exts/pride/pride_anthem.py +++ b/bot/exts/pride/pride_anthem.py @@ -36,9 +36,7 @@ class PrideAnthem(commands.Cog): @staticmethod def load_vids() -> list: """Loads a list of videos from the resources folder as dictionaries.""" - with open(Path("bot/resources/pride/anthems.json"), "r", encoding="utf8") as f: - anthems = json.load(f) - return anthems + return json.loads(Path("bot/resources/pride/anthems.json").read_text("utf8")) @commands.command(name="prideanthem", aliases=["anthem", "pridesong"]) async def prideanthem(self, ctx: commands.Context, genre: str = None) -> None: diff --git a/bot/exts/pride/pride_facts.py b/bot/exts/pride/pride_facts.py index 6d06cf64..47e69a03 100644 --- a/bot/exts/pride/pride_facts.py +++ b/bot/exts/pride/pride_facts.py @@ -28,8 +28,7 @@ class PrideFacts(commands.Cog): @staticmethod def load_facts() -> dict: """Loads a dictionary of years mapping to lists of facts.""" - with open(Path("bot/resources/pride/facts.json"), "r", encoding="utf8") as f: - return json.load(f) + return json.loads(Path("bot/resources/pride/facts.json").read_text("utf8")) @seasonal_task(Month.JUNE) async def send_pride_fact_daily(self) -> None: diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index d1eea388..8b522a72 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -1,6 +1,6 @@ import logging import random -from json import load +from json import loads from pathlib import Path from typing import Tuple @@ -28,9 +28,7 @@ class BeMyValentine(commands.Cog): def load_json() -> dict: """Load Valentines messages from the static resources.""" p = Path("bot/resources/valentines/bemyvalentine_valentines.json") - with p.open(encoding="utf8") as json_data: - valentines = load(json_data) - return valentines + return loads(p.read_text("utf8")) @in_month(Month.FEBRUARY) @commands.group(name="lovefest") diff --git a/bot/exts/valentines/lovecalculator.py b/bot/exts/valentines/lovecalculator.py index 8a4c71eb..b10b7bca 100644 --- a/bot/exts/valentines/lovecalculator.py +++ b/bot/exts/valentines/lovecalculator.py @@ -15,9 +15,8 @@ from bot.bot import Bot log = logging.getLogger(__name__) -with Path("bot/resources/valentines/love_matches.json").open(encoding="utf8") as file: - LOVE_DATA = json.load(file) - LOVE_DATA = sorted((int(key), value) for key, value in LOVE_DATA.items()) +LOVE_DATA = json.loads(Path("bot/resources/valentines/love_matches.json").read_text("utf8")) +LOVE_DATA = sorted((int(key), value) for key, value in LOVE_DATA.items()) class LoveCalculator(Cog): diff --git a/bot/exts/valentines/myvalenstate.py b/bot/exts/valentines/myvalenstate.py index 1c67984b..d2409dcc 100644 --- a/bot/exts/valentines/myvalenstate.py +++ b/bot/exts/valentines/myvalenstate.py @@ -12,8 +12,7 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with open(Path("bot/resources/valentines/valenstates.json"), "r", encoding="utf8") as file: - STATES = json.load(file) +STATES = json.loads(Path("bot/resources/valentines/valenstates.json").read_text("utf8")) class MyValenstate(commands.Cog): diff --git a/bot/exts/valentines/pickuplines.py b/bot/exts/valentines/pickuplines.py index 909169e6..00741a72 100644 --- a/bot/exts/valentines/pickuplines.py +++ b/bot/exts/valentines/pickuplines.py @@ -1,6 +1,6 @@ import logging import random -from json import load +from json import loads from pathlib import Path import discord @@ -11,8 +11,7 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with open(Path("bot/resources/valentines/pickup_lines.json"), "r", encoding="utf8") as f: - pickup_lines = load(f) +PICKUP_LINES = loads(Path("bot/resources/valentines/pickup_lines.json").read_text("utf8")) class PickupLine(commands.Cog): @@ -25,14 +24,14 @@ class PickupLine(commands.Cog): Note that most of them are very cheesy. """ - random_line = random.choice(pickup_lines["lines"]) + random_line = random.choice(PICKUP_LINES["lines"]) embed = discord.Embed( title=":cheese: Your pickup line :cheese:", description=random_line["line"], color=Colours.pink ) embed.set_thumbnail( - url=random_line.get("image", pickup_lines["placeholder"]) + url=random_line.get("image", PICKUP_LINES["placeholder"]) ) await ctx.send(embed=embed) diff --git a/bot/exts/valentines/savethedate.py b/bot/exts/valentines/savethedate.py index cc16f5c9..ffe559d6 100644 --- a/bot/exts/valentines/savethedate.py +++ b/bot/exts/valentines/savethedate.py @@ -1,6 +1,6 @@ import logging import random -from json import load +from json import loads from pathlib import Path import discord @@ -13,8 +13,7 @@ log = logging.getLogger(__name__) HEART_EMOJIS = [":heart:", ":gift_heart:", ":revolving_hearts:", ":sparkling_heart:", ":two_hearts:"] -with open(Path("bot/resources/valentines/date_ideas.json"), "r", encoding="utf8") as f: - VALENTINES_DATES = load(f) +VALENTINES_DATES = loads(Path("bot/resources/valentines/date_ideas.json").read_text("utf8")) class SaveTheDate(commands.Cog): diff --git a/bot/exts/valentines/valentine_zodiac.py b/bot/exts/valentines/valentine_zodiac.py index a444a355..45d1edd5 100644 --- a/bot/exts/valentines/valentine_zodiac.py +++ b/bot/exts/valentines/valentine_zodiac.py @@ -29,14 +29,14 @@ class ValentineZodiac(commands.Cog): """Load zodiac compatibility from static JSON resource.""" explanation_file = Path("bot/resources/valentines/zodiac_explanation.json") compatibility_file = Path("bot/resources/valentines/zodiac_compatibility.json") - with explanation_file.open(encoding="utf8") as json_data: - zodiac_fact = json.load(json_data) - for zodiac_data in zodiac_fact.values(): - zodiac_data["start_at"] = datetime.fromisoformat(zodiac_data["start_at"]) - zodiac_data["end_at"] = datetime.fromisoformat(zodiac_data["end_at"]) - - with compatibility_file.open(encoding="utf8") as json_data: - zodiacs = json.load(json_data) + + zodiac_fact = json.loads(explanation_file.read_text("utf8")) + + for zodiac_data in zodiac_fact.values(): + zodiac_data["start_at"] = datetime.fromisoformat(zodiac_data["start_at"]) + zodiac_data["end_at"] = datetime.fromisoformat(zodiac_data["end_at"]) + + zodiacs = json.loads(compatibility_file.read_text("utf8")) return zodiacs, zodiac_fact diff --git a/bot/exts/valentines/whoisvalentine.py b/bot/exts/valentines/whoisvalentine.py index 3f23201f..211b1f27 100644 --- a/bot/exts/valentines/whoisvalentine.py +++ b/bot/exts/valentines/whoisvalentine.py @@ -11,8 +11,7 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with open(Path("bot/resources/valentines/valentine_facts.json"), "r", encoding="utf8") as file: - FACTS = json.load(file) +FACTS = json.loads(Path("bot/resources/valentines/valentine_facts.json").read_text("utf8")) class ValentineFacts(commands.Cog): -- cgit v1.2.3 From 62345be36b0ebf8f867e0fb6597ebd5e29488d1c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 15:20:09 -0300 Subject: implement decorator-factory's changes except for the major refactoring, which would probably be in a separate pr --- bot/exts/evergreen/trivia_quiz.py | 55 ++++++++++++++++++++++----------------- 1 file changed, 31 insertions(+), 24 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index e1a06aa5..7aab8b87 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -3,8 +3,9 @@ import json import logging import operator import random +from dataclasses import dataclass from pathlib import Path -from typing import Callable, List, Optional, Tuple +from typing import Callable, List, Optional import discord from discord.ext import commands @@ -14,8 +15,6 @@ from bot.constants import Colours, NEGATIVE_REPLIES, Roles logger = logging.getLogger(__name__) -QAndA = Tuple[str, str] - DEFAULT_QUESTION_LIMIT = 6 STANDARD_VARIATION_TOLERANCE = 83 DYNAMICALLY_GEN_VARIATION_TOLERANCE = 95 @@ -62,7 +61,13 @@ UNITS_TO_BASE_UNITS = { } -def linear_system(q_format: str, a_format: str) -> QAndA: +@dataclass(frozen=True) +class QuizEntry: + question: str + answer: str + + +def linear_system(q_format: str, a_format: str) -> QuizEntry: """Generate a system of linear equations with two unknowns.""" x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) @@ -78,10 +83,10 @@ def linear_system(q_format: str, a_format: str) -> QAndA: coeffs[2] * x + coeffs[3] * y, ) - return question, answer + return QuizEntry(question, answer) -def mod_arith(q_format: str, a_format: str) -> QAndA: +def mod_arith(q_format: str, a_format: str) -> QuizEntry: """Generate a basic modular arithmetic question.""" quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) ans = random.randint(0, 9) # max remainder is 9, since the minimum modulus is 10 @@ -90,30 +95,30 @@ def mod_arith(q_format: str, a_format: str) -> QAndA: question = q_format.format(a, b, m) answer = a_format.format(ans) - return question, answer + return QuizEntry(question, answer) -def ngonal_prism(q_format: str, a_format: str) -> QAndA: +def ngonal_prism(q_format: str, a_format: str) -> QuizEntry: """Generate a question regarding vertices on n-gonal prisms.""" n = random.randint(0, len(N_PREFIXES) - 1) question = q_format.format(N_PREFIXES[n]) answer = a_format.format((n + N_PREFIX_STARTS_AT) * 2) - return question, answer + return QuizEntry(question, answer) -def imag_sqrt(q_format: str, a_format: str) -> QAndA: +def imag_sqrt(q_format: str, a_format: str) -> QuizEntry: """Generate a negative square root question.""" ans_coeff = random.randint(3, 10) question = q_format.format(ans_coeff ** 2) answer = a_format.format(ans_coeff) - return question, answer + return QuizEntry(question, answer) -def binary_calc(q_format: str, a_format: str) -> QAndA: +def binary_calc(q_format: str, a_format: str) -> QuizEntry: """Generate a binary calculation question.""" a = random.randint(15, 20) b = random.randint(10, a) @@ -133,30 +138,30 @@ def binary_calc(q_format: str, a_format: str) -> QAndA: question = q_format.format(a, oper[0], b) answer = a_format.format(oper[1](a, b)) - return question, answer + return QuizEntry(question, answer) -def solar_system(q_format: str, a_format: str) -> QAndA: +def solar_system(q_format: str, a_format: str) -> QuizEntry: """Generate a question on the planets of the Solar System.""" planet = random.choice(PLANETS) question = q_format.format(planet[0]) answer = a_format.format(planet[1]) - return question, answer + return QuizEntry(question, answer) -def taxonomic_rank(q_format: str, a_format: str) -> QAndA: +def taxonomic_rank(q_format: str, a_format: str) -> QuizEntry: """Generate a question on taxonomic classification.""" level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) question = q_format.format(TAXONOMIC_HIERARCHY[level]) answer = a_format.format(TAXONOMIC_HIERARCHY[level + 1]) - return question, answer + return QuizEntry(question, answer) -def base_units_convert(q_format: str, a_format: str) -> QAndA: +def base_units_convert(q_format: str, a_format: str) -> QuizEntry: """Generate a SI base units conversion question.""" unit = random.choice(list(UNITS_TO_BASE_UNITS)) @@ -167,7 +172,7 @@ def base_units_convert(q_format: str, a_format: str) -> QAndA: UNITS_TO_BASE_UNITS[unit][1] ) - return question, answer + return QuizEntry(question, answer) DYNAMIC_QUESTIONS_FORMAT_FUNCS = { @@ -231,7 +236,7 @@ class TriviaQuiz(commands.Cog): self.game_player_scores[ctx.channel.id] = {} # Stop game if running. - if self.game_status[ctx.channel.id] is True: + if self.game_status[ctx.channel.id]: await ctx.send( "Game is already running... " f"do `{self.bot.command_prefix}quiz stop`" @@ -318,10 +323,12 @@ class TriviaQuiz(commands.Cog): else: format_func = DYNAMIC_QUESTIONS_FORMAT_FUNCS[question_dict["dynamic_id"]] - question, answers = format_func( + quiz_entry = format_func( question_dict["question"], question_dict["answer"], ) + + question, answers = quiz_entry.question, quiz_entry.answer answers = [answers] var_tol = DYNAMICALLY_GEN_VARIATION_TOLERANCE @@ -492,7 +499,7 @@ class TriviaQuiz(commands.Cog): description="", ) - sorted_dict = sorted(player_data.items(), key=lambda a: a[1], reverse=True) + sorted_dict = sorted(player_data.items(), key=operator.itemgetter(1), reverse=True) for item in sorted_dict: embed.description += f"{item[0]}: {item[1]}\n" @@ -553,7 +560,7 @@ class TriviaQuiz(commands.Cog): q_left: int, ) -> None: """Send the correct answer of a question to the game channel.""" - info = question_dict.get("info", "") + info = question_dict.get("info") plurality = " is" if len(answers) == 1 else "s are" @@ -566,7 +573,7 @@ class TriviaQuiz(commands.Cog): description="", ) - if info != "": + if info is not None: embed.description += f"**Information**\n{info}\n\n" embed.description += ( -- cgit v1.2.3 From b090b15b4df08b7908cca6016a65802fc779cf3c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 15:23:15 -0300 Subject: add a docstring to the dataclass --- bot/exts/evergreen/trivia_quiz.py | 1 + 1 file changed, 1 insertion(+) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 7aab8b87..b5a18516 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -63,6 +63,7 @@ UNITS_TO_BASE_UNITS = { @dataclass(frozen=True) class QuizEntry: + """Dataclass for a quiz entry (a question and a string containing answers separated by commas)""" question: str answer: str -- cgit v1.2.3 From cf513ebd52cb337f760ae34e33380d1f09285c73 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 15:24:40 -0300 Subject: fix the QuizEntry dataclass --- bot/exts/evergreen/trivia_quiz.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index b5a18516..4d18eaef 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -63,7 +63,8 @@ UNITS_TO_BASE_UNITS = { @dataclass(frozen=True) class QuizEntry: - """Dataclass for a quiz entry (a question and a string containing answers separated by commas)""" + """Dataclass for a quiz entry (a question and a string containing answers separated by commas).""" + question: str answer: str -- cgit v1.2.3 From aa3a38649e465c1299f3adfc5a5e4aa6fb8102b8 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 15:27:08 -0300 Subject: delete trailing whitespace after docstring smh i have to stop making these errors lmao, definitely going to see that precommit thing after this --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 4d18eaef..6d421668 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -64,7 +64,7 @@ UNITS_TO_BASE_UNITS = { @dataclass(frozen=True) class QuizEntry: """Dataclass for a quiz entry (a question and a string containing answers separated by commas).""" - + question: str answer: str -- cgit v1.2.3 From 42002ea00706732f5a67c9bbad194c104b046f25 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Thu, 13 May 2021 17:54:49 -0400 Subject: chore: Break up the HelpSession.build_pages method --- bot/exts/evergreen/help.py | 172 +++++++++++++++++++++++---------------------- 1 file changed, 87 insertions(+), 85 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/help.py b/bot/exts/evergreen/help.py index 7e3fdad4..3c9ba4d2 100644 --- a/bot/exts/evergreen/help.py +++ b/bot/exts/evergreen/help.py @@ -287,22 +287,9 @@ class HelpSession: # Use LinePaginator to restrict embed line height paginator = LinePaginator(prefix="", suffix="", max_lines=self._max_lines) - prefix = constants.Client.prefix - # show signature if query is a command if isinstance(self.query, commands.Command): - signature = self._get_command_params(self.query) - parent = self.query.full_parent_name + " " if self.query.parent else "" - paginator.add_line(f"**```{prefix}{parent}{signature}```**") - - aliases = [f"`{alias}`" if not parent else f"`{parent} {alias}`" for alias in self.query.aliases] - aliases += [f"`{alias}`" for alias in getattr(self.query, "root_aliases", ())] - aliases = ", ".join(sorted(aliases)) - if aliases: - paginator.add_line(f"**Can also use:** {aliases}\n") - - if not await self.query.can_run(self._ctx): - paginator.add_line("***You cannot run this command.***\n") + await self._add_command_signature(paginator) if isinstance(self.query, Cog): paginator.add_line(f"**{self.query.name}**") @@ -312,97 +299,112 @@ class HelpSession: # list all children commands of the queried object if isinstance(self.query, (commands.GroupMixin, Cog)): + await self._list_child_commands(paginator) - # remove hidden commands if session is not wanting hiddens - if not self._show_hidden: - filtered = [c for c in self.query.commands if not c.hidden] - else: - filtered = self.query.commands - - # if after filter there are no commands, finish up - if not filtered: - self._pages = paginator.pages - return - - if isinstance(self.query, Cog): - grouped = (("**Commands:**", self.query.commands),) - - elif isinstance(self.query, commands.Command): - grouped = (("**Subcommands:**", self.query.commands),) - - # don't show prefix for subcommands - prefix = "" + self._pages = paginator.pages - # otherwise sort and organise all commands into categories - else: - cat_sort = sorted(filtered, key=self._category_key) - grouped = itertools.groupby(cat_sort, key=self._category_key) + async def _add_command_signature(self, paginator: LinePaginator) -> None: + prefix = constants.Client.prefix - for category, cmds in grouped: - cmds = sorted(cmds, key=lambda c: c.name) + signature = self._get_command_params(self.query) + parent = self.query.full_parent_name + " " if self.query.parent else "" + paginator.add_line(f"**```{prefix}{parent}{signature}```**") + aliases = [f"`{alias}`" if not parent else f"`{parent} {alias}`" for alias in self.query.aliases] + aliases += [f"`{alias}`" for alias in getattr(self.query, "root_aliases", ())] + aliases = ", ".join(sorted(aliases)) + if aliases: + paginator.add_line(f"**Can also use:** {aliases}\n") + if not await self.query.can_run(self._ctx): + paginator.add_line("***You cannot run this command.***\n") + + async def _list_child_commands(self, paginator: LinePaginator) -> None: + # remove hidden commands if session is not wanting hiddens + if not self._show_hidden: + filtered = [c for c in self.query.commands if not c.hidden] + else: + filtered = self.query.commands - if len(cmds) == 0: - continue + # if after filter there are no commands, finish up + if not filtered: + self._pages = paginator.pages + return - cat_cmds = [] + if isinstance(self.query, Cog): + grouped = (("**Commands:**", self.query.commands),) - for command in cmds: + elif isinstance(self.query, commands.Command): + grouped = (("**Subcommands:**", self.query.commands),) - # skip if hidden and hide if session is set to - if command.hidden and not self._show_hidden: - continue + # otherwise sort and organise all commands into categories + else: + cat_sort = sorted(filtered, key=self._category_key) + grouped = itertools.groupby(cat_sort, key=self._category_key) - # see if the user can run the command - strikeout = "" + for category, cmds in grouped: + await self._format_command_category(paginator, category, list(cmds)) - # Patch to make the !help command work outside of #bot-commands again - # This probably needs a proper rewrite, but this will make it work in - # the mean time. - try: - can_run = await command.can_run(self._ctx) - except CheckFailure: - can_run = False + async def _format_command_category(self, paginator: LinePaginator, category: str, cmds: List[Command]) -> None: + cmds = sorted(cmds, key=lambda c: c.name) + cat_cmds = [] + for command in cmds: + cat_cmds += await self._format_command(command) - if not can_run: - # skip if we don't show commands they can't run - if self._only_can_run: - continue - strikeout = "~~" + # state var for if the category should be added next + print_cat = 1 + new_page = True - signature = self._get_command_params(command) - info = f"{strikeout}**`{prefix}{signature}`**{strikeout}" + for details in cat_cmds: - # handle if the command has no docstring - if command.short_doc: - cat_cmds.append(f"{info}\n*{command.short_doc}*") - else: - cat_cmds.append(f"{info}\n*No details provided.*") + # keep details together, paginating early if it won"t fit + lines_adding = len(details.split("\n")) + print_cat + if paginator._linecount + lines_adding > self._max_lines: + paginator._linecount = 0 + new_page = True + paginator.close_page() - # state var for if the category should be added next + # new page so print category title again print_cat = 1 - new_page = True - for details in cat_cmds: + if print_cat: + if new_page: + paginator.add_line("") + paginator.add_line(category) + print_cat = 0 - # keep details together, paginating early if it won't fit - lines_adding = len(details.split("\n")) + print_cat - if paginator._linecount + lines_adding > self._max_lines: - paginator._linecount = 0 - new_page = True - paginator.close_page() + paginator.add_line(details) - # new page so print category title again - print_cat = 1 + async def _format_command(self, command: Command) -> List[str]: + # skip if hidden and hide if session is set to + if command.hidden and not self._show_hidden: + return [] - if print_cat: - if new_page: - paginator.add_line("") - paginator.add_line(category) - print_cat = 0 + # Patch to make the !help command work outside of #bot-commands again + # This probably needs a proper rewrite, but this will make it work in + # the mean time. + try: + can_run = await command.can_run(self._ctx) + except CheckFailure: + can_run = False + + # see if the user can run the command + strikeout = "" + if not can_run: + # skip if we don't show commands they can't run + if self._only_can_run: + return [] + strikeout = "~~" - paginator.add_line(details) + if isinstance(self.query, commands.Command): + prefix = "" + else: + prefix = constants.Client.prefix - self._pages = paginator.pages + signature = self._get_command_params(command) + info = f"{strikeout}**`{prefix}{signature}`**{strikeout}" + + # handle if the command has no docstring + short_doc = command.short_doc or "No details provided" + return [f"{info}\n*{short_doc}*"] def embed_page(self, page_number: int = 0) -> Embed: """Returns an Embed with the requested page formatted within.""" -- cgit v1.2.3 From 92c33d625068b9b39564dbf4fb9f6c1102711955 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Fri, 14 May 2021 12:34:30 -0400 Subject: chore: Refactor more code to follow our style guide --- bot/exts/evergreen/avatar_modification/_effects.py | 6 +- bot/exts/evergreen/connect_four.py | 70 +++++++++++----------- bot/exts/evergreen/game.py | 6 +- bot/exts/evergreen/issues.py | 16 ++--- bot/exts/evergreen/minesweeper.py | 12 ++-- bot/exts/evergreen/movie.py | 6 +- bot/exts/evergreen/snakes/_snakes_cog.py | 10 +++- bot/exts/evergreen/snakes/_utils.py | 16 ++--- bot/exts/evergreen/wolfram.py | 16 +++-- bot/exts/halloween/candy_collection.py | 8 ++- bot/exts/halloween/monstersurvey.py | 23 +++---- bot/exts/valentines/movie_generator.py | 6 +- bot/utils/__init__.py | 11 +++- bot/utils/checks.py | 30 ++++++---- 14 files changed, 136 insertions(+), 100 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/avatar_modification/_effects.py b/bot/exts/evergreen/avatar_modification/_effects.py index d2370b4b..9339ecc4 100644 --- a/bot/exts/evergreen/avatar_modification/_effects.py +++ b/bot/exts/evergreen/avatar_modification/_effects.py @@ -251,7 +251,7 @@ class PfpEffects: total_width = multiplier * single_wdith total_height = multiplier * single_height - new_image = Image.new('RGBA', (total_width, total_height), (250, 250, 250)) + new_image = Image.new("RGBA", (total_width, total_height), (250, 250, 250)) width_multiplier = 0 height = 0 @@ -275,13 +275,13 @@ class PfpEffects: def mosaic_effect(img_bytes: bytes, squares: int, file_name: str) -> discord.File: """Seperate function run from an executor which turns an image into a mosaic.""" avatar = Image.open(BytesIO(img_bytes)) - avatar = avatar.convert('RGBA').resize((1024, 1024)) + avatar = avatar.convert("RGBA").resize((1024, 1024)) img_squares = PfpEffects.split_image(avatar, squares) new_img = PfpEffects.join_images(img_squares) bufferedio = BytesIO() - new_img.save(bufferedio, format='PNG') + new_img.save(bufferedio, format="PNG") bufferedio.seek(0) return discord.File(bufferedio, filename=file_name) diff --git a/bot/exts/evergreen/connect_four.py b/bot/exts/evergreen/connect_four.py index dc365a70..7a39d442 100644 --- a/bot/exts/evergreen/connect_four.py +++ b/bot/exts/evergreen/connect_four.py @@ -22,13 +22,13 @@ class Game: """A Connect 4 Game.""" def __init__( - self, - bot: Bot, - channel: discord.TextChannel, - player1: discord.Member, - player2: typing.Optional[discord.Member], - tokens: typing.List[str], - size: int = 7 + self, + bot: Bot, + channel: discord.TextChannel, + player1: discord.Member, + player2: typing.Optional[discord.Member], + tokens: typing.List[str], + size: int = 7 ) -> None: self.bot = bot @@ -286,20 +286,20 @@ class ConnectFour(commands.Cog): return True def get_player( - self, - ctx: commands.Context, - announcement: discord.Message, - reaction: discord.Reaction, - user: discord.Member + self, + ctx: commands.Context, + announcement: discord.Message, + reaction: discord.Reaction, + user: discord.Member ) -> bool: """Predicate checking the criteria for the announcement message.""" if self.already_playing(ctx.author): # If they've joined a game since requesting a player 2 return True # Is dealt with later on if ( - user.id not in (ctx.me.id, ctx.author.id) - and str(reaction.emoji) == Emojis.hand_raised - and reaction.message.id == announcement.id + user.id not in (ctx.me.id, ctx.author.id) + and str(reaction.emoji) == Emojis.hand_raised + and reaction.message.id == announcement.id ): if self.already_playing(user): self.bot.loop.create_task(ctx.send(f"{user.mention} You're already playing a game!")) @@ -316,9 +316,9 @@ class ConnectFour(commands.Cog): return True if ( - user.id == ctx.author.id - and str(reaction.emoji) == CROSS_EMOJI - and reaction.message.id == announcement.id + user.id == ctx.author.id + and str(reaction.emoji) == CROSS_EMOJI + and reaction.message.id == announcement.id ): return True return False @@ -329,7 +329,7 @@ class ConnectFour(commands.Cog): @staticmethod def check_emojis( - e1: EMOJI_CHECK, e2: EMOJI_CHECK + e1: EMOJI_CHECK, e2: EMOJI_CHECK ) -> typing.Tuple[bool, typing.Optional[str]]: """Validate the emojis, the user put.""" if isinstance(e1, str) and emojis.count(e1) != 1: @@ -339,12 +339,12 @@ class ConnectFour(commands.Cog): return True, None async def _play_game( - self, - ctx: commands.Context, - user: typing.Optional[discord.Member], - board_size: int, - emoji1: str, - emoji2: str + self, + ctx: commands.Context, + user: typing.Optional[discord.Member], + board_size: int, + emoji1: str, + emoji2: str ) -> None: """Helper for playing a game of connect four.""" self.tokens = [":white_circle:", str(emoji1), str(emoji2)] @@ -369,11 +369,11 @@ class ConnectFour(commands.Cog): case_insensitive=True ) async def connect_four( - self, - ctx: commands.Context, - board_size: int = 7, - emoji1: EMOJI_CHECK = "\U0001f535", - emoji2: EMOJI_CHECK = "\U0001f534" + self, + ctx: commands.Context, + board_size: int = 7, + emoji1: EMOJI_CHECK = "\U0001f535", + emoji2: EMOJI_CHECK = "\U0001f534" ) -> None: """ Play the classic game of Connect Four with someone! @@ -430,11 +430,11 @@ class ConnectFour(commands.Cog): @guild_only() @connect_four.command(aliases=["bot", "computer", "cpu"]) async def ai( - self, - ctx: commands.Context, - board_size: int = 7, - emoji1: EMOJI_CHECK = "\U0001f535", - emoji2: EMOJI_CHECK = "\U0001f534" + self, + ctx: commands.Context, + board_size: int = 7, + emoji1: EMOJI_CHECK = "\U0001f535", + emoji2: EMOJI_CHECK = "\U0001f534" ) -> None: """Play Connect Four against a computer player.""" check, emoji = self.check_emojis(emoji1, emoji2) diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 6f01d81c..43f64be7 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -374,8 +374,10 @@ class Games(Cog): release_date = dt.utcfromtimestamp(data["first_release_date"]).date() if "first_release_date" in data else "?" # Create Age Ratings value - rating = ", ".join(f"{AgeRatingCategories(age['category']).name} {AgeRatings(age['rating']).name}" - for age in data["age_ratings"]) if "age_ratings" in data else "?" + rating = ", ".join( + f"{AgeRatingCategories(age['category']).name} {AgeRatings(age['rating']).name}" + for age in data["age_ratings"] + ) if "age_ratings" in data else "?" companies = [c["company"]["name"] for c in data["involved_companies"]] if "involved_companies" in data else "?" diff --git a/bot/exts/evergreen/issues.py b/bot/exts/evergreen/issues.py index 5bbc57c6..b67aa4a6 100644 --- a/bot/exts/evergreen/issues.py +++ b/bot/exts/evergreen/issues.py @@ -162,9 +162,9 @@ class Issues(commands.Cog): @staticmethod def format_embed( - results: t.List[t.Union[IssueState, FetchError]], - user: str, - repository: t.Optional[str] = None + results: t.List[t.Union[IssueState, FetchError]], + user: str, + repository: t.Optional[str] = None ) -> discord.Embed: """Take a list of IssueState or FetchError and format a Discord embed for them.""" description_list = [] @@ -187,11 +187,11 @@ class Issues(commands.Cog): @whitelist_override(channels=WHITELISTED_CHANNELS, categories=WHITELISTED_CATEGORIES) @commands.command(aliases=("pr",)) async def issue( - self, - ctx: commands.Context, - numbers: commands.Greedy[int], - repository: str = "sir-lancebot", - user: str = "python-discord" + self, + ctx: commands.Context, + numbers: commands.Greedy[int], + repository: str = "sir-lancebot", + user: str = "python-discord" ) -> None: """Command to retrieve issue(s) from a GitHub repository.""" # Remove duplicates diff --git a/bot/exts/evergreen/minesweeper.py b/bot/exts/evergreen/minesweeper.py index 7a31dfde..932358f9 100644 --- a/bot/exts/evergreen/minesweeper.py +++ b/bot/exts/evergreen/minesweeper.py @@ -212,12 +212,12 @@ class Minesweeper(commands.Cog): return True async def reveal_one( - self, - ctx: commands.Context, - revealed: GameBoard, - board: GameBoard, - x: int, - y: int + self, + ctx: commands.Context, + revealed: GameBoard, + board: GameBoard, + x: int, + y: int ) -> bool: """ Reveal one square. diff --git a/bot/exts/evergreen/movie.py b/bot/exts/evergreen/movie.py index fa284417..ff23df4c 100644 --- a/bot/exts/evergreen/movie.py +++ b/bot/exts/evergreen/movie.py @@ -79,8 +79,10 @@ class Movie(Cog): # Check if "results" is in result. If not, throw error. if "results" not in result: - err_msg = f"There is problem while making TMDB API request. Response Code: {result['status_code']}, " \ - f"{result['status_message']}." + err_msg = ( + f"There is problem while making TMDB API request. Response Code: {result['status_code']}, " + f"{result['status_message']}." + ) await ctx.send(err_msg) logger.warning(err_msg) diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index c50b23c5..07d3c363 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -579,9 +579,13 @@ class Snakes(Cog): antidote_embed = Embed(color=SNAKE_COLOR, title="Antidote") antidote_embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url) antidote_embed.set_image(url="https://media.giphy.com/media/ceeN6U57leAhi/giphy.gif") - antidote_embed.add_field(name=EMPTY_UNICODE, - value=f"Sorry you didnt make the antidote in time.\n" - f"The formula was {' '.join(antidote_answer)}") + antidote_embed.add_field( + name=EMPTY_UNICODE, + value=( + f"Sorry you didnt make the antidote in time.\n" + f"The formula was {' '.join(antidote_answer)}" + ) + ) await board_id.edit(embed=antidote_embed) log.debug("Ending pagination and removing all reactions...") diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index 8b39f217..0a5894b7 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -17,38 +17,38 @@ from bot.constants import Roles SNAKE_RESOURCES = Path("bot/resources/snakes").absolute() -h1 = r'''``` +h1 = r"""``` ---- ------ /--------\ |--------| |--------| \------/ - ----```''' -h2 = r'''``` + ----```""" +h2 = r"""``` ---- ------ /---\-/--\ |-----\--| |--------| \------/ - ----```''' -h3 = r'''``` + ----```""" +h3 = r"""``` ---- ------ /---\-/--\ |-----\--| |-----/--| \----\-/ - ----```''' -h4 = r'''``` + ----```""" +h4 = r"""``` ----- ----- \ /--| /---\ |--\ -\---| |--\--/-- / \------- / - ------```''' + ------```""" stages = [h1, h2, h3, h4] snakes = { "Baby Python": "https://i.imgur.com/SYOcmSa.png", diff --git a/bot/exts/evergreen/wolfram.py b/bot/exts/evergreen/wolfram.py index ca7d8454..d23afd6f 100644 --- a/bot/exts/evergreen/wolfram.py +++ b/bot/exts/evergreen/wolfram.py @@ -40,9 +40,11 @@ async def send_embed( """Generate & send a response embed with Wolfram as the author.""" embed = Embed(colour=colour) embed.description = message_txt - embed.set_author(name="Wolfram Alpha", - icon_url=WOLF_IMAGE, - url="https://www.wolframalpha.com/") + embed.set_author( + name="Wolfram Alpha", + icon_url=WOLF_IMAGE, + url="https://www.wolframalpha.com/" + ) if footer: embed.set_footer(text=footer) @@ -222,9 +224,11 @@ class Wolfram(Cog): return embed = Embed() - embed.set_author(name="Wolfram Alpha", - icon_url=WOLF_IMAGE, - url="https://www.wolframalpha.com/") + embed.set_author( + name="Wolfram Alpha", + icon_url=WOLF_IMAGE, + url="https://www.wolframalpha.com/" + ) embed.colour = Colours.soft_orange await ImagePaginator.paginate(pages, ctx, embed) diff --git a/bot/exts/halloween/candy_collection.py b/bot/exts/halloween/candy_collection.py index 14efa1fb..4afd5913 100644 --- a/bot/exts/halloween/candy_collection.py +++ b/bot/exts/halloween/candy_collection.py @@ -155,8 +155,12 @@ class CandyCollection(commands.Cog): ) -> None: """An alternative spooky message sent when user has no candies in the collection.""" embed = discord.Embed(color=author.color) - embed.set_author(name="Ghosts and Ghouls and Jack o' lanterns at night; " - "I tried to take your candies but you had none to begin with!") + embed.set_author( + name=( + "Ghosts and Ghouls and Jack o' lanterns at night; " + "I tried to take your candies but you had none to begin with!" + ) + ) await channel.send(embed=embed) @in_month(Month.OCTOBER) diff --git a/bot/exts/halloween/monstersurvey.py b/bot/exts/halloween/monstersurvey.py index 240a97db..96cda11e 100644 --- a/bot/exts/halloween/monstersurvey.py +++ b/bot/exts/halloween/monstersurvey.py @@ -71,7 +71,8 @@ class MonsterSurvey(Cog): default_embed.add_field( name=".monster show monster_name(optional)", value="Show a specific monster. If none is listed, it will give you an error with valid choices.", - inline=False) + inline=False + ) default_embed.add_field( name=".monster vote monster_name", value="Vote for a specific monster. You get one vote, but can change it at any time.", @@ -182,15 +183,17 @@ class MonsterSurvey(Cog): for rank, m in enumerate(top): votes = len(vr[m]["votes"]) percentage = ((votes / total_votes) * 100) if total_votes > 0 else 0 - embed.add_field(name=f"{rank+1}. {vr[m]['full_name']}", - value=( - f"{votes} votes. {percentage:.1f}% of total votes.\n" - f"Vote for this monster by typing " - f"'.monster vote {m}'\n" - f"Get more information on this monster by typing " - f"'.monster show {m}'" - ), - inline=False) + embed.add_field( + name=f"{rank+1}. {vr[m]['full_name']}", + value=( + f"{votes} votes. {percentage:.1f}% of total votes.\n" + f"Vote for this monster by typing " + f"'.monster vote {m}'\n" + f"Get more information on this monster by typing " + f"'.monster show {m}'" + ), + inline=False + ) embed.set_footer(text="You can also vote by their rank number. '.monster vote {number}' ") diff --git a/bot/exts/valentines/movie_generator.py b/bot/exts/valentines/movie_generator.py index 4508c3b2..0fc5edb4 100644 --- a/bot/exts/valentines/movie_generator.py +++ b/bot/exts/valentines/movie_generator.py @@ -54,8 +54,10 @@ class RomanceMovieFinder(commands.Cog): embed.set_thumbnail(url="https://i.imgur.com/LtFtC8H.png") await ctx.send(embed=embed) except KeyError: - warning_message = "A KeyError was raised while fetching information on the movie. The API service" \ - " could be unavailable or the API key could be set incorrectly." + warning_message = ( + "A KeyError was raised while fetching information on the movie. The API service" + " could be unavailable or the API key could be set incorrectly." + ) embed = discord.Embed(title=warning_message) log.warning(warning_message) await ctx.send(embed=embed) diff --git a/bot/utils/__init__.py b/bot/utils/__init__.py index 09a4dfc3..a1985019 100644 --- a/bot/utils/__init__.py +++ b/bot/utils/__init__.py @@ -3,7 +3,7 @@ import contextlib import re import string from datetime import datetime -from typing import Iterable, List +from typing import Iterable, List, Optional import discord from discord.ext.commands import BadArgument, Context @@ -31,8 +31,13 @@ def resolve_current_month() -> Month: async def disambiguate( - ctx: Context, entries: List[str], *, timeout: float = 30, - entries_per_page: int = 20, empty: bool = False, embed: discord.Embed = None + ctx: Context, + entries: List[str], + *, + timeout: float = 30, + entries_per_page: int = 20, + empty: bool = False, + embed: Optional[discord.Embed] = None ) -> str: """ Has the user choose between multiple entries in case one could not be chosen automatically. diff --git a/bot/utils/checks.py b/bot/utils/checks.py index 3783dd38..c06b6870 100644 --- a/bot/utils/checks.py +++ b/bot/utils/checks.py @@ -92,8 +92,10 @@ def in_whitelist_check( def with_role_check(ctx: Context, *role_ids: int) -> bool: """Returns True if the user has any one of the roles in role_ids.""" if not ctx.guild: # Return False in a DM - log.trace(f"{ctx.author} tried to use the '{ctx.command.name}'command from a DM. " - "This command is restricted by the with_role decorator. Rejecting request.") + log.trace( + f"{ctx.author} tried to use the '{ctx.command.name}'command from a DM. " + "This command is restricted by the with_role decorator. Rejecting request." + ) return False for role in ctx.author.roles: @@ -101,22 +103,28 @@ def with_role_check(ctx: Context, *role_ids: int) -> bool: log.trace(f"{ctx.author} has the '{role.name}' role, and passes the check.") return True - log.trace(f"{ctx.author} does not have the required role to use " - f"the '{ctx.command.name}' command, so the request is rejected.") + log.trace( + f"{ctx.author} does not have the required role to use " + f"the '{ctx.command.name}' command, so the request is rejected." + ) return False def without_role_check(ctx: Context, *role_ids: int) -> bool: """Returns True if the user does not have any of the roles in role_ids.""" if not ctx.guild: # Return False in a DM - log.trace(f"{ctx.author} tried to use the '{ctx.command.name}' command from a DM. " - "This command is restricted by the without_role decorator. Rejecting request.") + log.trace( + f"{ctx.author} tried to use the '{ctx.command.name}' command from a DM. " + "This command is restricted by the without_role decorator. Rejecting request." + ) return False author_roles = [role.id for role in ctx.author.roles] check = all(role not in author_roles for role in role_ids) - log.trace(f"{ctx.author} tried to call the '{ctx.command.name}' command. " - f"The result of the without_role check was {check}.") + log.trace( + f"{ctx.author} tried to call the '{ctx.command.name}' command. " + f"The result of the without_role check was {check}." + ) return check @@ -154,8 +162,10 @@ def cooldown_with_role_bypass(rate: int, per: float, type: BucketType = BucketTy # # If the `before_invoke` detail is ever a problem then I can quickly just swap over. if not isinstance(command, Command): - raise TypeError("Decorator `cooldown_with_role_bypass` must be applied after the command decorator. " - "This means it has to be above the command decorator in the code.") + raise TypeError( + "Decorator `cooldown_with_role_bypass` must be applied after the command decorator. " + "This means it has to be above the command decorator in the code." + ) command._before_invoke = predicate -- cgit v1.2.3 From 95e3bcbee2a68b1379b35c74872df70977cae592 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 15 May 2021 11:43:11 -0400 Subject: chore: Remove redundant f-strings --- bot/exts/christmas/advent_of_code/_cog.py | 2 +- bot/exts/christmas/hanukkah_embed.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index ce6a4cb6..ead84544 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -115,7 +115,7 @@ class AdventOfCode(commands.Cog): delta_str = f"{delta.days} days" await ctx.send( - f"The Advent of Code event is not currently running. " + "The Advent of Code event is not currently running. " f"The next event will start in {delta_str}." ) return diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index af5cfccf..77ef4684 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -67,14 +67,14 @@ class HanukkahEmbed(commands.Cog): hanukkah_start_hour = 18 if hours < hanukkah_start_hour: embed.description = ( - f"Hanukkah hasnt started yet, " + "Hanukkah hasnt started yet, " f"it will start in about {hanukkah_start_hour - hours} hour/s." ) await ctx.send(embed=embed) return elif hours > hanukkah_start_hour: embed.description = ( - f"It is the starting day of Hanukkah ! " + "It is the starting day of Hanukkah ! " f"Its been {hours - hanukkah_start_hour} hours hanukkah started !" ) await ctx.send(embed=embed) -- cgit v1.2.3 From c09ab5c5b8a2d682c320229271e75f21d7b33256 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 15 May 2021 11:57:14 -0400 Subject: chore: Reformat bot/utils/__init__.py --- bot/utils/__init__.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'bot') diff --git a/bot/utils/__init__.py b/bot/utils/__init__.py index a1985019..bef12d25 100644 --- a/bot/utils/__init__.py +++ b/bot/utils/__init__.py @@ -56,17 +56,21 @@ async def disambiguate( choices = (f"{index}: {entry}" for index, entry in enumerate(entries, start=1)) def check(message: discord.Message) -> bool: - return (message.content.isdecimal() - and message.author == ctx.author - and message.channel == ctx.channel) + return ( + message.content.isdecimal() + and message.author == ctx.author + and message.channel == ctx.channel + ) try: if embed is None: embed = discord.Embed() coro1 = ctx.bot.wait_for("message", check=check, timeout=timeout) - coro2 = LinePaginator.paginate(choices, ctx, embed=embed, max_lines=entries_per_page, - empty=empty, max_size=6000, timeout=9000) + coro2 = LinePaginator.paginate( + choices, ctx, embed=embed, max_lines=entries_per_page, + empty=empty, max_size=6000, timeout=9000 + ) # wait_for timeout will go to except instead of the wait_for thing as I expected futures = [asyncio.ensure_future(coro1), asyncio.ensure_future(coro2)] @@ -102,7 +106,7 @@ async def disambiguate( def replace_many( - sentence: str, replacements: dict, *, ignore_case: bool = False, match_case: bool = False + sentence: str, replacements: dict, *, ignore_case: bool = False, match_case: bool = False ) -> str: """ Replaces multiple substrings in a string given a mapping of strings. -- cgit v1.2.3 From e1361d03fac450365d4bdc8d10d8bcf2c99b479f Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 15 May 2021 12:32:10 -0400 Subject: chore: Update myvalenstate.py Removes a redundant f string, and when is one leftover match, get the first item of the match list instead of having [''] --- bot/exts/valentines/myvalenstate.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'bot') diff --git a/bot/exts/valentines/myvalenstate.py b/bot/exts/valentines/myvalenstate.py index d2409dcc..c699de94 100644 --- a/bot/exts/valentines/myvalenstate.py +++ b/bot/exts/valentines/myvalenstate.py @@ -61,8 +61,7 @@ class MyValenstate(commands.Cog): embed_text = f"You have {len(matches)} more matches, these being {leftovers}." elif len(matches) == 1: embed_title = "But there's another one!" - leftovers = str(matches) - embed_text = f"You have another match, this being {leftovers}." + embed_text = f"You have another match, this being {matches[0]}." else: embed_title = "You have a true match!" embed_text = "This state is your true Valenstate! There are no states that would suit" \ @@ -70,7 +69,7 @@ class MyValenstate(commands.Cog): embed = discord.Embed( title=f"Your Valenstate is {valenstate} \u2764", - description=f"{STATES[valenstate]['text']}", + description=STATES[valenstate]['text'], colour=Colours.pink ) embed.add_field(name=embed_title, value=embed_text) -- cgit v1.2.3 From 55d472a97efea392b4eb2b198ffa6f5f5026072d Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 15 May 2021 12:53:00 -0400 Subject: chore: Make all aliases in commands tuples --- bot/exts/christmas/hanukkah_embed.py | 2 +- bot/exts/easter/earth_photos.py | 2 +- bot/exts/easter/easter_riddle.py | 2 +- bot/exts/easter/egg_decorating.py | 2 +- bot/exts/easter/egg_facts.py | 2 +- bot/exts/easter/egghead_quiz.py | 2 +- bot/exts/evergreen/battleship.py | 2 +- bot/exts/evergreen/catify.py | 2 +- bot/exts/evergreen/connect_four.py | 4 ++-- bot/exts/evergreen/game.py | 12 ++++++------ bot/exts/evergreen/movie.py | 4 ++-- bot/exts/evergreen/pythonfacts.py | 2 +- bot/exts/evergreen/recommend_game.py | 2 +- bot/exts/evergreen/space.py | 2 +- bot/exts/evergreen/timed.py | 2 +- bot/exts/evergreen/trivia_quiz.py | 2 +- bot/exts/evergreen/wikipedia.py | 2 +- bot/exts/evergreen/wonder_twins.py | 2 +- bot/exts/halloween/spookynamerate.py | 4 ++-- bot/exts/pride/drag_queen_name.py | 2 +- bot/exts/pride/pride_anthem.py | 2 +- bot/exts/pride/pride_facts.py | 2 +- bot/exts/valentines/valentine_zodiac.py | 2 +- 23 files changed, 31 insertions(+), 31 deletions(-) (limited to 'bot') diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index 77ef4684..7a06b558 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -38,7 +38,7 @@ class HanukkahEmbed(commands.Cog): return hanukkah_dates @in_month(Month.DECEMBER) - @commands.command(name="hanukkah", aliases=["chanukah"]) + @commands.command(name="hanukkah", aliases=("chanukah",)) async def hanukkah_festival(self, ctx: commands.Context) -> None: """Tells you about the Hanukkah Festivaltime of festival, festival day, etc).""" hanukkah_dates = await self.get_hanukkah_dates() diff --git a/bot/exts/easter/earth_photos.py b/bot/exts/easter/earth_photos.py index 0e82e99a..9df4f9ca 100644 --- a/bot/exts/easter/earth_photos.py +++ b/bot/exts/easter/earth_photos.py @@ -16,7 +16,7 @@ class EarthPhotos(commands.Cog): def __init__(self, bot: Bot): self.bot = bot - @commands.command(aliases=["earth"]) + @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(): diff --git a/bot/exts/easter/easter_riddle.py b/bot/exts/easter/easter_riddle.py index 01b956f1..a87f93d1 100644 --- a/bot/exts/easter/easter_riddle.py +++ b/bot/exts/easter/easter_riddle.py @@ -26,7 +26,7 @@ class EasterRiddle(commands.Cog): 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. diff --git a/bot/exts/easter/egg_decorating.py b/bot/exts/easter/egg_decorating.py index 7448f702..d4b27b20 100644 --- a/bot/exts/easter/egg_decorating.py +++ b/bot/exts/easter/egg_decorating.py @@ -41,7 +41,7 @@ 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]: diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index c1c43f80..d60032f0 100644 --- a/bot/exts/easter/egg_facts.py +++ b/bot/exts/easter/egg_facts.py @@ -40,7 +40,7 @@ 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() diff --git a/bot/exts/easter/egghead_quiz.py b/bot/exts/easter/egghead_quiz.py index 4b67310f..7c4960cd 100644 --- a/bot/exts/easter/egghead_quiz.py +++ b/bot/exts/easter/egghead_quiz.py @@ -34,7 +34,7 @@ class EggheadQuiz(commands.Cog): 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. diff --git a/bot/exts/evergreen/battleship.py b/bot/exts/evergreen/battleship.py index d4584ae8..27c50bdb 100644 --- a/bot/exts/evergreen/battleship.py +++ b/bot/exts/evergreen/battleship.py @@ -434,7 +434,7 @@ class Battleship(commands.Cog): self.games.remove(game) raise - @battleship.command(name="ships", aliases=["boats"]) + @battleship.command(name="ships", aliases=("boats",)) async def battleship_ships(self, ctx: commands.Context) -> None: """Lists the ships that are found on the battleship grid.""" embed = discord.Embed(colour=Colours.blue) diff --git a/bot/exts/evergreen/catify.py b/bot/exts/evergreen/catify.py index 3182f69e..32dfae09 100644 --- a/bot/exts/evergreen/catify.py +++ b/bot/exts/evergreen/catify.py @@ -13,7 +13,7 @@ from bot.utils import helpers class Catify(commands.Cog): """Cog for the catify command.""" - @commands.command(aliases=["ᓚᘏᗢify", "ᓚᘏᗢ"]) + @commands.command(aliases=("ᓚᘏᗢify", "ᓚᘏᗢ")) @commands.cooldown(1, 5, commands.BucketType.user) async def catify(self, ctx: commands.Context, *, text: Optional[str]) -> None: """ diff --git a/bot/exts/evergreen/connect_four.py b/bot/exts/evergreen/connect_four.py index 7a39d442..5c82ffee 100644 --- a/bot/exts/evergreen/connect_four.py +++ b/bot/exts/evergreen/connect_four.py @@ -365,7 +365,7 @@ class ConnectFour(commands.Cog): @guild_only() @commands.group( invoke_without_command=True, - aliases=["4inarow", "connect4", "connectfour", "c4"], + aliases=("4inarow", "connect4", "connectfour", "c4"), case_insensitive=True ) async def connect_four( @@ -428,7 +428,7 @@ class ConnectFour(commands.Cog): await self._play_game(ctx, user, board_size, str(emoji1), str(emoji2)) @guild_only() - @connect_four.command(aliases=["bot", "computer", "cpu"]) + @connect_four.command(aliases=("bot", "computer", "cpu")) async def ai( self, ctx: commands.Context, diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 43f64be7..32fe9263 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -224,7 +224,7 @@ class Games(Cog): else: self.genres[genre_name] = genre - @group(name="games", aliases=["game"], invoke_without_command=True) + @group(name="games", aliases=("game",), invoke_without_command=True) async def games(self, ctx: Context, amount: Optional[int] = 5, *, genre: Optional[str]) -> None: """ Get random game(s) by genre from IGDB. Use .games genres command to get all available genres. @@ -277,7 +277,7 @@ class Games(Cog): await ImagePaginator.paginate(pages, ctx, Embed(title=f"Random {genre.title()} Games")) - @games.command(name="top", aliases=["t"]) + @games.command(name="top", aliases=("t",)) async def top(self, ctx: Context, amount: int = 10) -> None: """ Get current Top games in IGDB. @@ -294,19 +294,19 @@ class Games(Cog): pages = [await self.create_page(game) for game in games] await ImagePaginator.paginate(pages, ctx, Embed(title=f"Top {amount} Games")) - @games.command(name="genres", aliases=["genre", "g"]) + @games.command(name="genres", aliases=("genre", "g")) async def genres(self, ctx: Context) -> None: """Get all available genres.""" await ctx.send(f"Currently available genres: {', '.join(f'`{genre}`' for genre in self.genres)}") - @games.command(name="search", aliases=["s"]) + @games.command(name="search", aliases=("s",)) async def search(self, ctx: Context, *, search_term: str) -> None: """Find games by name.""" lines = await self.search_games(search_term) await LinePaginator.paginate(lines, ctx, Embed(title=f"Game Search Results: {search_term}"), empty=False) - @games.command(name="company", aliases=["companies"]) + @games.command(name="company", aliases=("companies",)) async def company(self, ctx: Context, amount: int = 5) -> None: """ Get random Game Companies companies from IGDB API. @@ -325,7 +325,7 @@ class Games(Cog): await ImagePaginator.paginate(pages, ctx, Embed(title="Random Game Companies")) @with_role(*STAFF_ROLES) - @games.command(name="refresh", aliases=["r"]) + @games.command(name="refresh", aliases=("r",)) async def refresh_genres_command(self, ctx: Context) -> None: """Refresh .games command genres.""" try: diff --git a/bot/exts/evergreen/movie.py b/bot/exts/evergreen/movie.py index ff23df4c..10638aea 100644 --- a/bot/exts/evergreen/movie.py +++ b/bot/exts/evergreen/movie.py @@ -53,7 +53,7 @@ class Movie(Cog): def __init__(self, bot: Bot): self.http_session: ClientSession = bot.http_session - @group(name="movies", aliases=["movie"], invoke_without_command=True) + @group(name="movies", aliases=("movie",), invoke_without_command=True) async def movies(self, ctx: Context, genre: str = "", amount: int = 5) -> None: """ Get random movies by specifying genre. Also support amount parameter, that define how much movies will be shown. @@ -103,7 +103,7 @@ class Movie(Cog): await ImagePaginator.paginate(pages, ctx, embed) - @movies.command(name="genres", aliases=["genre", "g"]) + @movies.command(name="genres", aliases=("genre", "g")) async def genres(self, ctx: Context) -> None: """Show all currently available genres for .movies command.""" await ctx.send(f"Current available genres: {', '.join('`' + genre.name + '`' for genre in MovieGenres)}") diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index e162c9bd..606545ab 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -15,7 +15,7 @@ COLORS = itertools.cycle([Colours.python_blue, Colours.python_yellow]) class PythonFacts(commands.Cog): """Sends a random fun fact about Python.""" - @commands.command(name="pythonfact", aliases=["pyfact"]) + @commands.command(name="pythonfact", aliases=("pyfact",)) async def get_python_fact(self, ctx: commands.Context) -> None: """Sends a Random fun fact about Python.""" embed = discord.Embed( diff --git a/bot/exts/evergreen/recommend_game.py b/bot/exts/evergreen/recommend_game.py index 56596020..45108969 100644 --- a/bot/exts/evergreen/recommend_game.py +++ b/bot/exts/evergreen/recommend_game.py @@ -25,7 +25,7 @@ class RecommendGame(commands.Cog): self.bot = bot self.index = 0 - @commands.command(name="recommendgame", aliases=["gamerec"]) + @commands.command(name="recommendgame", aliases=("gamerec",)) async def recommend_game(self, ctx: commands.Context) -> None: """Sends an Embed of a random game recommendation.""" if self.index >= len(game_recs): diff --git a/bot/exts/evergreen/space.py b/bot/exts/evergreen/space.py index 6c991d26..5e87c6d5 100644 --- a/bot/exts/evergreen/space.py +++ b/bot/exts/evergreen/space.py @@ -193,7 +193,7 @@ class Space(Cog): ) ) - @mars.command(name="dates", aliases=["d", "date", "rover", "rovers", "r"]) + @mars.command(name="dates", aliases=("d", "date", "rover", "rovers", "r")) async def dates(self, ctx: Context) -> None: """Get current available rovers photo date ranges.""" await ctx.send("\n".join( diff --git a/bot/exts/evergreen/timed.py b/bot/exts/evergreen/timed.py index 491231cc..2ea6b419 100644 --- a/bot/exts/evergreen/timed.py +++ b/bot/exts/evergreen/timed.py @@ -18,7 +18,7 @@ class TimedCommands(commands.Cog): return await ctx.bot.get_context(msg) - @commands.command(name="timed", aliases=["time", "t"]) + @commands.command(name="timed", aliases=("time", "t")) async def timed(self, ctx: commands.Context, *, command: str) -> None: """Time the command execution of a command.""" new_ctx = await self.create_execution_context(ctx, command) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 9db201ef..352d5ae8 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -43,7 +43,7 @@ class TriviaQuiz(commands.Cog): p = Path("bot", "resources", "evergreen", "trivia_quiz.json") return json.loads(p.read_text("utf8")) - @commands.group(name="quiz", aliases=["trivia"], invoke_without_command=True) + @commands.group(name="quiz", aliases=("trivia",), invoke_without_command=True) async def quiz_game(self, ctx: commands.Context, category: str = None) -> None: """ Start a quiz! diff --git a/bot/exts/evergreen/wikipedia.py b/bot/exts/evergreen/wikipedia.py index fa21b916..83937438 100644 --- a/bot/exts/evergreen/wikipedia.py +++ b/bot/exts/evergreen/wikipedia.py @@ -72,7 +72,7 @@ class WikipediaSearch(commands.Cog): return @commands.cooldown(1, 10, commands.BucketType.user) - @commands.command(name="wikipedia", aliases=["wiki"]) + @commands.command(name="wikipedia", aliases=("wiki",)) async def wikipedia_search_command(self, ctx: commands.Context, *, search: str) -> None: """Sends paginated top 10 results of Wikipedia search..""" contents = await self.wiki_request(ctx.channel, search) diff --git a/bot/exts/evergreen/wonder_twins.py b/bot/exts/evergreen/wonder_twins.py index 437d69f1..40edf785 100644 --- a/bot/exts/evergreen/wonder_twins.py +++ b/bot/exts/evergreen/wonder_twins.py @@ -38,7 +38,7 @@ class WonderTwins(Cog): object_name = self.append_onto(adjective, object_name) return f"{object_name} of {water_type}" - @command(name="formof", aliases=["wondertwins", "wondertwin", "fo"]) + @command(name="formof", aliases=("wondertwins", "wondertwin", "fo")) async def form_of(self, ctx: Context) -> None: """Command to send a Wonder Twins inspired phrase to the user invoking the command.""" await ctx.send(f"Form of {self.format_phrase()}!") diff --git a/bot/exts/halloween/spookynamerate.py b/bot/exts/halloween/spookynamerate.py index 63040289..c9b42ef5 100644 --- a/bot/exts/halloween/spookynamerate.py +++ b/bot/exts/halloween/spookynamerate.py @@ -117,7 +117,7 @@ class SpookyNameRate(Cog): """Get help on the Spooky Name Rate game.""" await ctx.send(embed=Embed.from_dict(HELP_MESSAGE_DICT)) - @spooky_name_rate.command(name="list", aliases=["all", "entries"]) + @spooky_name_rate.command(name="list", aliases=("all", "entries")) async def list_entries(self, ctx: Context) -> None: """Send all the entries up till now in a single embed.""" await ctx.send(embed=await self.get_responses_list(final=False)) @@ -134,7 +134,7 @@ class SpookyNameRate(Cog): "add an entry." ) - @spooky_name_rate.command(name="add", aliases=["register"]) + @spooky_name_rate.command(name="add", aliases=("register",)) async def add_name(self, ctx: Context, *, name: str) -> None: """Use this command to add/register your spookified name.""" if self.poll: diff --git a/bot/exts/pride/drag_queen_name.py b/bot/exts/pride/drag_queen_name.py index 6bf43913..81eeaff5 100644 --- a/bot/exts/pride/drag_queen_name.py +++ b/bot/exts/pride/drag_queen_name.py @@ -21,7 +21,7 @@ class DragNames(commands.Cog): """Loads a list of drag queen names.""" return json.loads(Path("bot/resources/pride/drag_queen_names.json").read_text("utf8")) - @commands.command(name="dragname", aliases=["dragqueenname", "queenme"]) + @commands.command(name="dragname", aliases=("dragqueenname", "queenme")) async def dragname(self, ctx: commands.Context) -> None: """Sends a message with a drag queen name.""" await ctx.send(random.choice(self.names)) diff --git a/bot/exts/pride/pride_anthem.py b/bot/exts/pride/pride_anthem.py index 21b7e468..ce4b06af 100644 --- a/bot/exts/pride/pride_anthem.py +++ b/bot/exts/pride/pride_anthem.py @@ -38,7 +38,7 @@ class PrideAnthem(commands.Cog): """Loads a list of videos from the resources folder as dictionaries.""" return json.loads(Path("bot/resources/pride/anthems.json").read_text("utf8")) - @commands.command(name="prideanthem", aliases=["anthem", "pridesong"]) + @commands.command(name="prideanthem", aliases=("anthem", "pridesong")) async def prideanthem(self, ctx: commands.Context, genre: str = None) -> None: """ Sends a message with a video of a random pride anthem. diff --git a/bot/exts/pride/pride_facts.py b/bot/exts/pride/pride_facts.py index 47e69a03..5bea1d32 100644 --- a/bot/exts/pride/pride_facts.py +++ b/bot/exts/pride/pride_facts.py @@ -72,7 +72,7 @@ class PrideFacts(commands.Cog): else: await target.send("The fact for the selected day is not yet available.") - @commands.command(name="pridefact", aliases=["pridefacts"]) + @commands.command(name="pridefact", aliases=("pridefacts",)) async def pridefact(self, ctx: commands.Context, option: str = None) -> None: """ Sends a message with a pride fact of the day. diff --git a/bot/exts/valentines/valentine_zodiac.py b/bot/exts/valentines/valentine_zodiac.py index 45d1edd5..d862ee63 100644 --- a/bot/exts/valentines/valentine_zodiac.py +++ b/bot/exts/valentines/valentine_zodiac.py @@ -116,7 +116,7 @@ class ValentineZodiac(commands.Cog): await ctx.send(embed=final_embed) log.trace("Embed from date successfully sent.") - @zodiac.command(name="partnerzodiac", aliases=["partner"]) + @zodiac.command(name="partnerzodiac", aliases=("partner",)) async def partner_zodiac(self, ctx: commands.Context, zodiac_sign: str) -> None: """Provides a random counter compatible zodiac sign to the given user's zodiac sign.""" embed = discord.Embed() -- cgit v1.2.3 From 28eb6d83dd8f1d1b41b4d45f09409cb6391ce52f Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Sat, 15 May 2021 12:54:54 -0400 Subject: fix: Remove the useless return Co-authored-by: Xithrius <15021300+Xithrius@users.noreply.github.com> --- bot/exts/evergreen/reddit.py | 1 - 1 file changed, 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/reddit.py b/bot/exts/evergreen/reddit.py index b5af83e7..e57fa2c0 100644 --- a/bot/exts/evergreen/reddit.py +++ b/bot/exts/evergreen/reddit.py @@ -99,7 +99,6 @@ class Reddit(Cog): f"{content_type}\u2003{Emojis.reddit_upvote}{ups}\u2003{Emojis.reddit_comments}" f"\u2002{comments}\u2003{Emojis.reddit_users}{author}\n\n" ) - return if paginate: post_page += f"**[{title}]({link})**\n\n" -- cgit v1.2.3 From f8a179df350eb3abb7f3595aaff3dbca312f540c Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 15 May 2021 13:31:34 -0400 Subject: chore: Make things that are only used once constants --- bot/exts/christmas/hanukkah_embed.py | 21 ++++++++++----------- bot/exts/easter/earth_photos.py | 4 +++- bot/exts/easter/egg_facts.py | 12 +++--------- bot/exts/evergreen/cheatsheet.py | 2 +- bot/exts/evergreen/magic_8ball.py | 7 +++---- bot/exts/evergreen/pythonfacts.py | 3 ++- bot/exts/halloween/halloween_facts.py | 9 ++++----- bot/exts/halloween/halloweenify.py | 10 +++++----- bot/exts/halloween/spookygif.py | 7 ++++--- bot/exts/pride/drag_queen_name.py | 12 +++--------- bot/exts/pride/pride_anthem.py | 12 +++--------- bot/exts/pride/pride_facts.py | 13 ++++--------- 12 files changed, 45 insertions(+), 67 deletions(-) (limited to 'bot') diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index 7a06b558..ca3146cc 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -11,16 +11,17 @@ from bot.utils.decorators import in_month log = logging.getLogger(__name__) +HEBCAL_URL = ( + "https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&" + "year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3448439&m=50&s=on" +) + class HanukkahEmbed(commands.Cog): """A cog that returns information about Hanukkah festival.""" def __init__(self, bot: Bot): self.bot = bot - self.url = ( - "https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&" - "year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3448439&m=50&s=on" - ) self.hanukkah_days = [] self.hanukkah_months = [] self.hanukkah_years = [] @@ -28,7 +29,7 @@ class HanukkahEmbed(commands.Cog): async def get_hanukkah_dates(self) -> List[str]: """Gets the dates for hanukkah festival.""" hanukkah_dates = [] - async with self.bot.http_session.get(self.url) as response: + async with self.bot.http_session.get(HEBCAL_URL) as response: json_data = await response.json() festivals = json_data["items"] for festival in festivals: @@ -57,9 +58,7 @@ class HanukkahEmbed(commands.Cog): day = str(today.day) month = str(today.month) year = str(today.year) - embed = Embed() - embed.title = "Hanukkah" - embed.colour = Colours.blue + embed = Embed(title="Hanukkah", colour=Colours.blue) if day in self.hanukkah_days and month in self.hanukkah_months and year in self.hanukkah_years: if int(day) == hanukkah_start_day: now = datetime.datetime.utcnow() @@ -74,8 +73,8 @@ class HanukkahEmbed(commands.Cog): return elif hours > hanukkah_start_hour: embed.description = ( - "It is the starting day of Hanukkah ! " - f"Its been {hours - hanukkah_start_hour} hours hanukkah started !" + "It is the starting day of Hanukkah! " + f"Its been {hours - hanukkah_start_hour} hours hanukkah started!" ) await ctx.send(embed=embed) return @@ -106,7 +105,7 @@ class HanukkahEmbed(commands.Cog): else: festival_end_month = hanukkah_end.strftime("%B") embed.description = ( - f"Looks like you missed Hanukkah !" + f"Looks like you missed Hanukkah!" f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}." ) diff --git a/bot/exts/easter/earth_photos.py b/bot/exts/easter/earth_photos.py index 9df4f9ca..f65790af 100644 --- a/bot/exts/easter/earth_photos.py +++ b/bot/exts/easter/earth_photos.py @@ -9,6 +9,8 @@ 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.""" @@ -21,7 +23,7 @@ class EarthPhotos(commands.Cog): """Returns a random photo of earth, sourced from Unsplash.""" async with ctx.typing(): async with self.bot.http_session.get( - "https://api.unsplash.com/photos/random", + API_URL, params={"query": "planet_earth", "client_id": Tokens.unsplash_access_key} ) as r: jsondata = await r.json() diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index d60032f0..ee383171 100644 --- a/bot/exts/easter/egg_facts.py +++ b/bot/exts/easter/egg_facts.py @@ -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,16 +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") - return loads(p.read_text("utf8")) - @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.""" @@ -51,7 +45,7 @@ class EasterFacts(commands.Cog): return discord.Embed( colour=Colours.soft_red, title="Easter Egg Fact", - description=random.choice(self.facts) + description=random.choice(EGG_FACTS) ) diff --git a/bot/exts/evergreen/cheatsheet.py b/bot/exts/evergreen/cheatsheet.py index 7ee34b1d..ae7793c9 100644 --- a/bot/exts/evergreen/cheatsheet.py +++ b/bot/exts/evergreen/cheatsheet.py @@ -12,7 +12,7 @@ from bot.bot import Bot from bot.constants import Categories, Channels, Colours, ERROR_REPLIES from bot.utils.decorators import whitelist_override -ERROR_MESSAGE = f"""\ +ERROR_MESSAGE = f""" Unknown cheat sheet. Please try to reformulate your query. **Examples**: diff --git a/bot/exts/evergreen/magic_8ball.py b/bot/exts/evergreen/magic_8ball.py index 4b3ed2a4..28ddcea0 100644 --- a/bot/exts/evergreen/magic_8ball.py +++ b/bot/exts/evergreen/magic_8ball.py @@ -9,18 +9,17 @@ from bot.bot import Bot log = logging.getLogger(__name__) +ANSWERS = json.loads(Path("bot/resources/evergreen/magic8ball.json").read_text("utf8")) + class Magic8ball(commands.Cog): """A Magic 8ball command to respond to a user's question.""" - def __init__(self): - self.answers = json.loads(Path("bot/resources/evergreen/magic8ball.json").read_text("utf8")) - @commands.command(name="8ball") async def output_answer(self, ctx: commands.Context, *, question: str) -> None: """Return a Magic 8ball answer from answers list.""" if len(question.split()) >= 3: - answer = random.choice(self.answers) + answer = random.choice(ANSWERS) await ctx.send(answer) else: await ctx.send("Usage: .8ball (minimum length of 3 eg: `will I win?`)") diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index 606545ab..80a8da5d 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -10,6 +10,7 @@ with open("bot/resources/evergreen/python_facts.txt") as file: FACTS = itertools.cycle(list(file)) COLORS = itertools.cycle([Colours.python_blue, Colours.python_yellow]) +PYFACTS_DISCUSSION = "https://github.com/python-discord/meta/discussions/93" class PythonFacts(commands.Cog): @@ -25,7 +26,7 @@ class PythonFacts(commands.Cog): ) embed.add_field( name="Suggestions", - value="Suggest more facts [here!](https://github.com/python-discord/meta/discussions/93)" + value=f"Suggest more facts [here!]({PYFACTS_DISCUSSION})" ) await ctx.send(embed=embed) diff --git a/bot/exts/halloween/halloween_facts.py b/bot/exts/halloween/halloween_facts.py index 98cc2db0..5ad8cc57 100644 --- a/bot/exts/halloween/halloween_facts.py +++ b/bot/exts/halloween/halloween_facts.py @@ -25,17 +25,16 @@ SPOOKY_EMOJIS = [ PUMPKIN_ORANGE = 0xFF7518 INTERVAL = timedelta(hours=6).total_seconds() +FACTS = json.loads(Path("bot/resources/halloween/halloween_facts.json").read_text("utf8")) +FACTS = list(enumerate(FACTS)) + class HalloweenFacts(commands.Cog): """A Cog for displaying interesting facts about Halloween.""" - def __init__(self): - self.halloween_facts = json.loads(Path("bot/resources/halloween/halloween_facts.json").read_text("utf8")) - self.facts = list(enumerate(self.halloween_facts)) - def random_fact(self) -> Tuple[int, str]: """Return a random fact from the loaded facts.""" - return random.choice(self.facts) + return random.choice(FACTS) @commands.command(name="spookyfact", aliases=("halloweenfact",), brief="Get the most recent Halloween fact") async def get_random_fact(self, ctx: commands.Context) -> None: diff --git a/bot/exts/halloween/halloweenify.py b/bot/exts/halloween/halloweenify.py index e839950a..83cfbaa7 100644 --- a/bot/exts/halloween/halloweenify.py +++ b/bot/exts/halloween/halloweenify.py @@ -12,6 +12,8 @@ from bot.bot import Bot log = logging.getLogger(__name__) +HALLOWEENIFY_DATA = loads(Path("bot/resources/halloween/halloweenify.json").read_text("utf8")) + class Halloweenify(commands.Cog): """A cog to change a invokers nickname to a spooky one!""" @@ -21,12 +23,10 @@ class Halloweenify(commands.Cog): async def halloweenify(self, ctx: commands.Context) -> None: """Change your nickname into a much spookier one!""" async with ctx.typing(): - data = loads(Path("bot/resources/halloween/halloweenify.json").read_text("utf8")) - # Choose a random character from our list we loaded above and set apart the nickname and image url. - character = choice(data["characters"]) - nickname = "".join([nickname for nickname in character]) - image = "".join([character[nickname] for nickname in character]) + character = choice(HALLOWEENIFY_DATA["characters"]) + nickname = "".join(nickname for nickname in character) + image = "".join(character[nickname] for nickname in character) # Build up a Embed embed = discord.Embed() diff --git a/bot/exts/halloween/spookygif.py b/bot/exts/halloween/spookygif.py index ffb91b1b..a2146a84 100644 --- a/bot/exts/halloween/spookygif.py +++ b/bot/exts/halloween/spookygif.py @@ -8,6 +8,8 @@ from bot.constants import Tokens log = logging.getLogger(__name__) +API_URL = "http://api.giphy.com/v1/gifs/random" + class SpookyGif(commands.Cog): """A cog to fetch a random spooky gif from the web!""" @@ -21,12 +23,11 @@ class SpookyGif(commands.Cog): async with ctx.typing(): params = {"api_key": Tokens.giphy, "tag": "halloween", "rating": "g"} # Make a GET request to the Giphy API to get a random halloween gif. - async with self.bot.http_session.get("http://api.giphy.com/v1/gifs/random", params=params) as resp: + async with self.bot.http_session.get(API_URL, params=params) as resp: data = await resp.json() url = data["data"]["image_url"] - embed = discord.Embed(colour=0x9b59b6) - embed.title = "A spooooky gif!" + embed = discord.Embed(title="A spooooky gif!", colour=0x9b59b6) embed.set_image(url=url) await ctx.send(embed=embed) diff --git a/bot/exts/pride/drag_queen_name.py b/bot/exts/pride/drag_queen_name.py index 81eeaff5..15ca6576 100644 --- a/bot/exts/pride/drag_queen_name.py +++ b/bot/exts/pride/drag_queen_name.py @@ -9,22 +9,16 @@ from bot.bot import Bot log = logging.getLogger(__name__) +NAMES = json.loads(Path("bot/resources/pride/drag_queen_names.json").read_text("utf8")) + class DragNames(commands.Cog): """Gives a random drag queen name!""" - def __init__(self): - self.names = self.load_names() - - @staticmethod - def load_names() -> list: - """Loads a list of drag queen names.""" - return json.loads(Path("bot/resources/pride/drag_queen_names.json").read_text("utf8")) - @commands.command(name="dragname", aliases=("dragqueenname", "queenme")) async def dragname(self, ctx: commands.Context) -> None: """Sends a message with a drag queen name.""" - await ctx.send(random.choice(self.names)) + await ctx.send(random.choice(NAMES)) def setup(bot: Bot) -> None: diff --git a/bot/exts/pride/pride_anthem.py b/bot/exts/pride/pride_anthem.py index ce4b06af..4650595a 100644 --- a/bot/exts/pride/pride_anthem.py +++ b/bot/exts/pride/pride_anthem.py @@ -10,13 +10,12 @@ from bot.bot import Bot log = logging.getLogger(__name__) +VIDEOS = json.loads(Path("bot/resources/pride/anthems.json").read_text("utf8")) + class PrideAnthem(commands.Cog): """Embed a random youtube video for a gay anthem!""" - def __init__(self): - self.anthems = self.load_vids() - def get_video(self, genre: Optional[str] = None) -> dict: """ Picks a random anthem from the list. @@ -27,17 +26,12 @@ class PrideAnthem(commands.Cog): if not genre: return random.choice(self.anthems) else: - songs = [song for song in self.anthems if genre.casefold() in song["genre"]] + songs = [song for song in VIDEOS if genre.casefold() in song["genre"]] try: return random.choice(songs) except IndexError: log.info("No videos for that genre.") - @staticmethod - def load_vids() -> list: - """Loads a list of videos from the resources folder as dictionaries.""" - return json.loads(Path("bot/resources/pride/anthems.json").read_text("utf8")) - @commands.command(name="prideanthem", aliases=("anthem", "pridesong")) async def prideanthem(self, ctx: commands.Context, genre: str = None) -> None: """ diff --git a/bot/exts/pride/pride_facts.py b/bot/exts/pride/pride_facts.py index 5bea1d32..631e2e8b 100644 --- a/bot/exts/pride/pride_facts.py +++ b/bot/exts/pride/pride_facts.py @@ -15,21 +15,16 @@ from bot.utils.decorators import seasonal_task log = logging.getLogger(__name__) +FACTS = json.loads(Path("bot/resources/pride/facts.json").read_text("utf8")) + class PrideFacts(commands.Cog): """Provides a new fact every day during the Pride season!""" def __init__(self, bot: Bot): self.bot = bot - self.facts = self.load_facts() - self.daily_fact_task = self.bot.loop.create_task(self.send_pride_fact_daily()) - @staticmethod - def load_facts() -> dict: - """Loads a dictionary of years mapping to lists of facts.""" - return json.loads(Path("bot/resources/pride/facts.json").read_text("utf8")) - @seasonal_task(Month.JUNE) async def send_pride_fact_daily(self) -> None: """Background task to post the daily pride fact every day.""" @@ -41,8 +36,8 @@ class PrideFacts(commands.Cog): async def send_random_fact(self, ctx: commands.Context) -> None: """Provides a fact from any previous day, or today.""" now = datetime.utcnow() - previous_years_facts = (y for x, y in self.facts.items() if int(x) < now.year) - current_year_facts = self.facts.get(str(now.year), [])[:now.day] + 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] try: await ctx.send(embed=self.make_embed(random.choice(previous_facts))) -- cgit v1.2.3 From bf999d03b02e0664ffe43c31cf9208c0251a8370 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 15 May 2021 13:44:14 -0400 Subject: chore: Apply suggested changes to hanukkah_embed.py --- bot/exts/christmas/hanukkah_embed.py | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) (limited to 'bot') diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index ca3146cc..119f2446 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -80,18 +80,8 @@ class HanukkahEmbed(commands.Cog): return festival_day = self.hanukkah_days.index(day) number_suffixes = ["st", "nd", "rd", "th"] - suffix = "" - if festival_day == 1: - suffix = number_suffixes[0] - if festival_day == 2: - suffix = number_suffixes[1] - if festival_day == 3: - suffix = number_suffixes[2] - if festival_day > 3: - suffix = number_suffixes[3] - message = "" - for _ in range(1, festival_day + 1): - message += ":menorah:" + suffix = number_suffixes[festival_day - 1 if festival_day <= 3 else 3] + message = ":menorah:" * festival_day embed.description = f"It is the {festival_day}{suffix} day of Hanukkah!\n{message}" await ctx.send(embed=embed) else: -- cgit v1.2.3 From 85733251d46151dc76378fad253c1d45e49eb9a0 Mon Sep 17 00:00:00 2001 From: Matteo Bertucci Date: Sat, 15 May 2021 20:07:10 +0200 Subject: Latex: temporarily disable loading of the cog As we are currently working on restricting resources on the latex cog, this commit will prevent it from loading. It will be reverted once solved. --- bot/exts/evergreen/latex.py | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'bot') diff --git a/bot/exts/evergreen/latex.py b/bot/exts/evergreen/latex.py index c4a8597c..8f42da90 100644 --- a/bot/exts/evergreen/latex.py +++ b/bot/exts/evergreen/latex.py @@ -91,4 +91,9 @@ class Latex(commands.Cog): def setup(bot: commands.Bot) -> None: """Load the Latex Cog.""" + # As we have resource issues on this cog, + # we have it currently disabled while we fix it. + import logging + logging.info("Latex cog is currently disabled. It won't be loaded.") + return bot.add_cog(Latex(bot)) -- cgit v1.2.3 From 01e22725c627b677224ccf8409f71c9b7bc68c81 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 15 May 2021 15:34:08 -0400 Subject: chore: Make more things use constants --- bot/exts/halloween/spookygif.py | 4 ++-- bot/exts/halloween/spookynamerate.py | 22 +++++++--------------- 2 files changed, 9 insertions(+), 17 deletions(-) (limited to 'bot') diff --git a/bot/exts/halloween/spookygif.py b/bot/exts/halloween/spookygif.py index a2146a84..9511d407 100644 --- a/bot/exts/halloween/spookygif.py +++ b/bot/exts/halloween/spookygif.py @@ -4,7 +4,7 @@ import discord from discord.ext import commands from bot.bot import Bot -from bot.constants import Tokens +from bot.constants import Colours, Tokens log = logging.getLogger(__name__) @@ -27,7 +27,7 @@ class SpookyGif(commands.Cog): data = await resp.json() url = data["data"]["image_url"] - embed = discord.Embed(title="A spooooky gif!", colour=0x9b59b6) + embed = discord.Embed(title="A spooooky gif!", colour=Colours.purple) embed.set_image(url=url) await ctx.send(embed=embed) diff --git a/bot/exts/halloween/spookynamerate.py b/bot/exts/halloween/spookynamerate.py index c9b42ef5..3d6d95fa 100644 --- a/bot/exts/halloween/spookynamerate.py +++ b/bot/exts/halloween/spookynamerate.py @@ -6,7 +6,7 @@ from datetime import datetime, timedelta from logging import getLogger from os import getenv from pathlib import Path -from typing import Dict, Union +from typing import Union from async_rediscache import RedisCache from discord import Embed, Reaction, TextChannel, User @@ -65,6 +65,11 @@ HELP_MESSAGE_DICT = { ], } +# The names are from https://www.mockaroo.com/ +NAMES = json.loads(Path("bot/resources/halloween/spookynamerate_names.json").read_text("utf8")) +FIRST_NAMES = NAMES["first_names"] +LAST_NAMES = NAMES["last_names"] + class SpookyNameRate(Cog): """ @@ -88,14 +93,6 @@ class SpookyNameRate(Cog): def __init__(self, bot: Bot) -> None: self.bot = bot - - names_data = self.load_json( - Path("bot", "resources", "halloween", "spookynamerate_names.json") - ) - self.first_names = names_data["first_names"] - self.last_names = names_data["last_names"] - # the names are from https://www.mockaroo.com/ - self.name = None self.bot.loop.create_task(self.load_vars()) @@ -302,7 +299,7 @@ class SpookyNameRate(Cog): await self.messages.clear() # reset the messages # send the next name - self.name = f"{random.choice(self.first_names)} {random.choice(self.last_names)}" + self.name = f"{random.choice(FIRST_NAMES)} {random.choice(LAST_NAMES)}" await self.data.set("name", self.name) await channel.send( @@ -368,11 +365,6 @@ class SpookyNameRate(Cog): logger.warning("Bot is unable to get the #seasonalbot-commands channel. Please check the channel ID.") return channel - @staticmethod - def load_json(file: Path) -> Dict[str, str]: - """Loads a JSON file and returns its contents.""" - return json.loads(file.read_text("utf8")) - @staticmethod def in_allowed_month() -> bool: """Returns whether running in the limited month.""" -- cgit v1.2.3 From 369134e791fd9a3e52a4948725c249d03128fdd6 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Sat, 15 May 2021 15:40:09 -0400 Subject: chore: Apply suggestions from code review Co-authored-by: Xithrius <15021300+Xithrius@users.noreply.github.com> --- bot/exts/evergreen/recommend_game.py | 2 +- bot/exts/valentines/myvalenstate.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/evergreen/recommend_game.py b/bot/exts/evergreen/recommend_game.py index 45108969..35d60128 100644 --- a/bot/exts/evergreen/recommend_game.py +++ b/bot/exts/evergreen/recommend_game.py @@ -41,7 +41,7 @@ class RecommendGame(commands.Cog): if author is not None: embed.set_author(name=author.name, icon_url=author.avatar_url) embed.set_image(url=game["image"]) - embed.add_field(name="Recommendation: " + game["title"] + "\n" + game["link"], value=game["description"]) + embed.add_field(name=f"Recommendation: {game['title']}\n{game['link']}", value=game["description"]) await ctx.send(embed=embed) diff --git a/bot/exts/valentines/myvalenstate.py b/bot/exts/valentines/myvalenstate.py index c699de94..52a61011 100644 --- a/bot/exts/valentines/myvalenstate.py +++ b/bot/exts/valentines/myvalenstate.py @@ -69,7 +69,7 @@ class MyValenstate(commands.Cog): embed = discord.Embed( title=f"Your Valenstate is {valenstate} \u2764", - description=STATES[valenstate]['text'], + description=STATES[valenstate]["text"], colour=Colours.pink ) embed.add_field(name=embed_title, value=embed_text) -- cgit v1.2.3 From 8ac335afc7466d92888c40db46e0c6d454743ff6 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 15 May 2021 17:32:09 -0400 Subject: chore: Add Iceman's suggested changes --- bot/exts/easter/bunny_name_generator.py | 9 ++++++--- bot/exts/easter/easter_riddle.py | 2 +- bot/exts/easter/egg_facts.py | 3 ++- bot/exts/evergreen/avatar_modification/_effects.py | 4 ++-- bot/exts/evergreen/avatar_modification/avatar_modify.py | 4 ++-- bot/exts/evergreen/battleship.py | 8 ++++---- 6 files changed, 17 insertions(+), 13 deletions(-) (limited to 'bot') diff --git a/bot/exts/easter/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index adde8704..3e97373f 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -17,14 +17,16 @@ BUNNY_NAMES = json.loads(Path("bot/resources/easter/bunny_names.json").read_text class BunnyNameGenerator(commands.Cog): """Generate a random bunny name, or bunnify your Discord username!""" - 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) 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. @@ -45,7 +47,8 @@ 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"] suffix = random.choice(extensions) diff --git a/bot/exts/easter/easter_riddle.py b/bot/exts/easter/easter_riddle.py index a87f93d1..88b3be2f 100644 --- a/bot/exts/easter/easter_riddle.py +++ b/bot/exts/easter/easter_riddle.py @@ -48,7 +48,7 @@ class EasterRiddle(commands.Cog): ) return - self.current_channel = ctx.message.channel + self.current_channel = ctx.channel random_question = random.choice(RIDDLE_QUESTIONS) question = random_question["question"] diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index ee383171..486e735f 100644 --- a/bot/exts/easter/egg_facts.py +++ b/bot/exts/easter/egg_facts.py @@ -40,7 +40,8 @@ class EasterFacts(commands.Cog): 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, diff --git a/bot/exts/evergreen/avatar_modification/_effects.py b/bot/exts/evergreen/avatar_modification/_effects.py index 9339ecc4..cd798fc2 100644 --- a/bot/exts/evergreen/avatar_modification/_effects.py +++ b/bot/exts/evergreen/avatar_modification/_effects.py @@ -14,7 +14,7 @@ class PfpEffects: """ Implements various image modifying effects, for the PfpModify cog. - All of these fuctions are slow, and blocking, so they should be ran in executors. + All of these functions are slow, and blocking, so they should be ran in executors. """ @staticmethod @@ -102,7 +102,7 @@ class PfpEffects: Applies the easter effect to the given image. This is done by getting the closest "easter" colour to each pixel and changing the colour - to the half-way RGBvalue. + to the half-way RGB value. We also then add an overlay image on top in middle right, a chocolate bunny by default. """ diff --git a/bot/exts/evergreen/avatar_modification/avatar_modify.py b/bot/exts/evergreen/avatar_modification/avatar_modify.py index 199b6dcb..17f34ed4 100644 --- a/bot/exts/evergreen/avatar_modification/avatar_modify.py +++ b/bot/exts/evergreen/avatar_modification/avatar_modify.py @@ -33,7 +33,7 @@ GENDER_OPTIONS = json.loads(Path("bot/resources/pride/gender_options.json").read async def in_executor(func: t.Callable[..., T], *args) -> T: """ - Runs the given synchronus function `func` in an executor. + Runs the given synchronous function `func` in an executor. This is useful for running slow, blocking code within async functions, so that they don't block the bot. @@ -71,7 +71,7 @@ class AvatarModify(commands.Cog): Fetches a user and handles errors. This helper function is required as the member cache doesn't always have the most up to date - profile picture. This can lead to errors if the image is delted from the Discord CDN. + profile picture. This can lead to errors if the image is deleted from the Discord CDN. fetch_member can't be used due to the avatar url being part of the user object, and some weird caching that D.py does """ diff --git a/bot/exts/evergreen/battleship.py b/bot/exts/evergreen/battleship.py index 27c50bdb..c2f2079c 100644 --- a/bot/exts/evergreen/battleship.py +++ b/bot/exts/evergreen/battleship.py @@ -31,8 +31,8 @@ EmojiSet = typing.Dict[typing.Tuple[bool, bool], str] class Player: """Each player in the game - their messages for the boards and their current grid.""" - user: discord.Member - board: discord.Message + user: typing.Optional[discord.Member] + board: typing.Optional[discord.Message] opponent_board: discord.Message grid: Grid @@ -417,9 +417,9 @@ class Battleship(commands.Cog): self.waiting.remove(ctx.author) if self.already_playing(ctx.author): return + game = Game(self.bot, ctx.channel, ctx.author, user) + self.games.append(game) try: - game = Game(self.bot, ctx.channel, ctx.author, user) - self.games.append(game) await game.start_game() self.games.remove(game) except discord.Forbidden: -- cgit v1.2.3 From 0285da6cae32bb5986111477bbd4d61e723005f3 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Sat, 15 May 2021 17:34:11 -0400 Subject: chore: Apply Iceman's suggestions Co-authored-by: Rohan Reddy Alleti --- bot/exts/easter/egg_decorating.py | 2 +- bot/exts/evergreen/avatar_modification/_effects.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'bot') diff --git a/bot/exts/easter/egg_decorating.py b/bot/exts/easter/egg_decorating.py index d4b27b20..fd7620d4 100644 --- a/bot/exts/easter/egg_decorating.py +++ b/bot/exts/easter/egg_decorating.py @@ -44,7 +44,7 @@ class EggDecorating(commands.Cog): @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. diff --git a/bot/exts/evergreen/avatar_modification/_effects.py b/bot/exts/evergreen/avatar_modification/_effects.py index cd798fc2..b53b26f3 100644 --- a/bot/exts/evergreen/avatar_modification/_effects.py +++ b/bot/exts/evergreen/avatar_modification/_effects.py @@ -273,7 +273,7 @@ class PfpEffects: @staticmethod def mosaic_effect(img_bytes: bytes, squares: int, file_name: str) -> discord.File: - """Seperate function run from an executor which turns an image into a mosaic.""" + """Separate function run from an executor which turns an image into a mosaic.""" avatar = Image.open(BytesIO(img_bytes)) avatar = avatar.convert("RGBA").resize((1024, 1024)) -- cgit v1.2.3 From ce8a9d85cd5a27c38c61f17f5656106ddd9c7a0f Mon Sep 17 00:00:00 2001 From: vcokltfre Date: Sat, 15 May 2021 23:21:09 +0100 Subject: feat: allow replying to messages to bookmark --- bot/exts/evergreen/bookmark.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 29915627..1d172a45 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -1,6 +1,7 @@ import asyncio import logging import random +import typing as t import discord from discord.ext import commands @@ -88,11 +89,16 @@ class Bookmark(commands.Cog): async def bookmark( self, ctx: commands.Context, - target_message: WrappedMessageConverter, + target_message: t.Optional[WrappedMessageConverter], *, title: str = "Bookmark" ) -> None: """Send the author a link to `target_message` via DMs.""" + if not target_message: + if not ctx.message.reference: + raise commands.UserInputError("You must either provide a message to bookmark, or reply to one.") + target_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) + # Prevent users from bookmarking a message in a channel they don't have access to permissions = ctx.author.permissions_in(target_message.channel) if not permissions.read_messages: -- cgit v1.2.3 From 8c8df556a982d06218465f98ec9ea9ccca01d6b0 Mon Sep 17 00:00:00 2001 From: vcokltfre Date: Sat, 15 May 2021 23:32:22 +0100 Subject: chore: add 'valid' wording --- bot/exts/evergreen/bookmark.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 1d172a45..1f65f07c 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -96,7 +96,7 @@ class Bookmark(commands.Cog): """Send the author a link to `target_message` via DMs.""" if not target_message: if not ctx.message.reference: - raise commands.UserInputError("You must either provide a message to bookmark, or reply to one.") + raise commands.UserInputError("You must either provide a valid message to bookmark, or reply to one.") target_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) # Prevent users from bookmarking a message in a channel they don't have access to -- cgit v1.2.3 From 6885c85f7c02fec618265881f00f92738b64eabc Mon Sep 17 00:00:00 2001 From: vcokltfre Date: Sun, 16 May 2021 03:19:26 +0100 Subject: chore: use ctx.fetch_message Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/exts/evergreen/bookmark.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 1f65f07c..c84446c5 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -97,7 +97,7 @@ class Bookmark(commands.Cog): if not target_message: if not ctx.message.reference: raise commands.UserInputError("You must either provide a valid message to bookmark, or reply to one.") - target_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) + target_message = await ctx.fetch_message(ctx.message.reference.message_id) # Prevent users from bookmarking a message in a channel they don't have access to permissions = ctx.author.permissions_in(target_message.channel) -- cgit v1.2.3 From 6230b7836593e125577261d90ec8e8910fa0f739 Mon Sep 17 00:00:00 2001 From: Chris Date: Sun, 16 May 2021 15:54:13 +0100 Subject: Bump d.py to 1.7.2 d.py 1.5.1 depending on multidict, which needs gcc installed. Bumping d.py to 1.7.2 removes the need fo rbuild tools in the image. d.py 1.7 introduced the line sep are on the paginator, so this needs to be added to our linepaginator subclass. --- bot/utils/pagination.py | 19 ++++- poetry.lock | 212 +++++++++++++++++++++++++++++++++--------------- pyproject.toml | 2 +- 3 files changed, 161 insertions(+), 72 deletions(-) (limited to 'bot') diff --git a/bot/utils/pagination.py b/bot/utils/pagination.py index 742281d7..a0a362cb 100644 --- a/bot/utils/pagination.py +++ b/bot/utils/pagination.py @@ -27,7 +27,14 @@ class EmptyPaginatorEmbed(Exception): class LinePaginator(Paginator): """A class that aids in paginating code blocks for Discord messages.""" - def __init__(self, prefix: str = "```", suffix: str = "```", max_size: int = 2000, max_lines: int = None): + def __init__( + self, + prefix: str = '```', + suffix: str = '```', + max_size: int = 2000, + max_lines: int = None, + linesep: str = "\n" + ): """ Overrides the Paginator.__init__ from inside discord.ext.commands. @@ -36,9 +43,13 @@ class LinePaginator(Paginator): `max_size` and `max_lines` denote the maximum amount of codepoints and lines allowed per page. """ - self.prefix = prefix - self.suffix = suffix - self.max_size = max_size - len(suffix) + super().__init__( + prefix, + suffix, + max_size - len(suffix), + linesep + ) + self.max_lines = max_lines self._current_page = [prefix] self._linecount = 0 diff --git a/poetry.lock b/poetry.lock index 78a30370..f70d0328 100644 --- a/poetry.lock +++ b/poetry.lock @@ -11,18 +11,19 @@ pycares = ">=3.0.0" [[package]] name = "aiohttp" -version = "3.6.3" +version = "3.7.4.post0" description = "Async http client/server framework (asyncio)" category = "main" optional = false -python-versions = ">=3.5.3" +python-versions = ">=3.6" [package.dependencies] async-timeout = ">=3.0,<4.0" attrs = ">=17.3.0" -chardet = ">=2.0,<4.0" -multidict = ">=4.5,<5.0" -yarl = ">=1.0,<1.6.0" +chardet = ">=2.0,<5.0" +multidict = ">=4.5,<7.0" +typing-extensions = ">=3.6.5" +yarl = ">=1.0,<2.0" [package.extras] speedups = ["aiodns", "brotlipy", "cchardet"] @@ -139,11 +140,11 @@ python-versions = ">=3.6.1" [[package]] name = "chardet" -version = "3.0.4" +version = "4.0.0" description = "Universal encoding detector for Python 2 and 3" category = "main" optional = false -python-versions = "*" +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" [[package]] name = "cycler" @@ -158,18 +159,18 @@ six = "*" [[package]] name = "discord.py" -version = "1.5.1" +version = "1.7.2" description = "A Python wrapper for the Discord API" category = "main" optional = false python-versions = ">=3.5.3" [package.dependencies] -aiohttp = ">=3.6.0,<3.7.0" +aiohttp = ">=3.6.0,<3.8.0" [package.extras] -docs = ["sphinx (==1.8.5)", "sphinxcontrib-trio (==1.1.1)", "sphinxcontrib-websupport"] -voice = ["PyNaCl (==1.3.0)"] +docs = ["sphinx (==3.0.3)", "sphinxcontrib-trio (==1.1.2)", "sphinxcontrib-websupport"] +voice = ["PyNaCl (>=1.3.0,<1.5)"] [[package]] name = "distlib" @@ -398,11 +399,11 @@ python-versions = ">=3.5" [[package]] name = "multidict" -version = "4.7.6" +version = "5.1.0" description = "multidict implementation" category = "main" optional = false -python-versions = ">=3.5" +python-versions = ">=3.6" [[package]] name = "nodeenv" @@ -653,6 +654,14 @@ category = "dev" optional = false python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" +[[package]] +name = "typing-extensions" +version = "3.10.0.0" +description = "Backported and Experimental Type Hints for Python 3.5+" +category = "main" +optional = false +python-versions = "*" + [[package]] name = "urllib3" version = "1.26.4" @@ -686,11 +695,11 @@ testing = ["coverage (>=4)", "coverage-enable-subprocess (>=1)", "flaky (>=3)", [[package]] name = "yarl" -version = "1.5.1" +version = "1.6.3" description = "Yet another URL library" category = "main" optional = false -python-versions = ">=3.5" +python-versions = ">=3.6" [package.dependencies] idna = ">=2.0" @@ -699,7 +708,7 @@ multidict = ">=4.0" [metadata] lock-version = "1.1" python-versions = "^3.9" -content-hash = "fc7ffecf728af848ad4fcc1d5b14ded3360b8473ca5da77b5d39e256d36bd0fd" +content-hash = "d0003b8cc4caac9d6eb0c14e4c4085191907d7fa0803888eddae4259446eada7" [metadata.files] aiodns = [ @@ -707,19 +716,43 @@ aiodns = [ {file = "aiodns-2.0.0.tar.gz", hash = "sha256:815fdef4607474295d68da46978a54481dd1e7be153c7d60f9e72773cd38d77d"}, ] aiohttp = [ - {file = "aiohttp-3.6.3-cp35-cp35m-macosx_10_14_x86_64.whl", hash = "sha256:1a4160579ffbc1b69e88cb6ca8bb0fbd4947dfcbf9fb1e2a4fc4c7a4a986c1fe"}, - {file = "aiohttp-3.6.3-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:fb83326d8295e8840e4ba774edf346e87eca78ba8a89c55d2690352842c15ba5"}, - {file = "aiohttp-3.6.3-cp35-cp35m-win32.whl", hash = "sha256:470e4c90da36b601676fe50c49a60d34eb8c6593780930b1aa4eea6f508dfa37"}, - {file = "aiohttp-3.6.3-cp35-cp35m-win_amd64.whl", hash = "sha256:a885432d3cabc1287bcf88ea94e1826d3aec57fd5da4a586afae4591b061d40d"}, - {file = "aiohttp-3.6.3-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:c506853ba52e516b264b106321c424d03f3ddef2813246432fa9d1cefd361c81"}, - {file = "aiohttp-3.6.3-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:797456399ffeef73172945708810f3277f794965eb6ec9bd3a0c007c0476be98"}, - {file = "aiohttp-3.6.3-cp36-cp36m-win32.whl", hash = "sha256:60f4caa3b7f7a477f66ccdd158e06901e1d235d572283906276e3803f6b098f5"}, - {file = "aiohttp-3.6.3-cp36-cp36m-win_amd64.whl", hash = "sha256:2ad493de47a8f926386fa6d256832de3095ba285f325db917c7deae0b54a9fc8"}, - {file = "aiohttp-3.6.3-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:319b490a5e2beaf06891f6711856ea10591cfe84fe9f3e71a721aa8f20a0872a"}, - {file = "aiohttp-3.6.3-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:66d64486172b032db19ea8522328b19cfb78a3e1e5b62ab6a0567f93f073dea0"}, - {file = "aiohttp-3.6.3-cp37-cp37m-win32.whl", hash = "sha256:206c0ccfcea46e1bddc91162449c20c72f308aebdcef4977420ef329c8fcc599"}, - {file = "aiohttp-3.6.3-cp37-cp37m-win_amd64.whl", hash = "sha256:687461cd974722110d1763b45c5db4d2cdee8d50f57b00c43c7590d1dd77fc5c"}, - {file = "aiohttp-3.6.3.tar.gz", hash = "sha256:698cd7bc3c7d1b82bb728bae835724a486a8c376647aec336aa21a60113c3645"}, + {file = "aiohttp-3.7.4.post0-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:3cf75f7cdc2397ed4442594b935a11ed5569961333d49b7539ea741be2cc79d5"}, + {file = "aiohttp-3.7.4.post0-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:4b302b45040890cea949ad092479e01ba25911a15e648429c7c5aae9650c67a8"}, + {file = "aiohttp-3.7.4.post0-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:fe60131d21b31fd1a14bd43e6bb88256f69dfc3188b3a89d736d6c71ed43ec95"}, + {file = "aiohttp-3.7.4.post0-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:393f389841e8f2dfc86f774ad22f00923fdee66d238af89b70ea314c4aefd290"}, + {file = "aiohttp-3.7.4.post0-cp36-cp36m-manylinux2014_ppc64le.whl", hash = "sha256:c6e9dcb4cb338d91a73f178d866d051efe7c62a7166653a91e7d9fb18274058f"}, + {file = "aiohttp-3.7.4.post0-cp36-cp36m-manylinux2014_s390x.whl", hash = "sha256:5df68496d19f849921f05f14f31bd6ef53ad4b00245da3195048c69934521809"}, + {file = "aiohttp-3.7.4.post0-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:0563c1b3826945eecd62186f3f5c7d31abb7391fedc893b7e2b26303b5a9f3fe"}, + {file = "aiohttp-3.7.4.post0-cp36-cp36m-win32.whl", hash = "sha256:3d78619672183be860b96ed96f533046ec97ca067fd46ac1f6a09cd9b7484287"}, + {file = "aiohttp-3.7.4.post0-cp36-cp36m-win_amd64.whl", hash = "sha256:f705e12750171c0ab4ef2a3c76b9a4024a62c4103e3a55dd6f99265b9bc6fcfc"}, + {file = "aiohttp-3.7.4.post0-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:230a8f7e24298dea47659251abc0fd8b3c4e38a664c59d4b89cca7f6c09c9e87"}, + {file = "aiohttp-3.7.4.post0-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:2e19413bf84934d651344783c9f5e22dee452e251cfd220ebadbed2d9931dbf0"}, + {file = "aiohttp-3.7.4.post0-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:e4b2b334e68b18ac9817d828ba44d8fcb391f6acb398bcc5062b14b2cbeac970"}, + {file = "aiohttp-3.7.4.post0-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:d012ad7911653a906425d8473a1465caa9f8dea7fcf07b6d870397b774ea7c0f"}, + {file = "aiohttp-3.7.4.post0-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:40eced07f07a9e60e825554a31f923e8d3997cfc7fb31dbc1328c70826e04cde"}, + {file = "aiohttp-3.7.4.post0-cp37-cp37m-manylinux2014_s390x.whl", hash = "sha256:209b4a8ee987eccc91e2bd3ac36adee0e53a5970b8ac52c273f7f8fd4872c94c"}, + {file = "aiohttp-3.7.4.post0-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:14762875b22d0055f05d12abc7f7d61d5fd4fe4642ce1a249abdf8c700bf1fd8"}, + {file = "aiohttp-3.7.4.post0-cp37-cp37m-win32.whl", hash = "sha256:7615dab56bb07bff74bc865307aeb89a8bfd9941d2ef9d817b9436da3a0ea54f"}, + {file = "aiohttp-3.7.4.post0-cp37-cp37m-win_amd64.whl", hash = "sha256:d9e13b33afd39ddeb377eff2c1c4f00544e191e1d1dee5b6c51ddee8ea6f0cf5"}, + {file = "aiohttp-3.7.4.post0-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:547da6cacac20666422d4882cfcd51298d45f7ccb60a04ec27424d2f36ba3eaf"}, + {file = "aiohttp-3.7.4.post0-cp38-cp38-manylinux1_i686.whl", hash = "sha256:af9aa9ef5ba1fd5b8c948bb11f44891968ab30356d65fd0cc6707d989cd521df"}, + {file = "aiohttp-3.7.4.post0-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:64322071e046020e8797117b3658b9c2f80e3267daec409b350b6a7a05041213"}, + {file = "aiohttp-3.7.4.post0-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:bb437315738aa441251214dad17428cafda9cdc9729499f1d6001748e1d432f4"}, + {file = "aiohttp-3.7.4.post0-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:e54962802d4b8b18b6207d4a927032826af39395a3bd9196a5af43fc4e60b009"}, + {file = "aiohttp-3.7.4.post0-cp38-cp38-manylinux2014_s390x.whl", hash = "sha256:a00bb73540af068ca7390e636c01cbc4f644961896fa9363154ff43fd37af2f5"}, + {file = "aiohttp-3.7.4.post0-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:79ebfc238612123a713a457d92afb4096e2148be17df6c50fb9bf7a81c2f8013"}, + {file = "aiohttp-3.7.4.post0-cp38-cp38-win32.whl", hash = "sha256:515dfef7f869a0feb2afee66b957cc7bbe9ad0cdee45aec7fdc623f4ecd4fb16"}, + {file = "aiohttp-3.7.4.post0-cp38-cp38-win_amd64.whl", hash = "sha256:114b281e4d68302a324dd33abb04778e8557d88947875cbf4e842c2c01a030c5"}, + {file = "aiohttp-3.7.4.post0-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:7b18b97cf8ee5452fa5f4e3af95d01d84d86d32c5e2bfa260cf041749d66360b"}, + {file = "aiohttp-3.7.4.post0-cp39-cp39-manylinux1_i686.whl", hash = "sha256:15492a6368d985b76a2a5fdd2166cddfea5d24e69eefed4630cbaae5c81d89bd"}, + {file = "aiohttp-3.7.4.post0-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:bdb230b4943891321e06fc7def63c7aace16095be7d9cf3b1e01be2f10fba439"}, + {file = "aiohttp-3.7.4.post0-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:cffe3ab27871bc3ea47df5d8f7013945712c46a3cc5a95b6bee15887f1675c22"}, + {file = "aiohttp-3.7.4.post0-cp39-cp39-manylinux2014_ppc64le.whl", hash = "sha256:f881853d2643a29e643609da57b96d5f9c9b93f62429dcc1cbb413c7d07f0e1a"}, + {file = "aiohttp-3.7.4.post0-cp39-cp39-manylinux2014_s390x.whl", hash = "sha256:a5ca29ee66f8343ed336816c553e82d6cade48a3ad702b9ffa6125d187e2dedb"}, + {file = "aiohttp-3.7.4.post0-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:17c073de315745a1510393a96e680d20af8e67e324f70b42accbd4cb3315c9fb"}, + {file = "aiohttp-3.7.4.post0-cp39-cp39-win32.whl", hash = "sha256:932bb1ea39a54e9ea27fc9232163059a0b8855256f4052e776357ad9add6f1c9"}, + {file = "aiohttp-3.7.4.post0-cp39-cp39-win_amd64.whl", hash = "sha256:02f46fc0e3c5ac58b80d4d56eb0a7c7d97fcef69ace9326289fb9f1955e65cfe"}, + {file = "aiohttp-3.7.4.post0.tar.gz", hash = "sha256:493d3299ebe5f5a7c66b9819eacdcfbbaaf1a8e84911ddffcdc48888497afecf"}, ] aioredis = [ {file = "aioredis-1.3.1-py3-none-any.whl", hash = "sha256:b61808d7e97b7cd5a92ed574937a079c9387fdadd22bfbfa7ad2fd319ecc26e3"}, @@ -798,16 +831,16 @@ cfgv = [ {file = "cfgv-3.2.0.tar.gz", hash = "sha256:cf22deb93d4bcf92f345a5c3cd39d3d41d6340adc60c78bbbd6588c384fda6a1"}, ] chardet = [ - {file = "chardet-3.0.4-py2.py3-none-any.whl", hash = "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"}, - {file = "chardet-3.0.4.tar.gz", hash = "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae"}, + {file = "chardet-4.0.0-py2.py3-none-any.whl", hash = "sha256:f864054d66fd9118f2e67044ac8981a54775ec5b67aed0441892edb553d21da5"}, + {file = "chardet-4.0.0.tar.gz", hash = "sha256:0d6f53a15db4120f2b08c94f11e7d93d2c911ee118b6b30a04ec3ee8310179fa"}, ] cycler = [ {file = "cycler-0.10.0-py2.py3-none-any.whl", hash = "sha256:1d8a5ae1ff6c5cf9b93e8811e581232ad8920aeec647c37316ceac982b08cb2d"}, {file = "cycler-0.10.0.tar.gz", hash = "sha256:cd7b2d1018258d7247a71425e9f26463dfb444d411c39569972f4ce586b0c9d8"}, ] "discord.py" = [ - {file = "discord.py-1.5.1-py3-none-any.whl", hash = "sha256:2367359e31f6527f8a936751fc20b09d7495dd6a76b28c8fb13d4ca6c55b7563"}, - {file = "discord.py-1.5.1.tar.gz", hash = "sha256:def00dc50cf36d21346d71bc89f0cad8f18f9a3522978dc18c7796287d47de8b"}, + {file = "discord.py-1.7.2-py3-none-any.whl", hash = "sha256:f179db299c949a8cf0a12c1b1b94d0da9a18e088857154d93ae5ab1d807ec61d"}, + {file = "discord.py-1.7.2.tar.gz", hash = "sha256:114e76cd27362fb919abf7f001a2dbdc77c9a67cff74ed6a89aecd6582ee298e"}, ] distlib = [ {file = "distlib-0.3.1-py2.py3-none-any.whl", hash = "sha256:8c09de2c67b3e7deef7184574fc060ab8a793e7adbb183d942c389c8b13c52fb"}, @@ -979,23 +1012,43 @@ mslex = [ {file = "mslex-0.3.0.tar.gz", hash = "sha256:4a1ac3f25025cad78ad2fe499dd16d42759f7a3801645399cce5c404415daa97"}, ] multidict = [ - {file = "multidict-4.7.6-cp35-cp35m-macosx_10_14_x86_64.whl", hash = "sha256:275ca32383bc5d1894b6975bb4ca6a7ff16ab76fa622967625baeebcf8079000"}, - {file = "multidict-4.7.6-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:1ece5a3369835c20ed57adadc663400b5525904e53bae59ec854a5d36b39b21a"}, - {file = "multidict-4.7.6-cp35-cp35m-win32.whl", hash = "sha256:5141c13374e6b25fe6bf092052ab55c0c03d21bd66c94a0e3ae371d3e4d865a5"}, - {file = "multidict-4.7.6-cp35-cp35m-win_amd64.whl", hash = "sha256:9456e90649005ad40558f4cf51dbb842e32807df75146c6d940b6f5abb4a78f3"}, - {file = "multidict-4.7.6-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:e0d072ae0f2a179c375f67e3da300b47e1a83293c554450b29c900e50afaae87"}, - {file = "multidict-4.7.6-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:3750f2205b800aac4bb03b5ae48025a64e474d2c6cc79547988ba1d4122a09e2"}, - {file = "multidict-4.7.6-cp36-cp36m-win32.whl", hash = "sha256:f07acae137b71af3bb548bd8da720956a3bc9f9a0b87733e0899226a2317aeb7"}, - {file = "multidict-4.7.6-cp36-cp36m-win_amd64.whl", hash = "sha256:6513728873f4326999429a8b00fc7ceddb2509b01d5fd3f3be7881a257b8d463"}, - {file = "multidict-4.7.6-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:feed85993dbdb1dbc29102f50bca65bdc68f2c0c8d352468c25b54874f23c39d"}, - {file = "multidict-4.7.6-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:fcfbb44c59af3f8ea984de67ec7c306f618a3ec771c2843804069917a8f2e255"}, - {file = "multidict-4.7.6-cp37-cp37m-win32.whl", hash = "sha256:4538273208e7294b2659b1602490f4ed3ab1c8cf9dbdd817e0e9db8e64be2507"}, - {file = "multidict-4.7.6-cp37-cp37m-win_amd64.whl", hash = "sha256:d14842362ed4cf63751648e7672f7174c9818459d169231d03c56e84daf90b7c"}, - {file = "multidict-4.7.6-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:c026fe9a05130e44157b98fea3ab12969e5b60691a276150db9eda71710cd10b"}, - {file = "multidict-4.7.6-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:51a4d210404ac61d32dada00a50ea7ba412e6ea945bbe992e4d7a595276d2ec7"}, - {file = "multidict-4.7.6-cp38-cp38-win32.whl", hash = "sha256:5cf311a0f5ef80fe73e4f4c0f0998ec08f954a6ec72b746f3c179e37de1d210d"}, - {file = "multidict-4.7.6-cp38-cp38-win_amd64.whl", hash = "sha256:7388d2ef3c55a8ba80da62ecfafa06a1c097c18032a501ffd4cabbc52d7f2b19"}, - {file = "multidict-4.7.6.tar.gz", hash = "sha256:fbb77a75e529021e7c4a8d4e823d88ef4d23674a202be4f5addffc72cbb91430"}, + {file = "multidict-5.1.0-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:b7993704f1a4b204e71debe6095150d43b2ee6150fa4f44d6d966ec356a8d61f"}, + {file = "multidict-5.1.0-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:9dd6e9b1a913d096ac95d0399bd737e00f2af1e1594a787e00f7975778c8b2bf"}, + {file = "multidict-5.1.0-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:f21756997ad8ef815d8ef3d34edd98804ab5ea337feedcd62fb52d22bf531281"}, + {file = "multidict-5.1.0-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:1ab820665e67373de5802acae069a6a05567ae234ddb129f31d290fc3d1aa56d"}, + {file = "multidict-5.1.0-cp36-cp36m-manylinux2014_ppc64le.whl", hash = "sha256:9436dc58c123f07b230383083855593550c4d301d2532045a17ccf6eca505f6d"}, + {file = "multidict-5.1.0-cp36-cp36m-manylinux2014_s390x.whl", hash = "sha256:830f57206cc96ed0ccf68304141fec9481a096c4d2e2831f311bde1c404401da"}, + {file = "multidict-5.1.0-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:2e68965192c4ea61fff1b81c14ff712fc7dc15d2bd120602e4a3494ea6584224"}, + {file = "multidict-5.1.0-cp36-cp36m-win32.whl", hash = "sha256:2f1a132f1c88724674271d636e6b7351477c27722f2ed789f719f9e3545a3d26"}, + {file = "multidict-5.1.0-cp36-cp36m-win_amd64.whl", hash = "sha256:3a4f32116f8f72ecf2a29dabfb27b23ab7cdc0ba807e8459e59a93a9be9506f6"}, + {file = "multidict-5.1.0-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:46c73e09ad374a6d876c599f2328161bcd95e280f84d2060cf57991dec5cfe76"}, + {file = "multidict-5.1.0-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:018132dbd8688c7a69ad89c4a3f39ea2f9f33302ebe567a879da8f4ca73f0d0a"}, + {file = "multidict-5.1.0-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:4b186eb7d6ae7c06eb4392411189469e6a820da81447f46c0072a41c748ab73f"}, + {file = "multidict-5.1.0-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:3a041b76d13706b7fff23b9fc83117c7b8fe8d5fe9e6be45eee72b9baa75f348"}, + {file = "multidict-5.1.0-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:051012ccee979b2b06be928a6150d237aec75dd6bf2d1eeeb190baf2b05abc93"}, + {file = "multidict-5.1.0-cp37-cp37m-manylinux2014_s390x.whl", hash = "sha256:6a4d5ce640e37b0efcc8441caeea8f43a06addace2335bd11151bc02d2ee31f9"}, + {file = "multidict-5.1.0-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:5cf3443199b83ed9e955f511b5b241fd3ae004e3cb81c58ec10f4fe47c7dce37"}, + {file = "multidict-5.1.0-cp37-cp37m-win32.whl", hash = "sha256:f200755768dc19c6f4e2b672421e0ebb3dd54c38d5a4f262b872d8cfcc9e93b5"}, + {file = "multidict-5.1.0-cp37-cp37m-win_amd64.whl", hash = "sha256:05c20b68e512166fddba59a918773ba002fdd77800cad9f55b59790030bab632"}, + {file = "multidict-5.1.0-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:54fd1e83a184e19c598d5e70ba508196fd0bbdd676ce159feb412a4a6664f952"}, + {file = "multidict-5.1.0-cp38-cp38-manylinux1_i686.whl", hash = "sha256:0e3c84e6c67eba89c2dbcee08504ba8644ab4284863452450520dad8f1e89b79"}, + {file = "multidict-5.1.0-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:dc862056f76443a0db4509116c5cd480fe1b6a2d45512a653f9a855cc0517456"}, + {file = "multidict-5.1.0-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:0e929169f9c090dae0646a011c8b058e5e5fb391466016b39d21745b48817fd7"}, + {file = "multidict-5.1.0-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:d81eddcb12d608cc08081fa88d046c78afb1bf8107e6feab5d43503fea74a635"}, + {file = "multidict-5.1.0-cp38-cp38-manylinux2014_s390x.whl", hash = "sha256:585fd452dd7782130d112f7ddf3473ffdd521414674c33876187e101b588738a"}, + {file = "multidict-5.1.0-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:37e5438e1c78931df5d3c0c78ae049092877e5e9c02dd1ff5abb9cf27a5914ea"}, + {file = "multidict-5.1.0-cp38-cp38-win32.whl", hash = "sha256:07b42215124aedecc6083f1ce6b7e5ec5b50047afa701f3442054373a6deb656"}, + {file = "multidict-5.1.0-cp38-cp38-win_amd64.whl", hash = "sha256:929006d3c2d923788ba153ad0de8ed2e5ed39fdbe8e7be21e2f22ed06c6783d3"}, + {file = "multidict-5.1.0-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:b797515be8743b771aa868f83563f789bbd4b236659ba52243b735d80b29ed93"}, + {file = "multidict-5.1.0-cp39-cp39-manylinux1_i686.whl", hash = "sha256:d5c65bdf4484872c4af3150aeebe101ba560dcfb34488d9a8ff8dbcd21079647"}, + {file = "multidict-5.1.0-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:b47a43177a5e65b771b80db71e7be76c0ba23cc8aa73eeeb089ed5219cdbe27d"}, + {file = "multidict-5.1.0-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:806068d4f86cb06af37cd65821554f98240a19ce646d3cd24e1c33587f313eb8"}, + {file = "multidict-5.1.0-cp39-cp39-manylinux2014_ppc64le.whl", hash = "sha256:46dd362c2f045095c920162e9307de5ffd0a1bfbba0a6e990b344366f55a30c1"}, + {file = "multidict-5.1.0-cp39-cp39-manylinux2014_s390x.whl", hash = "sha256:ace010325c787c378afd7f7c1ac66b26313b3344628652eacd149bdd23c68841"}, + {file = "multidict-5.1.0-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:ecc771ab628ea281517e24fd2c52e8f31c41e66652d07599ad8818abaad38cda"}, + {file = "multidict-5.1.0-cp39-cp39-win32.whl", hash = "sha256:fc13a9524bc18b6fb6e0dbec3533ba0496bbed167c56d0aabefd965584557d80"}, + {file = "multidict-5.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:7df80d07818b385f3129180369079bd6934cf70469f99daaebfac89dca288359"}, + {file = "multidict-5.1.0.tar.gz", hash = "sha256:25b4e5f22d3a37ddf3effc0710ba692cfc792c2b9edfb9c05aefe823256e84d5"}, ] nodeenv = [ {file = "nodeenv-1.6.0-py2.py3-none-any.whl", hash = "sha256:621e6b7076565ddcacd2db0294c0381e01fd28945ab36bcf00f41c5daf63bef7"}, @@ -1230,6 +1283,11 @@ toml = [ {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, ] +typing-extensions = [ + {file = "typing_extensions-3.10.0.0-py2-none-any.whl", hash = "sha256:0ac0f89795dd19de6b97debb0c6af1c70987fd80a2d62d1958f7e56fcc31b497"}, + {file = "typing_extensions-3.10.0.0-py3-none-any.whl", hash = "sha256:779383f6086d90c99ae41cf0ff39aac8a7937a9283ce0a414e5dd782f4c94a84"}, + {file = "typing_extensions-3.10.0.0.tar.gz", hash = "sha256:50b6f157849174217d0656f99dc82fe932884fb250826c18350e159ec6cdf342"}, +] urllib3 = [ {file = "urllib3-1.26.4-py2.py3-none-any.whl", hash = "sha256:2f4da4594db7e1e110a944bb1b551fdf4e6c136ad42e4234131391e21eb5b0df"}, {file = "urllib3-1.26.4.tar.gz", hash = "sha256:e7b021f7241115872f92f43c6508082facffbd1c048e3c6e2bb9c2a157e28937"}, @@ -1239,21 +1297,41 @@ virtualenv = [ {file = "virtualenv-20.4.6.tar.gz", hash = "sha256:72cf267afc04bf9c86ec932329b7e94db6a0331ae9847576daaa7ca3c86b29a4"}, ] yarl = [ - {file = "yarl-1.5.1-cp35-cp35m-macosx_10_14_x86_64.whl", hash = "sha256:db6db0f45d2c63ddb1a9d18d1b9b22f308e52c83638c26b422d520a815c4b3fb"}, - {file = "yarl-1.5.1-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:17668ec6722b1b7a3a05cc0167659f6c95b436d25a36c2d52db0eca7d3f72593"}, - {file = "yarl-1.5.1-cp35-cp35m-win32.whl", hash = "sha256:040b237f58ff7d800e6e0fd89c8439b841f777dd99b4a9cca04d6935564b9409"}, - {file = "yarl-1.5.1-cp35-cp35m-win_amd64.whl", hash = "sha256:f18d68f2be6bf0e89f1521af2b1bb46e66ab0018faafa81d70f358153170a317"}, - {file = "yarl-1.5.1-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:c52ce2883dc193824989a9b97a76ca86ecd1fa7955b14f87bf367a61b6232511"}, - {file = "yarl-1.5.1-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:ce584af5de8830d8701b8979b18fcf450cef9a382b1a3c8ef189bedc408faf1e"}, - {file = "yarl-1.5.1-cp36-cp36m-win32.whl", hash = "sha256:df89642981b94e7db5596818499c4b2219028f2a528c9c37cc1de45bf2fd3a3f"}, - {file = "yarl-1.5.1-cp36-cp36m-win_amd64.whl", hash = "sha256:3a584b28086bc93c888a6c2aa5c92ed1ae20932f078c46509a66dce9ea5533f2"}, - {file = "yarl-1.5.1-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:da456eeec17fa8aa4594d9a9f27c0b1060b6a75f2419fe0c00609587b2695f4a"}, - {file = "yarl-1.5.1-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:bc2f976c0e918659f723401c4f834deb8a8e7798a71be4382e024bcc3f7e23a8"}, - {file = "yarl-1.5.1-cp37-cp37m-win32.whl", hash = "sha256:4439be27e4eee76c7632c2427ca5e73703151b22cae23e64adb243a9c2f565d8"}, - {file = "yarl-1.5.1-cp37-cp37m-win_amd64.whl", hash = "sha256:48e918b05850fffb070a496d2b5f97fc31d15d94ca33d3d08a4f86e26d4e7c5d"}, - {file = "yarl-1.5.1-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:9b930776c0ae0c691776f4d2891ebc5362af86f152dd0da463a6614074cb1b02"}, - {file = "yarl-1.5.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:b3b9ad80f8b68519cc3372a6ca85ae02cc5a8807723ac366b53c0f089db19e4a"}, - {file = "yarl-1.5.1-cp38-cp38-win32.whl", hash = "sha256:f379b7f83f23fe12823085cd6b906edc49df969eb99757f58ff382349a3303c6"}, - {file = "yarl-1.5.1-cp38-cp38-win_amd64.whl", hash = "sha256:9102b59e8337f9874638fcfc9ac3734a0cfadb100e47d55c20d0dc6087fb4692"}, - {file = "yarl-1.5.1.tar.gz", hash = "sha256:c22c75b5f394f3d47105045ea551e08a3e804dc7e01b37800ca35b58f856c3d6"}, + {file = "yarl-1.6.3-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:0355a701b3998dcd832d0dc47cc5dedf3874f966ac7f870e0f3a6788d802d434"}, + {file = "yarl-1.6.3-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:bafb450deef6861815ed579c7a6113a879a6ef58aed4c3a4be54400ae8871478"}, + {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:547f7665ad50fa8563150ed079f8e805e63dd85def6674c97efd78eed6c224a6"}, + {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:63f90b20ca654b3ecc7a8d62c03ffa46999595f0167d6450fa8383bab252987e"}, + {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_ppc64le.whl", hash = "sha256:97b5bdc450d63c3ba30a127d018b866ea94e65655efaf889ebeabc20f7d12406"}, + {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_s390x.whl", hash = "sha256:d8d07d102f17b68966e2de0e07bfd6e139c7c02ef06d3a0f8d2f0f055e13bb76"}, + {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:15263c3b0b47968c1d90daa89f21fcc889bb4b1aac5555580d74565de6836366"}, + {file = "yarl-1.6.3-cp36-cp36m-win32.whl", hash = "sha256:b5dfc9a40c198334f4f3f55880ecf910adebdcb2a0b9a9c23c9345faa9185721"}, + {file = "yarl-1.6.3-cp36-cp36m-win_amd64.whl", hash = "sha256:b2e9a456c121e26d13c29251f8267541bd75e6a1ccf9e859179701c36a078643"}, + {file = "yarl-1.6.3-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:ce3beb46a72d9f2190f9e1027886bfc513702d748047b548b05dab7dfb584d2e"}, + {file = "yarl-1.6.3-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:2ce4c621d21326a4a5500c25031e102af589edb50c09b321049e388b3934eec3"}, + {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:d26608cf178efb8faa5ff0f2d2e77c208f471c5a3709e577a7b3fd0445703ac8"}, + {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:4c5bcfc3ed226bf6419f7a33982fb4b8ec2e45785a0561eb99274ebbf09fdd6a"}, + {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:4736eaee5626db8d9cda9eb5282028cc834e2aeb194e0d8b50217d707e98bb5c"}, + {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_s390x.whl", hash = "sha256:68dc568889b1c13f1e4745c96b931cc94fdd0defe92a72c2b8ce01091b22e35f"}, + {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:7356644cbed76119d0b6bd32ffba704d30d747e0c217109d7979a7bc36c4d970"}, + {file = "yarl-1.6.3-cp37-cp37m-win32.whl", hash = "sha256:00d7ad91b6583602eb9c1d085a2cf281ada267e9a197e8b7cae487dadbfa293e"}, + {file = "yarl-1.6.3-cp37-cp37m-win_amd64.whl", hash = "sha256:69ee97c71fee1f63d04c945f56d5d726483c4762845400a6795a3b75d56b6c50"}, + {file = "yarl-1.6.3-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:e46fba844f4895b36f4c398c5af062a9808d1f26b2999c58909517384d5deda2"}, + {file = "yarl-1.6.3-cp38-cp38-manylinux1_i686.whl", hash = "sha256:31ede6e8c4329fb81c86706ba8f6bf661a924b53ba191b27aa5fcee5714d18ec"}, + {file = "yarl-1.6.3-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:fcbb48a93e8699eae920f8d92f7160c03567b421bc17362a9ffbbd706a816f71"}, + {file = "yarl-1.6.3-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:72a660bdd24497e3e84f5519e57a9ee9220b6f3ac4d45056961bf22838ce20cc"}, + {file = "yarl-1.6.3-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:324ba3d3c6fee56e2e0b0d09bf5c73824b9f08234339d2b788af65e60040c959"}, + {file = "yarl-1.6.3-cp38-cp38-manylinux2014_s390x.whl", hash = "sha256:e6b5460dc5ad42ad2b36cca524491dfcaffbfd9c8df50508bddc354e787b8dc2"}, + {file = "yarl-1.6.3-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:6d6283d8e0631b617edf0fd726353cb76630b83a089a40933043894e7f6721e2"}, + {file = "yarl-1.6.3-cp38-cp38-win32.whl", hash = "sha256:9ede61b0854e267fd565e7527e2f2eb3ef8858b301319be0604177690e1a3896"}, + {file = "yarl-1.6.3-cp38-cp38-win_amd64.whl", hash = "sha256:f0b059678fd549c66b89bed03efcabb009075bd131c248ecdf087bdb6faba24a"}, + {file = "yarl-1.6.3-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:329412812ecfc94a57cd37c9d547579510a9e83c516bc069470db5f75684629e"}, + {file = "yarl-1.6.3-cp39-cp39-manylinux1_i686.whl", hash = "sha256:c49ff66d479d38ab863c50f7bb27dee97c6627c5fe60697de15529da9c3de724"}, + {file = "yarl-1.6.3-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:f040bcc6725c821a4c0665f3aa96a4d0805a7aaf2caf266d256b8ed71b9f041c"}, + {file = "yarl-1.6.3-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:d5c32c82990e4ac4d8150fd7652b972216b204de4e83a122546dce571c1bdf25"}, + {file = "yarl-1.6.3-cp39-cp39-manylinux2014_ppc64le.whl", hash = "sha256:d597767fcd2c3dc49d6eea360c458b65643d1e4dbed91361cf5e36e53c1f8c96"}, + {file = "yarl-1.6.3-cp39-cp39-manylinux2014_s390x.whl", hash = "sha256:8aa3decd5e0e852dc68335abf5478a518b41bf2ab2f330fe44916399efedfae0"}, + {file = "yarl-1.6.3-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:73494d5b71099ae8cb8754f1df131c11d433b387efab7b51849e7e1e851f07a4"}, + {file = "yarl-1.6.3-cp39-cp39-win32.whl", hash = "sha256:5b883e458058f8d6099e4420f0cc2567989032b5f34b271c0827de9f1079a424"}, + {file = "yarl-1.6.3-cp39-cp39-win_amd64.whl", hash = "sha256:4953fb0b4fdb7e08b2f3b3be80a00d28c5c8a2056bb066169de00e6501b986b6"}, + {file = "yarl-1.6.3.tar.gz", hash = "sha256:8a9066529240171b68893d60dca86a763eae2139dd42f42106b03cf4b426bf10"}, ] diff --git a/pyproject.toml b/pyproject.toml index 8a79ea4c..2528511e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,7 @@ pillow = "~=8.1" pytz = "~=2019.2" sentry-sdk = "~=0.19" PyYAML = "~=5.4" -"discord.py" = "~=1.5.1" +"discord.py" = "~=1.7.2" async-rediscache = {extras = ["fakeredis"], version = "~=0.1.4"} emojis = "~=0.6.0" matplotlib = "~=3.4.1" -- cgit v1.2.3 From ca9232b11acf012b8525871ec02428cae7f2c205 Mon Sep 17 00:00:00 2001 From: ChrisJL Date: Sun, 16 May 2021 16:53:09 +0100 Subject: Type hint optional parameter Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/utils/pagination.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/utils/pagination.py b/bot/utils/pagination.py index a0a362cb..d9c0862a 100644 --- a/bot/utils/pagination.py +++ b/bot/utils/pagination.py @@ -32,7 +32,7 @@ class LinePaginator(Paginator): prefix: str = '```', suffix: str = '```', max_size: int = 2000, - max_lines: int = None, + max_lines: Optional[int] = None, linesep: str = "\n" ): """ -- cgit v1.2.3 From 90dcb6c2bc5005ebc1d890b6a194a9b53521de0a Mon Sep 17 00:00:00 2001 From: vcokltfre Date: Sun, 16 May 2021 19:02:03 +0100 Subject: fix: use resolved reference --- bot/exts/evergreen/bookmark.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot') diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index c84446c5..85c9b46f 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -97,7 +97,7 @@ class Bookmark(commands.Cog): if not target_message: if not ctx.message.reference: raise commands.UserInputError("You must either provide a valid message to bookmark, or reply to one.") - target_message = await ctx.fetch_message(ctx.message.reference.message_id) + target_message = ctx.message.reference.resolved # Prevent users from bookmarking a message in a channel they don't have access to permissions = ctx.author.permissions_in(target_message.channel) -- cgit v1.2.3