From 64424091fe52d941ee40f83e0472f5c045e6eb30 Mon Sep 17 00:00:00 2001 From: Zalko <88582103+Zalk0@users.noreply.github.com> Date: Wed, 29 Nov 2023 15:59:46 +0100 Subject: [PATCH] feat: try ruff --- .github/{dependabot.yml => dependabot.yaml} | 0 .github/workflows/python-app.yml | 40 --------- .github/workflows/ruff.yaml | 21 +++++ .gitignore | 3 + bot.py | 67 ++++++++++------ commands/admin.py | 8 +- commands/skyblock.py | 89 +++++++++++++++------ commands/utils.py | 40 ++++++--- commands_list.py | 67 ++++++++++------ main.py | 21 +++-- pyproject.toml | 7 ++ responses.py | 28 +++++-- src/latex_render.py | 48 ++++++----- src/skyblock_guild.py | 23 ++++-- tasks.py | 10 ++- 15 files changed, 304 insertions(+), 168 deletions(-) rename .github/{dependabot.yml => dependabot.yaml} (100%) delete mode 100644 .github/workflows/python-app.yml create mode 100644 .github/workflows/ruff.yaml create mode 100644 pyproject.toml diff --git a/.github/dependabot.yml b/.github/dependabot.yaml similarity index 100% rename from .github/dependabot.yml rename to .github/dependabot.yaml diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml deleted file mode 100644 index 6d1e361..0000000 --- a/.github/workflows/python-app.yml +++ /dev/null @@ -1,40 +0,0 @@ -# This workflow will install Python dependencies, run lint with a single version of Python -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python - -name: Python lint - -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] - -permissions: - contents: read - -jobs: - build: - runs-on: ubuntu-latest - strategy: - matrix: - # python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] - python-version: ["3.12"] - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python-version }} - cache: "pip" - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install flake8 - if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - - name: Lint with flake8 - run: | - # stop the build if there are Python syntax errors or undefined names - flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics - # exit-zero treats all errors as warnings. - flake8 . --count --exit-zero --max-line-length=119 --statistics >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/ruff.yaml b/.github/workflows/ruff.yaml new file mode 100644 index 0000000..ac83019 --- /dev/null +++ b/.github/workflows/ruff.yaml @@ -0,0 +1,21 @@ +name: Ruff + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +permissions: + contents: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Lint & format + uses: chartboost/ruff-action@v1 + with: + args: "check format --fix" diff --git a/.gitignore b/.gitignore index 38ba337..a0466ae 100644 --- a/.gitignore +++ b/.gitignore @@ -11,5 +11,8 @@ venv/ # Python's cache __pycache__/ +# Ruff's cache +.ruff_cache/ + # Logs folder logs/ diff --git a/bot.py b/bot.py index 28bd1fd..d38d2df 100644 --- a/bot.py +++ b/bot.py @@ -11,33 +11,44 @@ # Create a class of the bot class ChouetteBot(discord.Client): - # Initialization when class is called def __init__(self): # Associate the env variables to the bot self.config = os.environ # Define the bot debug log level - self.bot_logger = logging.getLogger('bot') - log_level = logging.getLevelName(self.config.get('LOG_LEVEL', logging.INFO)) - self.log_level = log_level if isinstance(log_level, int) else logging.INFO + self.bot_logger = logging.getLogger("bot") + log_level = logging.getLevelName( + self.config.get("LOG_LEVEL", logging.INFO) + ) + self.log_level = ( + log_level if isinstance(log_level, int) else logging.INFO + ) self.bot_logger.setLevel(self.log_level) # Set intents for the bot intents = discord.Intents.all() # Set activity of the bot - activity_type = {"playing": 0, - "streaming": 1, - "listening": 2, - "watching": 3, - "custom": 4, # Idk what it is - "competing": 5} - activity = discord.Activity(type=activity_type.get(self.config['BOT_ACTIVITY_TYPE']), - name=self.config['BOT_ACTIVITY_NAME']) + activity_type = { + "playing": 0, + "streaming": 1, + "listening": 2, + "watching": 3, + "custom": 4, # Idk what it is + "competing": 5, + } + activity = discord.Activity( + type=activity_type.get(self.config["BOT_ACTIVITY_TYPE"]), + name=self.config["BOT_ACTIVITY_NAME"], + ) # Apply intents, activity and status to the bot - super().__init__(intents=intents, activity=activity, status=self.config['BOT_STATUS']) + super().__init__( + intents=intents, + activity=activity, + status=self.config["BOT_STATUS"], + ) # Declare command tree self.tree = discord.app_commands.CommandTree(self) @@ -57,7 +68,9 @@ async def on_ready(self): # Executed once when bot is ready if self.first: # Hypixel guild - hypixel_guild = self.get_guild(int(self.config['HYPIXEL_GUILD_ID'])) + hypixel_guild = self.get_guild( + int(self.config["HYPIXEL_GUILD_ID"]) + ) # Call commands and import tasks await commands(self.tree, hypixel_guild) @@ -87,18 +100,24 @@ async def on_message(self, message: discord.Message): # Do a log on the Python console if message.guild is not None: - self.bot_logger.debug(f'{author} said: "{user_msg}" #{channel} in {message.guild.name}') + self.bot_logger.debug( + f'{author} said: "{user_msg}" #{channel} in {message.guild.name}' + ) else: - self.bot_logger.debug(f'{author} said: "{user_msg}" in Direct Message') + self.bot_logger.debug( + f'{author} said: "{user_msg}" in Direct Message' + ) # Call responses with message of the user and responds if necessary response = await responses(self, channel, user_msg, author) - if not response[0] == '': + if not response[0] == "": if response[1]: await channel.send(response[0], reference=message) else: await channel.send(response[0]) - self.bot_logger.info(f'{self.user} responded to {author}: "{response[0]}"') + self.bot_logger.info( + f'{self.user} responded to {author}: "{response[0]}"' + ) async def is_team_member_or_owner(self, author: discord.User) -> bool: if not self.owners: @@ -112,15 +131,15 @@ async def is_team_member_or_owner(self, author: discord.User) -> bool: # Add a basic HTTP server to check if the bot is up async def start_server(self): # Set a logger for the webserver - web_logger = logging.getLogger('web') + web_logger = logging.getLogger("web") # Don't want to spam logs with site access if self.log_level >= logging.INFO: - logging.getLogger('aiohttp.access').setLevel(logging.ERROR) + logging.getLogger("aiohttp.access").setLevel(logging.ERROR) # Set some basic headers for security headers = { "X-Content-Type-Options": "nosniff", - "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'" + "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'", } # Remove the Server header and apply the headers @@ -135,10 +154,12 @@ async def handler(req: web.Request): app = web.Application() app.on_response_prepare.append(_default_headers) - app.add_routes([web.get('/', handler)]) + app.add_routes([web.get("/", handler)]) runner = web.AppRunner(app) await runner.setup() - site = web.TCPSite(runner, self.config['SERVER_HOST'], int(self.config['SERVER_PORT'])) + site = web.TCPSite( + runner, self.config["SERVER_HOST"], int(self.config["SERVER_PORT"]) + ) try: await site.start() except Exception as e: diff --git a/commands/admin.py b/commands/admin.py index 0d4d27e..e2331b7 100644 --- a/commands/admin.py +++ b/commands/admin.py @@ -19,5 +19,9 @@ async def is_admin(interaction: discord.Interaction[ChouetteBot]): @app_commands.check(is_admin) @app_commands.command(name="whisper", description="Whisper an admin message") async def whisper(interaction: discord.Interaction[ChouetteBot], message: str): - await interaction.channel.send(f"{interaction.client.user.name} wants to say this message: {message}") - await interaction.response.send_message("Commande réussie", ephemeral=True, delete_after=2) + await interaction.channel.send( + f"{interaction.client.user.name} wants to say this message: {message}" + ) + await interaction.response.send_message( + "Commande réussie", ephemeral=True, delete_after=2 + ) diff --git a/commands/skyblock.py b/commands/skyblock.py index 95a25cd..d3bc88f 100644 --- a/commands/skyblock.py +++ b/commands/skyblock.py @@ -17,33 +17,52 @@ class Skyblock(app_commands.Group): # Set command group name and description def __init__(self): - super().__init__(name="skyblock", description="Hypixel Skyblock related commands") + super().__init__( + name="skyblock", description="Hypixel Skyblock related commands" + ) # Make a command to check the version of mods for Hypixel Skyblock - @app_commands.command(name="mods", - description="Check the latest release of the most popular mods for the Hypixel Skyblock") + @app_commands.command( + name="mods", + description="Check the latest release of the most popular mods for the Hypixel Skyblock", + ) async def mods(self, interaction: discord.Interaction[ChouetteBot]): await interaction.response.defer(thinking=True) api_github = "https://api.github.com/repos/" async with aiohttp.ClientSession() as session: - async with session.get(f"{api_github}Dungeons-Guide/Skyblock-Dungeons-Guide/releases/latest") as response: + async with session.get( + f"{api_github}Dungeons-Guide/Skyblock-Dungeons-Guide/releases/latest" + ) as response: dungeonsguide = await response.json() - async with session.get(f"{api_github}Moulberry/NotEnoughUpdates/releases/latest") as response: + async with session.get( + f"{api_github}Moulberry/NotEnoughUpdates/releases/latest" + ) as response: notenoughupdates = await response.json() - async with session.get(f"{api_github}BiscuitDevelopment/SkyblockAddons/releases/latest") as response: + async with session.get( + f"{api_github}BiscuitDevelopment/SkyblockAddons/releases/latest" + ) as response: skyblockaddons = await response.json() - async with session.get(f"{api_github}Skytils/SkytilsMod/releases/latest") as response: + async with session.get( + f"{api_github}Skytils/SkytilsMod/releases/latest" + ) as response: skytils = await response.json() - await interaction.followup.send(f"The latest releases are :\n" - f"Dungeons Guide : `{dungeonsguide['name'].replace('v', '')}`\n" - f"Not Enough Updates : `{notenoughupdates['name']}`\n" - f"SkyblockAddons : `{skyblockaddons['name'].replace('Patch v', '')}`\n" - f"Skytils : `{skytils['name'].replace('Skytils ', '')}`") + await interaction.followup.send( + f"The latest releases are :\n" + f"Dungeons Guide : `{dungeonsguide['name'].replace('v', '')}`\n" + f"Not Enough Updates : `{notenoughupdates['name']}`\n" + f"SkyblockAddons : `{skyblockaddons['name'].replace('Patch v', '')}`\n" + f"Skytils : `{skytils['name'].replace('Skytils ', '')}`" + ) # Make a command to check if it's raining in Spider's Den in Hypixel Skyblock - @app_commands.command(name="spider_rain", description="Show the time until the next rain and thunderstorm") + @app_commands.command( + name="spider_rain", + description="Show the time until the next rain and thunderstorm", + ) async def spider(self, interaction: discord.Interaction[ChouetteBot]): - utc_last_thunderstorm = round(datetime(2023, 3, 27, 1, 45, 56, tzinfo=timezone.utc).timestamp()) + utc_last_thunderstorm = round( + datetime(2023, 3, 27, 1, 45, 56, tzinfo=timezone.utc).timestamp() + ) time_now = round(datetime.now(tz=timezone.utc).timestamp()) base = time_now - utc_last_thunderstorm thunderstorm = base % ((3850 + 1000) * 4) @@ -56,24 +75,46 @@ async def spider(self, interaction: discord.Interaction[ChouetteBot]): rain_msg = f"The rain will end " if thunderstorm <= (3850 * 4 + 1000 * 3): next_thunderstorm = time_now + (3850 * 4 + 1000 * 3) - thunderstorm - thunderstorm_msg = f"The next thunderstorm will be " + thunderstorm_msg = ( + f"The next thunderstorm will be " + ) else: - thunderstorm_duration = time_now + (3850 * 4 + 1000 * 4) - thunderstorm - thunderstorm_msg = f"The thunderstorm will end " - await interaction.response.send_message(f"{rain_msg}\n{thunderstorm_msg}") + thunderstorm_duration = ( + time_now + (3850 * 4 + 1000 * 4) - thunderstorm + ) + thunderstorm_msg = ( + f"The thunderstorm will end " + ) + await interaction.response.send_message( + f"{rain_msg}\n{thunderstorm_msg}" + ) # Make a command to check if the user is in the guild in-game - @app_commands.command(name="guild", description="Give a role if in the guild in-game") + @app_commands.command( + name="guild", description="Give a role if in the guild in-game" + ) @app_commands.rename(pseudo="pseudo_mc") - async def in_guild(self, interaction: discord.Interaction[ChouetteBot], pseudo: str): - if interaction.user.get_role(int(interaction.client.config['HYPIXEL_GUILD_ROLE'])): + async def in_guild( + self, interaction: discord.Interaction[ChouetteBot], pseudo: str + ): + if interaction.user.get_role( + int(interaction.client.config["HYPIXEL_GUILD_ROLE"]) + ): await interaction.response.send_message("Vous avez déjà le rôle !") return await interaction.response.defer(thinking=True) - checked = check(pseudo, interaction.client.config['HYPIXEL_GUILD_NAME'], interaction.user.global_name) + checked = check( + pseudo, + interaction.client.config["HYPIXEL_GUILD_NAME"], + interaction.user.global_name, + ) if checked: - role = interaction.guild.get_role(int(interaction.client.config['HYPIXEL_GUILD_ROLE'])) + role = interaction.guild.get_role( + int(interaction.client.config["HYPIXEL_GUILD_ROLE"]) + ) await interaction.user.add_roles(role) - await interaction.followup.send("Vous avez été assigné le rôle de membre !") + await interaction.followup.send( + "Vous avez été assigné le rôle de membre !" + ) else: await interaction.followup.send(checked) diff --git a/commands/utils.py b/commands/utils.py index 15792bf..c5a3c1b 100644 --- a/commands/utils.py +++ b/commands/utils.py @@ -21,21 +21,29 @@ async def latex(interaction: discord.Interaction[ChouetteBot], equation: str): # Make the roll command @app_commands.command(name="roll", description="Roll a die") async def die_roll(interaction: discord.Interaction[ChouetteBot]): - await interaction.response.send_message(f"{random.randint(1, 6)} \N{GAME DIE}") + await interaction.response.send_message( + f"{random.randint(1, 6)} \N{GAME DIE}" + ) # Make the ping command @app_commands.command(name="ping", description="Test the ping of the bot") async def ping(interaction: discord.Interaction[ChouetteBot]): - await interaction.response.send_message(f"Pong! In {round(interaction.client.latency * 1000)}ms") + await interaction.response.send_message( + f"Pong! In {round(interaction.client.latency * 1000)}ms" + ) # Make a cheh command @app_commands.command(name="cheh", description="Cheh somebody") -async def cheh(interaction: discord.Interaction[ChouetteBot], user: discord.Member): +async def cheh( + interaction: discord.Interaction[ChouetteBot], user: discord.Member +): # Check if the user to cheh is the bot or the user sending the command if user == interaction.client.user: - await interaction.response.send_message("Vous ne pouvez pas me **Cheh** !") + await interaction.response.send_message( + "Vous ne pouvez pas me **Cheh** !" + ) elif user == interaction.user: await interaction.response.send_message("**FEUR**") else: @@ -48,26 +56,38 @@ async def cheh(interaction: discord.Interaction[ChouetteBot], user: discord.Memb @app_commands.guild_only @app_commands.checks.bot_has_permissions(manage_messages=True) @app_commands.context_menu(name="Pin/Unpin") -async def pin(interaction: discord.Interaction[ChouetteBot], message: discord.Message): +async def pin( + interaction: discord.Interaction[ChouetteBot], message: discord.Message +): if message.pinned: await message.unpin() - await interaction.response.send_message("The message has been unpinned!", ephemeral=True) + await interaction.response.send_message( + "The message has been unpinned!", ephemeral=True + ) else: await message.pin() - await interaction.response.send_message("The message has been pinned!", ephemeral=True) + await interaction.response.send_message( + "The message has been pinned!", ephemeral=True + ) # Make a context menu command to delete messages @app_commands.guild_only -@app_commands.checks.bot_has_permissions(manage_messages=True, read_message_history=True, read_messages=True) +@app_commands.checks.bot_has_permissions( + manage_messages=True, read_message_history=True, read_messages=True +) @app_commands.checks.has_permissions(manage_messages=True) @app_commands.context_menu(name="Delete until here") -async def delete(interaction: discord.Interaction[ChouetteBot], message: discord.Message): +async def delete( + interaction: discord.Interaction[ChouetteBot], message: discord.Message +): await interaction.response.defer(ephemeral=True, thinking=True) last_id = interaction.channel.last_message_id def is_msg(msg: discord.Message) -> bool: return (message.id >> 22) <= (msg.id >> 22) <= (last_id >> 22) - del_msg = await message.channel.purge(bulk=True, reason="Admin used bulk delete", check=is_msg) + del_msg = await message.channel.purge( + bulk=True, reason="Admin used bulk delete", check=is_msg + ) await interaction.followup.send(f"{len(del_msg)} messages supprimés !") diff --git a/commands_list.py b/commands_list.py index 24d583f..c18aa91 100644 --- a/commands_list.py +++ b/commands_list.py @@ -12,21 +12,23 @@ from bot import ChouetteBot # List the commands -COMMANDS_LIST: Tuple = ( +COMMANDS_LIST: Tuple = ( # noqa: E501 latex, die_roll, ping, cheh, pin, delete, - whisper + whisper, ) SPACES = " " * 38 # List of commands to add to the command tree -async def commands(tree: discord.app_commands.CommandTree, hypixel_guild: discord.Guild): +async def commands( + tree: discord.app_commands.CommandTree, hypixel_guild: discord.Guild +): # Add the commands to the Tree for command in COMMANDS_LIST: tree.add_command(command) @@ -36,36 +38,55 @@ async def commands(tree: discord.app_commands.CommandTree, hypixel_guild: discor # Create a global commands error handler @tree.error - async def on_command_error(interaction: discord.Interaction[ChouetteBot], - error: discord.app_commands.AppCommandError): + async def on_command_error( + interaction: discord.Interaction[ChouetteBot], + error: discord.app_commands.AppCommandError, + ): if isinstance(error, discord.app_commands.BotMissingPermissions): bot_perms = ", ".join(error.missing_permissions) - interaction.client.bot_logger.error(f"{interaction.client.user} is missing {bot_perms} " - f"to do {interaction.command.name} in #{interaction.channel}") + interaction.client.bot_logger.error( + f"{interaction.client.user} is missing {bot_perms} " + f"to do {interaction.command.name} in #{interaction.channel}" + ) if len(error.missing_permissions) == 1: - await interaction.response.send_message(f"I am missing this permission: {bot_perms}", - ephemeral=True) + await interaction.response.send_message( + f"I am missing this permission: {bot_perms}", + ephemeral=True, + ) else: - await interaction.response.send_message(f"I am missing these permissions: {bot_perms}", - ephemeral=True) + await interaction.response.send_message( + f"I am missing these permissions: {bot_perms}", + ephemeral=True, + ) return if isinstance(error, discord.app_commands.MissingPermissions): user_perms = ", ".join(error.missing_permissions) - interaction.client.bot_logger.error(f"{interaction.user} is missing {user_perms} " - f"to do {interaction.command.name} in #{interaction.channel}") + interaction.client.bot_logger.error( + f"{interaction.user} is missing {user_perms} " + f"to do {interaction.command.name} in #{interaction.channel}" + ) if len(error.missing_permissions) == 1: - await interaction.response.send_message(f"You are missing this permission: {user_perms}", - ephemeral=True) + await interaction.response.send_message( + f"You are missing this permission: {user_perms}", + ephemeral=True, + ) else: - await interaction.response.send_message(f"You are missing these permissions: {user_perms}", - ephemeral=True) + await interaction.response.send_message( + f"You are missing these permissions: {user_perms}", + ephemeral=True, + ) return if isinstance(error, discord.app_commands.CheckFailure): - interaction.client.bot_logger.error(f"{interaction.user} tried to do {interaction.command.name} " - f"in #{interaction.channel}\n{SPACES}{error}") - await interaction.response.send_message("You're not allowed to use this command!", - ephemeral=True) + interaction.client.bot_logger.error( + f"{interaction.user} tried to do {interaction.command.name} " + f"in #{interaction.channel}\n{SPACES}{error}" + ) + await interaction.response.send_message( + "You're not allowed to use this command!", ephemeral=True + ) return - await interaction.response.send_message(f"{error}\nThis error is not caught, please signal it!", - ephemeral=True) + await interaction.response.send_message( + f"{error}\nThis error is not caught, please signal it!", + ephemeral=True, + ) interaction.client.bot_logger.error(error) diff --git a/main.py b/main.py index c658aba..9d6b3b9 100644 --- a/main.py +++ b/main.py @@ -8,21 +8,30 @@ def main(): # Load the .env values if a .env file exists - if Path('.env').is_file(): + if Path(".env").is_file(): load_dotenv() # Create an instance of the ChouetteBot client = ChouetteBot() # Setup the logging - Path('logs').mkdir(exist_ok=True) - handler = handlers.RotatingFileHandler(filename=Path('logs', 'bot.log'), backupCount=3, - encoding='utf-8', delay=True) + Path("logs").mkdir(exist_ok=True) + handler = handlers.RotatingFileHandler( + filename=Path("logs", "bot.log"), + backupCount=3, + encoding="utf-8", + delay=True, + ) handler.doRollover() # Run the client with the token - client.run(client.config['BOT_TOKEN'], reconnect=True, log_handler=handler, root_logger=True) + client.run( + client.config["BOT_TOKEN"], + reconnect=True, + log_handler=handler, + root_logger=True, + ) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..773ae6b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,7 @@ +[project] +requires-python = ">=3.8" + + +[tool.ruff] +line-length = 79 +extend-exclude = ["venv38"] diff --git a/responses.py b/responses.py index 4ab21dd..141886f 100644 --- a/responses.py +++ b/responses.py @@ -11,19 +11,29 @@ from bot import ChouetteBot -async def responses(client: ChouetteBot, channel: Messageable, message: str, author: discord.User) -> tuple[str, bool]: +async def responses( + client: ChouetteBot, + channel: Messageable, + message: str, + author: discord.User, +) -> tuple[str, bool]: # Checks if a message ends with quoi - if ''.join(filter(str.isalpha, message)).lower().endswith("quoi"): + if "".join(filter(str.isalpha, message)).lower().endswith("quoi"): return "**FEUR**", False # Checks if a message contains $$ to signify LaTeX expression if message.count("$") > 1: if (message.count("$") % 2) == 0: await channel.send(file=await latex_process(message)) - client.bot_logger.info(f'{client.user} responded to {author}: "equation.png"') - return '', False - return "Nombre de $ impair, " \ - "veuillez en mettre un nombre pair pour que je puisse afficher les équations LaTeX !", False + client.bot_logger.info( + f'{client.user} responded to {author}: "equation.png"' + ) + return "", False + return ( + "Nombre de $ impair, " + "veuillez en mettre un nombre pair pour que je puisse afficher les équations LaTeX !", + False, + ) # Add command to sync slash commands for team members and owner of the bot if message == f"{client.user.mention} sync": @@ -36,7 +46,9 @@ async def responses(client: ChouetteBot, channel: Messageable, message: str, aut except discord.app_commands.CommandSyncFailure as e: client.bot_logger.error(e) return str(e), True - client.bot_logger.info(f"{author}, who isn't authorized, tried to sync the commands") + client.bot_logger.info( + f"{author}, who isn't authorized, tried to sync the commands" + ) # Return empty string if no condition is checked - return '', False + return "", False diff --git a/src/latex_render.py b/src/latex_render.py index 2c0a81e..42d423b 100644 --- a/src/latex_render.py +++ b/src/latex_render.py @@ -10,20 +10,22 @@ async def latex_render(equation: str) -> discord.File: options = r"\dpi{200} \bg_black \color[RGB]{240, 240, 240} \pagecolor[RGB]{49, 51, 56}" # bg_black is for putting a black background (custom command of the site) instead of a transparent one # only then a custom background color can be used with pagecolor. color is for the text color - url = f"https://latex.codecogs.com/png.latex?{options} {equation}".replace(" ", "%20") + url = f"https://latex.codecogs.com/png.latex?{options} {equation}".replace( + " ", "%20" + ) async with aiohttp.ClientSession() as session: async with session.get(url) as response: response_content = await response.read() - return discord.File(BytesIO(response_content), filename='equation.png') + return discord.File(BytesIO(response_content), filename="equation.png") # Make a LaTeX process function to use when LaTeX maths is inserted in a message async def latex_process(message: str): message = await latex_replace(message) parts = message.split("$") - equation = r'\\' + equation = r"\\" for i in range(len(parts)): - if i != '': + if i != "": if i % 2: # It's maths, so nothing to do equation += f" {parts[i]}" else: # It's text @@ -33,27 +35,29 @@ async def latex_process(message: str): equation += rf" \textrm{{{linebreak}}}" else: equation += rf" \textrm{{{parts[i]}}}" - return await latex_render(equation.replace(r" \textrm{}", '')) + return await latex_render(equation.replace(r" \textrm{}", "")) # LaTeX replace accents and special characters to commands # TODO: Add all the symbols that may appear async def latex_replace(message: str) -> str: - message = message.replace(r"ù", r"\`u") \ - .replace(r"é", r"\'e") \ - .replace(r"è", r"\`e") \ - .replace(r"ê", r"\^e") \ - .replace(r"à", r"\`a") \ - .replace(r"ï", r"\"i") \ - .replace(r"î", r"\^i") \ - .replace(r"œ", r"\oe") \ - .replace(r"æ", r"\ae") \ - .replace(r"Ï", r"\¨I") \ - .replace(r"Î", r"\^I") \ - .replace(r"À", r"\`A") \ - .replace(r"É", r"\'E") \ - .replace(r"È", r"\`E") \ - .replace(r"Ê", r"\^E") \ - .replace(r"ç", r"\c c") \ - .replace(r"Ç", r"\c C") + message = ( + message.replace(r"ù", r"\`u") + .replace(r"é", r"\'e") + .replace(r"è", r"\`e") + .replace(r"ê", r"\^e") + .replace(r"à", r"\`a") + .replace(r"ï", r"\"i") + .replace(r"î", r"\^i") + .replace(r"œ", r"\oe") + .replace(r"æ", r"\ae") + .replace(r"Ï", r"\¨I") + .replace(r"Î", r"\^I") + .replace(r"À", r"\`A") + .replace(r"É", r"\'E") + .replace(r"È", r"\`E") + .replace(r"Ê", r"\^E") + .replace(r"ç", r"\c c") + .replace(r"Ç", r"\c C") + ) return message diff --git a/src/skyblock_guild.py b/src/skyblock_guild.py index a0ee308..def8b75 100644 --- a/src/skyblock_guild.py +++ b/src/skyblock_guild.py @@ -2,7 +2,7 @@ from dotenv import dotenv_values api_hypixel = "https://api.hypixel.net/" -token_hypixel = dotenv_values()['HYPIXEL_KEY'] +token_hypixel = dotenv_values()["HYPIXEL_KEY"] async def fetch(session, url, params=None): @@ -11,7 +11,9 @@ async def fetch(session, url, params=None): async def return_discord_hypixel(session, uuid): - response = await fetch(session, f"{api_hypixel}player", {"key": token_hypixel, "uuid": uuid}) + response = await fetch( + session, f"{api_hypixel}player", {"key": token_hypixel, "uuid": uuid} + ) try: return response["player"]["socialMedia"]["links"]["DISCORD"] except Exception: @@ -21,18 +23,25 @@ async def return_discord_hypixel(session, uuid): async def return_uuid(session, pseudo): - response = await fetch(session, f"https://api.mojang.com/users/profiles/minecraft/{pseudo}") + response = await fetch( + session, f"https://api.mojang.com/users/profiles/minecraft/{pseudo}" + ) try: return response["id"] except Exception: # This Minecraft pseudo doesn't exist - if response["errorMessage"] == f"Couldn't find any profile with name {pseudo}": + if ( + response["errorMessage"] + == f"Couldn't find any profile with name {pseudo}" + ): return 0 return async def return_guild(session, name): - response = await fetch(session, f"{api_hypixel}guild", {"key": token_hypixel, "name": name}) + response = await fetch( + session, f"{api_hypixel}guild", {"key": token_hypixel, "name": name} + ) try: return response["guild"] except Exception: @@ -53,7 +62,9 @@ async def check(pseudo, guild, discord): async with aiohttp.ClientSession() as session: uuid = await return_uuid(session, pseudo) if uuid == 0: - return f"Il n'y a pas de compte Minecraft avec ce pseudo : {pseudo}" + return ( + f"Il n'y a pas de compte Minecraft avec ce pseudo : {pseudo}" + ) elif uuid is None: return "Something wrong happened" diff --git a/tasks.py b/tasks.py index b4b7c04..8a096bc 100644 --- a/tasks.py +++ b/tasks.py @@ -13,11 +13,13 @@ async def tasks_list(client: ChouetteBot): # Loop to send message every 2 hours for pokeroll @tasks.loop(time=[time(t) for t in range(0, 24, 2)]) async def poke_ping(): - guild = client.get_guild(int(client.config['GUILD_ID'])) - dresseurs = guild.get_role(int(client.config['POKE_ROLE'])) - pokeball = client.get_emoji(int(client.config['POKEBALL_EMOJI'])) + guild = client.get_guild(int(client.config["GUILD_ID"])) + dresseurs = guild.get_role(int(client.config["POKE_ROLE"])) + pokeball = client.get_emoji(int(client.config["POKEBALL_EMOJI"])) msg_poke = f"{dresseurs.mention} C'est l'heure d'attraper des pokémons {pokeball}" - await client.get_channel(int(client.config['POKE_CHANNEL'])).send(msg_poke) + await client.get_channel(int(client.config["POKE_CHANNEL"])).send( + msg_poke + ) # Start loop poke_ping.start()