From babdf6a0f96ff2c953287628f9bf823a6f653dbe Mon Sep 17 00:00:00 2001 From: ConchDev Date: Thu, 22 Jun 2023 00:28:21 -0400 Subject: [PATCH 1/7] Refactor: Fix code structure in cogs dir --- cogs/developer.py | 14 ++++++------- cogs/fun.py | 12 ++++------- cogs/general.py | 6 +++--- cogs/helper.py | 16 ++++++++------- cogs/listeners.py | 23 +++++++++++++-------- cogs/misc.py | 24 +++++++++++++--------- cogs/moderation.py | 51 +++++++++++++++++++++++++++++----------------- 7 files changed, 83 insertions(+), 63 deletions(-) diff --git a/cogs/developer.py b/cogs/developer.py index 1081c2c..1bc6641 100644 --- a/cogs/developer.py +++ b/cogs/developer.py @@ -1,5 +1,4 @@ from __future__ import annotations -from io import BytesIO import os import traceback @@ -50,7 +49,7 @@ async def _load(self, ctx: commands.Context[CodingBot], cog_: str): title=f"Successfully loaded extension: `{cog_}`", color=discord.Color.green(), ) - except Exception as e: + except Exception: embed = discord.Embed( title=f"Failed to load extension: `{cog_}`", color=discord.Color.red() ) @@ -75,7 +74,7 @@ async def _unload(self, ctx: commands.Context[CodingBot], cog_: str): title=f"Successfully unloaded extension: `{cog_}`", color=discord.Color.green(), ) - except Exception as e: + except Exception: embed = discord.Embed( title=f"Failed to unload extension: `{cog_}`", color=discord.Color.red() ) @@ -99,7 +98,7 @@ async def _reload(self, ctx: commands.Context[CodingBot], cog_: str): title=f"Successfully reloaded extension: `{cog_}`", color=discord.Color.green(), ) - except Exception as e: + except Exception: embed = discord.Embed( title=f"Failed to reload extension: `{cog_}`", color=discord.Color.red() ) @@ -154,7 +153,7 @@ async def _unloadall(self, ctx: commands.Context[CodingBot]): """ cogs: Dict[str, List[str]] = {"unloaded": [], "not": []} - processing: Mapping[str, ModuleType] = self.bot.extensions.copy() # type: ignore + processing: Mapping[str, ModuleType] = self.bot.extensions.copy() for cog in processing: try: await self.bot.unload_extension(cog) @@ -184,7 +183,7 @@ async def _reloadall(self, ctx: commands.Context[CodingBot]): """ cogs: Dict[str, List[str]] = {"reloaded": [], "not": []} - processing: Mapping[str, ModuleType] = self.bot.extensions.copy() # type: ignore + processing: Mapping[str, ModuleType] = self.bot.extensions.copy() for cog in processing: try: await self.bot.reload_extension(cog) @@ -268,7 +267,8 @@ async def _getusermetric( embed = discord.Embed( title=f"{member.name}#{member.discriminator} Detailed anaylysis", description=f"Total thanks this month: {total_thank_count}\n" - f"Revoked thanks this month: {revoked_thank_count} (`{revoked_thank_count/total_thank_count*100 if total_thank_count > 0 else 0:.2f}%`)\n" + f"Revoked thanks this month: {revoked_thank_count} " + f"(`{revoked_thank_count/total_thank_count*100 if total_thank_count > 0 else 0:.2f}%`)\n" f"Actual thanks this month: {surviving_thank_count} (`{surviving_thank_count/total_thank_count*100 if total_thank_count > 0 else 0:.2f}%`)" f'\n{formatted_message if record else ""}', timestamp=discord.utils.utcnow(), diff --git a/cogs/fun.py b/cogs/fun.py index 7606fe6..371bc3b 100644 --- a/cogs/fun.py +++ b/cogs/fun.py @@ -1,18 +1,14 @@ from __future__ import annotations import random -import json from io import BytesIO -from textwrap import wrap from typing import TYPE_CHECKING, Optional import base64 import discord -from discord import utils from discord.ext import commands -from ext.helpers import create_trash_meme, get_rock +from ext.helpers import create_trash_meme from ext.http import Http -from ext.ui.view import * import asyncio @@ -299,7 +295,7 @@ async def reverse(self, ctx: commands.Context[CodingBot], *, text: str): @commands.hybrid_command(name="owofy") async def owofy(self, ctx: commands.Context[CodingBot], *, text: str): embed = discord.Embed( - title=f"Owofied Text", + title="Owofied Text", description=text.replace("o", "OwO"), color=discord.Color.random(), ) @@ -311,7 +307,7 @@ async def owofy(self, ctx: commands.Context[CodingBot], *, text: str): @commands.hybrid_command(name="mock") async def mock(self, ctx: commands.Context[CodingBot], *, text: str): embed = discord.Embed( - title=f"Mocked Text", + title="Mocked Text", description=text.swapcase(), color=discord.Color.random(), ) @@ -334,7 +330,7 @@ async def _beerparty( if len(users) == 0: return await ctx.send("Nobody joined the beerparty :(") await ctx.send( - ", ".join(user.display_name for user in users) + f" joined the beerparty!" + ", ".join(user.display_name for user in users) + " joined the beerparty!" ) # Filters command diff --git a/cogs/general.py b/cogs/general.py index eb30d41..f7c46c1 100644 --- a/cogs/general.py +++ b/cogs/general.py @@ -1,13 +1,12 @@ from __future__ import annotations -import datetime import inspect import os from typing import TYPE_CHECKING, List import discord from discord.ext import commands -from ext.helpers import UrbanDefinition, UrbanDictionary, find_anime_source +from ext.helpers import UrbanDefinition, UrbanDictionary if TYPE_CHECKING: from ext.models import CodingBot @@ -34,7 +33,8 @@ async def _source( ------ `{prefix}source` *will send link to my source code* `{prefix}source [command]` *will send link to the source code of the command* - `{prefix}source [command] [subcommand]` *will send link to the source code of the subcommand* + `{prefix}source [command] [subcommand]`: + *will send link to the source code of the subcommand* """ github = "<:githubwhite:804344724621230091>" embed = discord.Embed(title=f"{github} GitHub (Click Here) {github}") diff --git a/cogs/helper.py b/cogs/helper.py index eb3e591..6f26bfb 100644 --- a/cogs/helper.py +++ b/cogs/helper.py @@ -76,7 +76,7 @@ async def capture_evidence( """ view = ConfirmButton(ctx) view.message = await ctx.author.send( - f"Do you want to provide an evidence for your action?", view=view + "Do you want to provide an evidence for your action?", view=view ) view_touched = not (await view.wait()) evidence_byts = None @@ -97,7 +97,8 @@ async def capture_evidence( except asyncio.TimeoutError: await initial_mess.delete() await ctx.author.send( - "You didn't send any evidence in time. Proceeding with the ban without evidence." + "You didn't send any evidence in time. " + "Proceeding with the ban without evidence." ) else: evidence_byts = await wait_mess.attachments[0].read() @@ -149,7 +150,8 @@ async def log( }, "warn": { "action": "warned", - "undo_action": f"removed warning (`{kwargs.get('warning') or 'removed all warnings'}`)", + "undo_action": "removed warning " + f"(`{kwargs.get('warning') or 'removed all warnings'}`)", "icon": ":warning:", "undo_icon": ":flag_white:", "color": discord.Color.yellow(), @@ -351,7 +353,7 @@ async def help_ban( if read_help_rules_role in member.roles: await member.remove_roles(read_help_rules_role) - if not help_ban_role in member.roles: + if help_ban_role not in member.roles: await member.add_roles(help_ban_role) await self.bot.reply(ctx, f"help-banned {member.mention} with reason: {reason}") @@ -372,17 +374,17 @@ async def help_unban( """ help_ban_role = ctx.guild.get_role(HELP_BAN_ROLE_ID) read_help_rules_role = ctx.guild.get_role(READ_HELP_RULES_ROLE_ID) - if not help_ban_role in member.roles: + if help_ban_role not in member.roles: return await self.bot.reply(ctx, f"{member.mention} is not help-banned") - if not read_help_rules_role in member.roles: + if read_help_rules_role not in member.roles: await member.add_roles(read_help_rules_role) if help_ban_role in member.roles: await member.remove_roles(help_ban_role) await self.bot.reply(ctx, f"help-unbanned {member.mention}") try: - await member.send(f"You have been help-unbanned") + await member.send("You have been help-unbanned") await self.log(action="ban", undo=True, member=member, helper=ctx.author) except discord.Forbidden: pass diff --git a/cogs/listeners.py b/cogs/listeners.py index 9ba0cd5..64deead 100644 --- a/cogs/listeners.py +++ b/cogs/listeners.py @@ -40,7 +40,8 @@ def valid_gh_sect(name: str): async def afk_user_messaage(self, message: discord.Message): """ Responsible for checking if a message was sent by an AFK user. - If so, the bot will send a message to the channel informating that they are no longer AFK. + If so, the bot will send a message to the channel informing the user + that they are no longer AFK. It will also remove the [AFK] tag from the user's name. Parameters @@ -66,13 +67,12 @@ async def afk_user_messaage(self, message: discord.Message): try: if "[AFK]" in message.author.display_name: name = message.author.display_name.split(" ")[1:] - # type: ignore await message.author.edit(nick=" ".join(name)) except (discord.HTTPException, discord.Forbidden): pass staff_role = message.guild.get_role(795145820210462771) - if staff_role and staff_role in message.author.roles: # type: ignore + if staff_role and staff_role in message.author.roles: on_pat_staff = message.guild.get_role(726441123966484600) try: await message.author.add_roles(on_pat_staff) @@ -80,7 +80,8 @@ async def afk_user_messaage(self, message: discord.Message): pass del self.bot.afk_cache[message.guild.id][message.author.id] em = discord.Embed( - description=f"{message.author.mention} Welcome back, I removed your AFK!", + description=f"{message.author.mention} Welcome back, " + "I removed your AFK!", color=discord.Color.dark_gold(), ) msg = await message.reply(embed=em) @@ -91,7 +92,8 @@ async def afk_user_messaage(self, message: discord.Message): async def user_mentioned(self, message: discord.Message): """ Responsible for checking if an AFK user was mentioned in a message. - If so, the bot will send a message to the channel informing that the user that was mentioned is AFK. + If so, the bot will send a message to the channel informing that the user + that was mentioned is AFK. Parameters ---------- @@ -108,7 +110,8 @@ async def user_mentioned(self, message: discord.Message): if record: reason, time_ = record em = discord.Embed( - description=f"{member.mention} is AFK: {reason} ()", + description=f"{member.mention} is AFK: {reason} " + f"()", color=discord.Color.dark_blue(), ) await message.reply(embed=em) @@ -155,7 +158,8 @@ async def on_command_error(self, ctx: commands.Context, error: Exception) -> Non elif isinstance(error, commands.CommandOnCooldown): embed = discord.Embed( title="Command on Cooldown", - description=f"{ctx.author.mention} Please wait {error.retry_after:.2f} seconds before using this command again.", + description=f"{ctx.author.mention} Please wait {error.retry_after:.2f}" + " seconds before using this command again.", color=discord.Color.red(), ) return await ctx.send(embed=embed, ephemeral=True) @@ -195,7 +199,8 @@ async def track_sent_message(self, message: discord.Message): columns=columns, values=values, extras=[ - f"ON CONFLICT (user_id, guild_id) DO UPDATE SET message_count = message_count + 1, {status} = {status} + 1" + "ON CONFLICT (user_id, guild_id) DO UPDATE SET message_count = " + f"message_count + 1, {status} = {status} + 1" ], ) @@ -221,7 +226,7 @@ async def track_deleted_message(self, message: discord.Message): ) @commands.Cog.listener("on_message_edit") - async def invite_in_message(self, _: discord.Message, after: discord.Message): + async def invite_in_message_edit(self, _: discord.Message, after: discord.Message): """ Responsible for tracking member joins. """ diff --git a/cogs/misc.py b/cogs/misc.py index e61c75c..46d4582 100644 --- a/cogs/misc.py +++ b/cogs/misc.py @@ -4,14 +4,12 @@ import random import re -import string -from datetime import datetime, timedelta from typing import TYPE_CHECKING, Optional import button_paginator as pg import discord from discord.ext import commands -from ext.helpers import Spotify, grouper, ordinal_suffix_of, find_anime_source +from ext.helpers import Spotify, grouper, ordinal_suffix_of from ext.http import Http from ext.ui.view import Piston @@ -42,7 +40,8 @@ async def cog_check(self, ctx: commands.Context[CodingBot]) -> bool: ) async def retry(self, ctx: commands.Context[CodingBot]): """ - Reinvoke a command, running it again. This does NOT bypass any permissions checks | Code from v4 + Reinvoke a command, running it again. + This does NOT bypass any permissions checks | Code from v4 """ try: message = await ctx.channel.fetch_message(ctx.message.reference.message_id) @@ -287,7 +286,10 @@ async def thank_show( embed.add_field( name=f"Thank: {thank_id}", - value=f"Thank giver: {giver.mention}\nDate: \nReason: {reason}\nThank given in: {channel.mention}\nMessage link: [Click here!]({msg_link})", + value= + f"Thank giver: {giver.mention}\nDate: \n" + f"Reason: {reason}\nThank given in: {channel.mention}\n" + f"Message link: [Click here!]({msg_link})", inline=False, ) @@ -310,7 +312,8 @@ async def thank_delete(self, ctx: commands.Context[CodingBot], thank_id: str): Usage: ------ - `{prefix}thank delete [thank_id]`: *will delete the thank with the id [thank_id]* + `{prefix}thank delete [thank_id]`: + *will delete the thank with the id [thank_id]* """ record = await self.bot.conn.select_record( @@ -367,10 +370,11 @@ async def thank_leaderboard(self, ctx: commands.Context[CodingBot]): for info in information: user = [ctx.guild.get_member(i.user_id) for i in info] embed = discord.Embed( - title=f"Thank points leaderboard", + title="Thank points leaderboard", description="\n\n".join( [ - f"`{i}{ordinal_suffix_of(i)}` is {user.mention} with `{thanks_count.thanks_count}` Thank point(s)" + f"`{i}{ordinal_suffix_of(i)}` is {user.mention} with " + f"`{thanks_count.thanks_count}` Thank point(s)" for i, (user, thanks_count) in enumerate(zip(user, info), 1) ] ), @@ -421,7 +425,7 @@ async def trainee_list(self, ctx: commands.Context[CodingBot]): f"{i}. {member.mention}" for i, member in enumerate(members, 1) ) embed = discord.Embed( - title=f"Trainees list", description=trainees, color=discord.Color.blue() + title="Trainees list", description=trainees, color=discord.Color.blue() ) await self.bot.reply(ctx, embed=embed) @@ -442,7 +446,7 @@ async def spotify(self, ctx: commands.Context, member: discord.Member = None): if not result: if member == ctx.author: return await ctx.reply( - f"You are currently not listening to spotify!", mention_author=False + "You are currently not listening to spotify!", mention_author=False ) return await self.bot.reply( ctx, diff --git a/cogs/moderation.py b/cogs/moderation.py index 4b8ebb2..a99b4be 100644 --- a/cogs/moderation.py +++ b/cogs/moderation.py @@ -3,7 +3,7 @@ import asyncio import datetime from io import BytesIO -from typing import TYPE_CHECKING, Any, Dict, Optional, Union +from typing import Any, Dict, Optional, Union import discord import humanize @@ -13,9 +13,6 @@ from ext.ui.view import ConfirmButton from ext.consts import TCR_MEMBER_ROLE_ID -if TYPE_CHECKING: - from ext.models import CodingBot - def trainee_check(): def wrapper(ctx: commands.Context[CodingBot]): @@ -64,9 +61,11 @@ def check_member_permission( ctx.author.top_role.position <= member.top_role.position and ctx.author != ctx.guild.owner ): - return f"You can't {ctx.command.name} this member. They have a higher or equal role than you." + return f"You can't {ctx.command.name} this member. They have a higher or "\ + "equal role than you." elif ctx.guild.me.top_role.position <= member.top_role.position and priv_level: - return f"I can't {ctx.command.name} this member. They have a higher or equal role than me." + return f"I can't {ctx.command.name} this member. "\ + "They have a higher or equal role than me." return False @@ -75,7 +74,7 @@ async def capture_evidence( ) -> Optional[discord.Attachment]: view = ConfirmButton(ctx) view.message = await ctx.author.send( - f"Do you want to provide an evidence for your action?", view=view + "Do you want to provide an evidence for your action?", view=view ) view_touched = not (await view.wait()) evidence_byts = None @@ -96,7 +95,8 @@ async def capture_evidence( except asyncio.TimeoutError: await initial_mess.delete() await ctx.author.send( - "You didn't send any evidence in time. Proceeding with the ban without evidence." + "You didn't send any evidence in time. " + "Proceeding with the ban without evidence." ) else: evidence_byts = await wait_mess.attachments[0].read() @@ -238,7 +238,13 @@ async def kick( await member.kick(reason=reason) await self.bot.reply(ctx, f"Kicked {member.mention}") evidence = await self.capture_evidence(ctx) - await self.log(action="kick", moderator=ctx.author, member=member, reason=reason, evidence=evidence) # type: ignore + await self.log( + action="kick", + moderator=ctx.author, + member=member, + reason=reason, + evidence=evidence + ) @commands.hybrid_command(name="ban") @commands.has_permissions(ban_members=True) @@ -270,7 +276,8 @@ async def ban( await ctx.guild.ban(member, reason=reason, delete_message_days=7) await self.bot.reply(ctx, f"Banned {member.mention}") evidence = await self.capture_evidence(ctx) - await self.log(action="ban", moderator=ctx.author, member=member, undo=False, reason=reason, duration=None, evidence=evidence) # type: ignore + await self.log(action="ban", moderator=ctx.author, member=member, + undo=False, reason=reason, duration=None, evidence=evidence) @commands.hybrid_command(name="unban") @commands.has_permissions(ban_members=True) @@ -299,7 +306,8 @@ async def unban( ) else: await self.bot.reply(ctx, f"Unbanned {user.mention}") - await self.log(action="ban", moderator=ctx.author, member=user, undo=True, reason=reason, duration=None) # type: ignore + await self.log(action="ban", moderator=ctx.author, member=user, undo=True, + reason=reason, duration=None) @trainee_check() @commands.hybrid_command(name="mute", aliases=["timeout"]) @@ -335,7 +343,9 @@ async def mute( await member.timeout(until) await self.bot.reply(ctx, f"Muted {member.mention}") evidence = await self.capture_evidence(ctx) - await self.log(action="mute", moderator=ctx.author, member=member, undo=False, reason=reason, duration=duration, evidence=evidence) # type: ignore + await self.log(action="mute", moderator=ctx.author, member=member, + undo=False, reason=reason, duration=duration, + evidence=evidence) @trainee_check() @commands.hybrid_command(name="unmute") @@ -365,8 +375,8 @@ async def unmute( return await self.bot.reply(ctx, f"{member.mention} is not muted.") else: await self.bot.reply(ctx, f"Unmuted {member.mention}") - await self.log(action="mute", moderator=ctx.author, member=member, undo=True, reason=reason) # type: ignore - + await self.log(action="mute", moderator=ctx.author, member=member, + undo=True, reason=reason) @trainee_check() @commands.hybrid_command() async def massban( @@ -404,7 +414,8 @@ async def massban( ) if counter_dict["not_banned"]: embed.color = discord.Color.yellow() - description += f"\n\nFollowing members were not banned:\n{', '.join(f'{user.mention}' for user in counter_dict['not_banned'])}" + description += "\n\nFollowing members were not banned:\n" + f"{', '.join(f'{user.mention}' for user in counter_dict['not_banned'])}" embed.description = description await self.bot.reply(ctx, embed=embed) @@ -446,7 +457,8 @@ async def warn( ) await self.bot.reply(ctx, f"Warned {member.mention}") evidence = await self.capture_evidence(ctx) - await self.log(action="warn", moderator=ctx.author, member=member, reason=reason, evidence=evidence) # type: ignore + await self.log(action="warn", moderator=ctx.author, member=member, + reason=reason, evidence=evidence) @trainee_check() @commands.hybrid_command(name="purge") @@ -461,8 +473,9 @@ async def purge(self, ctx: commands.Context[CodingBot], amount: int = 1): Example: {prefix}purge 10 """ - purged_amt = len(await ctx.channel.purge(limit=amount + 1)) # type: ignore - await self.bot.reply(ctx, f"Purged {purged_amt} messages in {ctx.channel.mention}") # type: ignore + purged_amt = len(await ctx.channel.purge(limit=amount + 1)) + await self.bot.reply(ctx, + f"Purged {purged_amt} messages in {ctx.channel.mention}") @trainee_check() @commands.hybrid_command(name="warnings") @@ -561,7 +574,7 @@ async def clearwarning( f"{target.mention}'s warning was cleared.", allowed_mentions=discord.AllowedMentions(users=False), ) - await self.log(action="warn", moderator=ctx.author, member=target, undo=True) # type: ignore + await self.log(action="warn", moderator=ctx.author, member=target, undo=True) @trainee_check() @commands.hybrid_command(name="verify") From 7a3b65441545a88b006c9a6213fe20ab0c48463c Mon Sep 17 00:00:00 2001 From: ConchDev Date: Thu, 22 Jun 2023 13:19:08 -0400 Subject: [PATCH 2/7] Refactor: Fix up more unreasonable code --- ext/consts.py | 8 +++++--- ext/helpers.py | 24 +++++++++++++----------- ext/http.py | 4 ++-- ext/logger.py | 3 ++- ext/models.py | 20 +++++++++++--------- 5 files changed, 33 insertions(+), 26 deletions(-) diff --git a/ext/consts.py b/ext/consts.py index 13e364b..3ea80f9 100644 --- a/ext/consts.py +++ b/ext/consts.py @@ -33,7 +33,8 @@ def __str__(self) -> str: return f"v{self.major}.{self.submajor}.{self.minor} [{self.release}]" def release_format(self): - return f"Version: `{self.major}.{self.submajor}.{self.minor}`\nPatch: `{self.release}`" + return f"Version: `{self.major}.{self.submajor}.{self.minor}"\ + f"`\nPatch: `{self.release}`" VERSION = Version(major=0, submajor=0, minor=1, release="alpha") @@ -108,9 +109,10 @@ def release_format(self): date BIGINT, reason TEXT DEFAULT "No reason given", is_staff BOOLEAN CHECK(is_staff IN (0, 1)) DEFAULT 0, - thank_revoked BOOLEAN CHECK(thank_revoked IN (0, 1)) DEFAULT 0 + thank_revoked BOOLEAN CHECK(thank_revoked IN (0, 1))\ + DEFAULT 0 ); - """ + """ MESSAGE_METRIC_SCHEMA = """CREATE TABLE IF NOT EXISTS message_metric ( user_id BIGINT, diff --git a/ext/helpers.py b/ext/helpers.py index f7fde71..e03e70a 100644 --- a/ext/helpers.py +++ b/ext/helpers.py @@ -1,7 +1,6 @@ from __future__ import annotations import asyncio -import base64 import datetime as dt import functools import itertools @@ -9,7 +8,6 @@ import string import sys import traceback -import urllib from io import BytesIO from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple @@ -17,7 +15,6 @@ import discord import humanize from bs4 import BeautifulSoup -from colorthief import ColorThief from discord.ext import tasks from PIL import Image, ImageDraw, ImageFilter, ImageFont from cbvx import iml @@ -255,7 +252,7 @@ async def construct_image(self, **kwargs: Any) -> discord.File: else: try: vanity = await member.guild.vanity_invite() - except: + except Exception: pass ago = dt.datetime.now(dt.timezone.utc) - member.created_at img = BytesIO( @@ -534,7 +531,8 @@ def pil_process(pic: BytesIO, name, artists, time, time_at, track) -> discord.Fi buffer.seek(0) # Pass raw bytes to cbvx.iml (needs to be png data) csp = iml.Spotify(buffer.getvalue()) - # Spotify class has 3 config methods - rate (logarithmic rate of interpolation), contrast and shift (pallet shift) + # Spotify class has 3 config methods - rate (logarithmic rate of interpolation), + # contrast, and shift (pallet shift) csp.rate(0.55) # Higner = less sharp interpolation csp.contrast(20.0) # default, Higner = more contrast csp.shift(0) # default @@ -546,7 +544,6 @@ def pil_process(pic: BytesIO, name, artists, time, time_at, track) -> discord.Fi base = Image.frombytes("RGB", (600, 300), result) font0 = ImageFont.truetype("storage/fonts/spotify.ttf", 35) # For title - font = ImageFont.truetype("storage/fonts/spotify.ttf", 28) # Artist font2 = ImageFont.truetype("storage/fonts/spotify.ttf", 18) # Time stamps draw = ImageDraw.Draw( @@ -602,7 +599,8 @@ async def get_from_local(self, bot, act: discord.Spotify) -> discord.File: ).total_seconds() track = time_at / time time = f"{time // 60:02d}:{time % 60:02d}" - time_at = f"{int((time_at if time_at > 0 else 0) // 60):02d}:{int((time_at if time_at > 0 else 0) % 60):02d}" + time_at = f"{int((time_at if time_at > 0 else 0) // 60):02d}:"\ + f"{int((time_at if time_at > 0 else 0) % 60):02d}" pog = act.album_cover_url name = "".join([x for x in act.title if x in s]) name = name[0:21] + "..." if len(name) > 21 else name @@ -700,7 +698,8 @@ async def cache_insert_or_ban(self, member: discord.Member) -> bool: assert channel is not None await channel.send( - f"{member.mention} is highly unlikely to be part of the raid, skipping user.\nReason: Failed the raid mode checks" + f"{member.mention} is highly unlikely to be part of the raid, " + "skipping user.\nReason: Failed the raid mode checks" ) return False @@ -716,9 +715,12 @@ async def notify_staff(self) -> None: title="A possible raid has been detected!", color=discord.Color.gold(), ) - embed.description += f"""\nThe criteria is detected to be `{self.raid_mode_criteria} ± 1` days - Use `{self.bot.command_prefix[0]}raid-mode enable` after making sure this is not a false positive to enable raid mode! - Upon usage of the command, the bot will automatically ban users who have been created within this time. + embed.description += f""" + The criteria is detected to be `{self.raid_mode_criteria} ± 1` days + Use `{self.bot.command_prefix[0]}raid-mode enable` after making sure this \ + is not a false positive to enable raid mode! + Upon usage of the command, the bot will automatically ban users who have \ + been created within this time. """ await channel.send( f"<@&{TCR_STAFF_ROLE_ID}>", diff --git a/ext/http.py b/ext/http.py index ac29c8d..deacd36 100644 --- a/ext/http.py +++ b/ext/http.py @@ -7,12 +7,12 @@ def __init__(self, session: aiohttp.ClientSession): self.session = session self.cache = {"piston": {}} self.api = { - # ////////////////////////////////////////////////////////////////////////////////////// + # ////////////////////////////////////////////////////////////////////////// # prelude "get": { "meme": lambda: self.api["meme-api"]["gimme"](), }, - # ////////////////////////////////////////////////////////////////////////////////////// + # //////////////////////////////////////////////////////////////////////// # "rock": { # "random": lambda: self.get( # "https://rockapi.apiworks.tech/rock/random", _json=True diff --git a/ext/logger.py b/ext/logger.py index 88281ae..1f7fc00 100644 --- a/ext/logger.py +++ b/ext/logger.py @@ -11,7 +11,8 @@ class CustomFormatter(logging.Formatter): light_blue = "\x1b[1;36m" purple = "\x1b[5;35m" reset = "\x1b[0m" - local_format = "{}%(asctime)s{reset} {}%(levelname)s{reset} {}%(name)s{reset} dependent%(message)s{reset}".format( + local_format = "{}%(asctime)s{reset} {}%(levelname)s{reset} {}%(name)s{reset} "\ + " dependent%(message)s{reset}".format( grey, blue, purple, reset=reset ) diff --git a/ext/models.py b/ext/models.py index 61ff180..19d8788 100644 --- a/ext/models.py +++ b/ext/models.py @@ -11,7 +11,6 @@ Iterable, List, Mapping, - NamedTuple, Optional, Set, Tuple, @@ -128,7 +127,7 @@ def __getattr__(self, __name: str) -> Any: return super().__getattribute__(__name) async def __aenter__(self) -> "Database": - self.bot.logger.info(f"Making connections to databases") + self.bot.logger.info("Making connections to databases") self.conn["config"] = await aiosqlite.connect("./database/config.db") self.conn["warnings"] = await aiosqlite.connect("./database/warnings.db") self.conn["afk"] = await aiosqlite.connect("./database/afk.db") @@ -139,7 +138,7 @@ async def __aenter__(self) -> "Database": return self async def fill_cache(self): - self.bot.logger.info(f"Filling stored cache data before startup") + self.bot.logger.info("Filling stored cache data before startup") record = await self.select_record( "afk", table="afk", arguments=["user_id", "reason", "afk_time"] ) @@ -291,11 +290,11 @@ async def send_bot_help( self, mapping: Mapping[Optional[commands.Cog], List[commands.Command]] ) -> None: embed = discord.Embed(title="Bot Commands", description="Coding Bot V6") - for cog, commands in mapping.items(): + for cog, cmds in mapping.items(): if cog and not cog.hidden: embed.add_field( name=cog.qualified_name, - value=" ".join(f"`{command.name}`" for command in commands), + value=" ".join(f"`{command.name}`" for command in cmds), ) destination = self.get_destination() await destination.send(embed=embed) @@ -307,7 +306,8 @@ async def send_group_help(self, group: commands.Group[Any, ..., Any], /) -> None for command in group.commands: if not command.hidden: - embed.description += f"\n`{command.qualified_name} - {command.brief or 'Not documented yet'}`" + embed.description += f"\n`{command.qualified_name} - "\ + f"{command.brief or 'Not documented yet'}`" destination = self.get_destination() await destination.send(embed=embed) @@ -336,7 +336,8 @@ async def send_cog_help(self, cog: commands.Cog[Any, ..., Any], /) -> None: for command in cog.get_commands(): if not command.hidden: - embed.description += f"\n`{command.qualified_name} {command.brief or 'Not documented yet'}`" + embed.description += f"\n`{command.qualified_name} "\ + f"{command.brief or 'Not documented yet'}`" destination = self.get_destination() await destination.send(embed=embed) @@ -401,7 +402,7 @@ async def start(self, token: str, *, reconnect: bool = True) -> None: async def on_ready(self) -> None: await self.wait_until_ready() await self.tracker.cache_invites() - self.logger.info(f"Coding Bot V6 is ready for action!") + self.logger.info("Coding Bot V6 is ready for action!") async def on_invite_create(self, invite: discord.Invite) -> None: await self.tracker.update_invite_cache(invite) @@ -450,7 +451,8 @@ async def on_member_join(self, member: discord.Member) -> None: # type: ignore # Always a Messageable await channel.send(content=member.mention, file=file) await verify_here.send( # type: ignore # Always a Messageable - f"Welcome {member.mention}! Follow the instructions in other channels to get verified. :)", + f"Welcome {member.mention}! Follow the instructions " + "in other channels to get verified. :)", embed=embed, ) From a9c0227673d3f104dedc4aa4c8406fd19fad6287 Mon Sep 17 00:00:00 2001 From: ConchDev Date: Thu, 22 Jun 2023 13:39:34 -0400 Subject: [PATCH 3/7] Refactor: follow PEP8 and improve readability --- cogs/developer.py | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/cogs/developer.py b/cogs/developer.py index 1bc6641..8db47e7 100644 --- a/cogs/developer.py +++ b/cogs/developer.py @@ -253,23 +253,43 @@ async def _getusermetric( ) record = message_metric[0] if message_metric else None if record: + deleted_message_percent = (record.deleted_message_count / + record.message_count * 100) + actual_message_percent = ((record.message_count - + record.deleted_message_count) / + record.message_count * 100) + offline_message_percent = record.offline / record.message_count * 100 + online_message_percent = record.online / record.message_count * 100 + dnd_message_percent = record.dnd / record.message_count * 100 + idle_message_percent = record.idle / record.message_count * 100 formatted_message = f""" **__Message metrics__** For {member.mention}: - \u3164 • **__Total message count__**: {record.message_count} - \u3164 • **__Deleted message count__**: {record.deleted_message_count} (`{record.deleted_message_count / record.message_count * 100:.2f}%`) - \u3164 • **__Actual message count__**: {record.message_count - record.deleted_message_count} (`{(record.message_count - record.deleted_message_count) / record.message_count * 100:.2f}%`) - \u3164 • **__Offline message count__**: {record.offline} (`{record.offline / record.message_count * 100:.2f}%`) - \u3164 • **__Online message count__**: {record.online} (`{record.online / record.message_count * 100:.2f}%`) - \u3164 • **__Dnd message count__**: {record.dnd} (`{record.dnd / record.message_count * 100:.2f}%`) - \u3164 • **__Idle message count__**: {record.idle} (`{record.idle / record.message_count * 100:.2f}%`) + \u3164 • **__Total message count__**: {record.message_count} + \u3164 • **__Deleted message count__**: \ + {record.deleted_message_count} (`{deleted_message_percent}%`) + \u3164 • **__Actual message count__**: \ + {record.message_count - record.deleted_message_count} \ + (`{actual_message_percent}%`) + \u3164 • **__Offline message count__**: \ + {record.offline} (`{offline_message_percent}%`) + \u3164 • **__Online message count__**: \ + {record.online} (`{online_message_percent}%`) + \u3164 • **__Dnd message count__**: {record.dnd} (`{dnd_message_percent}%`) + \u3164 • **__Idle message count__**: \ + {record.idle} (`{idle_message_percent}%`) """ + revoked_thanks_percent = (revoked_thank_count/total_thank_count*100 + if total_thank_count > 0 else 0) + actual_thanks_percent = (surviving_thank_count/total_thank_count*100 + if total_thank_count > 0 else 0) embed = discord.Embed( title=f"{member.name}#{member.discriminator} Detailed anaylysis", description=f"Total thanks this month: {total_thank_count}\n" f"Revoked thanks this month: {revoked_thank_count} " - f"(`{revoked_thank_count/total_thank_count*100 if total_thank_count > 0 else 0:.2f}%`)\n" - f"Actual thanks this month: {surviving_thank_count} (`{surviving_thank_count/total_thank_count*100 if total_thank_count > 0 else 0:.2f}%`)" + f"(`{revoked_thanks_percent}%`)\n" + f"Actual thanks this month: \ + {surviving_thank_count} (`{actual_thanks_percent}%`)" f'\n{formatted_message if record else ""}', timestamp=discord.utils.utcnow(), ) From 67303b41d367a248dd1d9e1a946011bea491e2ea Mon Sep 17 00:00:00 2001 From: ConchDev Date: Thu, 22 Jun 2023 13:45:00 -0400 Subject: [PATCH 4/7] Refactor: remove commented commands --- cogs/fun.py | 142 ++-------------------------------------------------- 1 file changed, 3 insertions(+), 139 deletions(-) diff --git a/cogs/fun.py b/cogs/fun.py index 371bc3b..0587403 100644 --- a/cogs/fun.py +++ b/cogs/fun.py @@ -40,24 +40,6 @@ async def trash(self, ctx: commands.Context[CodingBot], *, user: discord.Member) file = await create_trash_meme(avatar_one, avatar_two) await self.bot.send(ctx, file=file) - # @commands.hybrid_command() - # async def rock( - # self, ctx: commands.Context[CodingBot], *, query: Optional[str] = None - # ): - # """ - # Get a random rock - # Usage: - # ------ - # `{prefix}rock`: *will get a random rock* - # `{prefix}rock [rock]`: *will get the [rock]* - - # """ - # rock_info = await get_rock(self) - # return await self.bot.reply( - # ctx, - # embed=rock_info, - # ) - @commands.hybrid_command() async def number( self, ctx: commands.Context[CodingBot], number: Optional[int] = None @@ -186,28 +168,6 @@ async def token(self, ctx: commands.Context[CodingBot]): ) await self.bot.reply(ctx, embed=embed) - # @commands.hybrid_command(name="animal") - # async def animal(self, ctx: commands.Context[CodingBot], animal: Optional[str] = None): - # options = ("dog", "cat", "panda", "fox", "red_panda", "koala", "bird", "raccoon", "kangaroo") - # if (not animal) or (animal and animal not in options): - # animal = random.choice(options) - - # response = await self.http.api["some-random-api"]["animal"](animal) - # if response.status in range(200,300): - # json = await response.json() - - # image = json["image"] - # fact = json["fact"] - - # embed = discord.Embed(title="Here's the animal image you asked.", color=discord.Color.random()) - # embed.set_image(url=image) - # embed.set_footer(text=fact) - # else: - # embed = discord.Embed(title="ERROR!", description=f"Received a bad status code of {response.status}") - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - - # await self.bot.reply(ctx,embed=embed) - @commands.hybrid_group(invoke_without_command=True) async def binary(self, ctx: commands.Context[CodingBot]): embed = discord.Embed( @@ -254,32 +214,6 @@ async def binary_decode(self, ctx: commands.Context[CodingBot], *, binary: str): await self.bot.reply(ctx, embed=embed) - # @commands.hybrid_command(name="lyrics") - # async def lyrics(self, ctx: commands.Context[CodingBot], *, query: str = None): - # if not query: - # embed = discord.Embed(title = "Hey! I'm confused", description=f"You must provide a search argument or I couldn't find the lyrics") - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - - # response = await self.http.api["some-random-api"]["lyrics"](query) - # if response.status in range(200, 300): - # json = await response.json() - - # lyrics = json['lyrics'] - # artist = json['author'] - # title = json['title'] - # thumbnail = json['thumbnail']['genius'] - - # for chunk in wrap(lyrics, 4096, replace_whitespace = False): - # embed = discord.Embed(title = f"{artist} - {title}", description = chunk, color=discord.Color.random()) - # embed.set_thumbnail(url=thumbnail) - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - - # else: - # embed = discord.Embed(title="ERROR!", description=f"Received a bad status code of {response.status}") - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - - # await self.bot.reply(ctx,embed=embed) - @commands.hybrid_command(name="reverse") async def reverse(self, ctx: commands.Context[CodingBot], *, text: str): embed = discord.Embed( @@ -321,7 +255,9 @@ async def _beerparty( self, ctx: commands.Context, *, reason: commands.clean_content = None ): reason = ("\nReason: " + reason) if reason else "" - msg = await ctx.send("Open invite to beerparty! React with 🍻 to join!" + reason) + msg = await ctx.send( + "Open invite to beerparty! React with 🍻 to join!" + reason + ) await msg.add_reaction("\U0001f37b") await asyncio.sleep(60) msg = await ctx.channel.fetch_message(msg.id) @@ -333,77 +269,5 @@ async def _beerparty( ", ".join(user.display_name for user in users) + " joined the beerparty!" ) - # Filters command - # @commands.hybrid_group(invoke_without_command=True) - # async def filter(self, ctx: commands.Context[CodingBot]): - # embed = discord.Embed(title="Filter command", description="Available methods: `invert`, `greyscale`, `colour [hex]`", color=discord.Color.random()) - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - # await self.bot.reply(ctx,embed=embed) - - # @filter.command(name="invert") - # async def filter_invert(self, ctx: commands.Context[CodingBot], member: discord.Member = None): - # if not member: - # member = ctx.author - # pfp = member.display_avatar.url - # response = await self.http.api["some-random-api"]["filters"]["invert"](pfp) - - # embed = discord.Embed(title="Filter command - Invert", color=discord.Color.random()) - # embed.set_image(url=response) - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - # await self.bot.reply(ctx,embed=embed) - - # @filter.command(name="greyscale") - # async def filter_greyscale(self, ctx: commands.Context[CodingBot], member: discord.Member = None): - # if not member: - # member = ctx.author - # pfp = member.display_avatar.url - # response = await self.http.api["some-random-api"]["filters"]["greyscale"](pfp) - - # embed = discord.Embed(title="Filter command - Greyscale", color=discord.Color.random()) - # embed.set_image(url=response) - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - # await self.bot.reply(ctx,embed=embed) - - # @filter.command(name="colour") - # async def filter_colour(self, ctx: commands.Context[CodingBot], member: discord.Member = None, hex_code: str = None): - # if not member: - # member = ctx.author - # if not hex_code: - # embed = discord.Embed(title="ERROR!", description="No Hex? Hex colour code is required") - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - # hex_code = hex_code.replace('#', '') - # pfp = member.display_avatar.url - # response = await self.http.api["some-random-api"]["filters"]["greyscale"](pfp, hex_code) - - # embed = discord.Embed(title="Filter command - Colour", color=discord.Color.random()) - # embed.set_image(url=response) - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - # await self.bot.reply(ctx,embed=embed) - - # @filter.command(name="brightness") - # async def filter_brightness(self, ctx: commands.Context[CodingBot], member: discord.Member = None): - # if not member: - # member = ctx.author - # pfp = member.display_avatar.url - # response = await self.http.api["some-random-api"]["filters"]["brightness"](pfp) - - # embed = discord.Embed(title="Filter command - Brightness", color=discord.Color.random()) - # embed.set_image(url=response) - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - # await self.bot.reply(ctx,embed=embed) - - # @filter.command(name="threshold") - # async def filter_threshold(self, ctx: commands.Context[CodingBot], member: discord.Member = None): - # if not member: - # member = ctx.author - # pfp = member.display_avatar.url - # response = await self.http.api["some-random-api"]["filters"]["threshold"](pfp) - - # embed = discord.Embed(title="Filter command - Threshold", color=discord.Color.random()) - # embed.set_image(url=response) - # embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar.url) - # await self.bot.reply(ctx,embed=embed) - - async def setup(bot: CodingBot): await bot.add_cog(Fun(bot)) From 5796cf70d03bf4201c71f134ed764ecf1659f851 Mon Sep 17 00:00:00 2001 From: ConchDev Date: Thu, 22 Jun 2023 13:45:37 -0400 Subject: [PATCH 5/7] Refactor: Fix comment to adhere to PEP8 --- cogs/listeners.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cogs/listeners.py b/cogs/listeners.py index 64deead..bf7180d 100644 --- a/cogs/listeners.py +++ b/cogs/listeners.py @@ -259,7 +259,8 @@ async def invite_in_message(self, message: discord.Message): ) if re.search( invite_regex, message.content - ): # `check_invite` already checks if there is an invite, why are we checking again? + ): # `check_invite` already checks if there is an invite, + # why are we checking again? await message.delete() return await message.channel.send( "Please don't send invite links in this server!" From bfd7684b14395940ce6268b1fabda6ccf40962e0 Mon Sep 17 00:00:00 2001 From: ConchDev Date: Thu, 22 Jun 2023 13:47:03 -0400 Subject: [PATCH 6/7] Refactor: Fix PEP8 in view.py --- ext/ui/view.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/ext/ui/view.py b/ext/ui/view.py index c5b2cc6..066bcf8 100644 --- a/ext/ui/view.py +++ b/ext/ui/view.py @@ -82,10 +82,16 @@ async def get_code_out(self): if child.custom_id == "info": if self.ran: child.style = discord.ButtonStyle.green - child.label = f"ran '{self.lang}' code | {int(time.time()) - self.timestamp}s" + child.label = ( + f"ran '{self.lang}' code | " + f"{int(time.time()) - self.timestamp}s" + ) else: child.style = discord.ButtonStyle.red - child.label = f"failed to run '{self.lang}' code | {int(time.time()) - self.timestamp}s" + child.label = ( + f"failed to run '{self.lang}' code | " + f"{int(time.time()) - self.timestamp}s" + ) await self.msg.edit( embed=self.cog.bot.embed( title=" ", description=f"```{self.lang}\n{output[0]}\n```" From c2cea1e8204ce8d846a60275ec75987db2a74bd0 Mon Sep 17 00:00:00 2001 From: ConchDev Date: Thu, 22 Jun 2023 13:56:22 -0400 Subject: [PATCH 7/7] Refactor: Remove another commented command --- cogs/misc.py | 80 ++-------------------------------------------------- 1 file changed, 2 insertions(+), 78 deletions(-) diff --git a/cogs/misc.py b/cogs/misc.py index 46d4582..4ec4323 100644 --- a/cogs/misc.py +++ b/cogs/misc.py @@ -81,7 +81,7 @@ async def afk( if staff_role in member.roles: try: - await member.remove_roles(on_pat_staff) # type: ignore + await member.remove_roles(on_pat_staff) except (discord.Forbidden, discord.HTTPException): pass if ctx.guild.id not in self.bot.afk_cache: @@ -95,7 +95,7 @@ async def afk( ) try: await member.edit(nick=f"[AFK] {member.display_name}") - except: + except Exception: pass try: self.bot.afk_cache[ctx.guild.id][member.id] = ( @@ -457,82 +457,6 @@ async def spotify(self, ctx: commands.Context, member: discord.Member = None): file, view = result await self.bot.send(ctx, file=file, view=view) - # @commands.command(name='sauce') - # async def sauce(self, ctx: commands.Context[CodingBot], source: Optional[str] = None): - # """ - # Get the sauce of a source. - # Example: {prefix}sauce - # """ - # source = source or ctx.message.attachments[0].url if ctx.message.attachments else None - # if not source: - # return await ctx.send( - # 'Please provide image/video url, ' - # 'reply to another message or upload the image/video along with the command. ' - # f'Please use {ctx.prefix}help saucefor more information.') - - # anime_information = await find_anime_source(self.bot.session, source) - - # result = anime_information['result'] - # if not result: - # return await ctx.send( - # 'Could not find any anime source for this image/video.' - # ) - # else: - # result = result[0] - - # print(ctx.channel.is_nsfw()) - # print(result['anilist'].get('isAdult')) - - # if result['anilist'].get('isAdult') and not ctx.channel.is_nsfw(): - # await ctx.send( - # 'This source is marked as adult content and can only be used in NSFW channels. I Will try to DM you instead.' - # ) - # ctx = ctx.author - - # browser = "https://trace.moe/?url={}".format(source) - - # anilist_id = result['anilist']['id'] - # mal_id = result['anilist']['idMal'] - - # anilist_url = f'https://anilist.co/anime/{anilist_id}' - # anilist_banner = f"https://img.anili.st/media/{anilist_id}" - # mal_url = f'https://myanimelist.net/anime/{mal_id}' - - # native = result['anilist']['title'].get('native') - # english = result['anilist']['title'].get('english') - # romaji = result['anilist']['title'].get('romaji') - - # filename = result['filename'] - # similarity = round(result['similarity'] * 100, 2) - - # from_timestamp = timedelta(seconds=int(result['from'])) - # to_timestamp = timedelta(seconds=int(result['to'])) - - # embed = discord.Embed(timestamp=discord.utils.utcnow()) - # embed.add_field( - # name="Anime Title", DD - # value=f"Native: {native}\nEnglish: {english}\nRomaji: {romaji}", - # inline=False - # ) - # embed.add_field( - # name="Scene Details", - # value=f"**Filename:** {filename}\n**From:** {from_timestamp}\n**To:** {to_timestamp}\n**Similarity:** {similarity}%", - # inline=False - # ) - # embed.add_field( - # name="Links", - # value="[Open In Browser]({}) | [AniList]({}) | [MyAnimeList]({})".format( - # browser, anilist_url, mal_url - # ), - # inline=False - - # ) - # embed.set_image(url=anilist_banner) - # try: - # await ctx.send(embed=embed) - # except (discord.HTTPException, discord.Forbidden): - # pass - async def setup(bot: CodingBot): await bot.add_cog(Miscellaneous(bot))