Skip to content

Commit

Permalink
change methods not using its bound instance to staticmethod…" (#24)
Browse files Browse the repository at this point in the history
This reverts commit 2792954.
  • Loading branch information
cringe-neko-girl authored Jan 11, 2025
1 parent 2792954 commit ac148ac
Show file tree
Hide file tree
Showing 15 changed files with 70 additions and 140 deletions.
6 changes: 2 additions & 4 deletions Cogs/ampa.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@ def check(m):
logger.error(f"An error occurred: {e}")
await ctx.send(f"An error occurred: {e}")

@staticmethod
def list_files(search_path: str = ".") -> list:
def list_files(self, search_path: str = ".") -> list:
"""List all file paths in the given directory and its subdirectories, ignoring package and cache files."""
file_paths = []
ignore_patterns = [
Expand Down Expand Up @@ -101,8 +100,7 @@ def list_files(search_path: str = ".") -> list:

return file_paths

@staticmethod
async def send_file_to_user(user: discord.User, file_path: str):
async def send_file_to_user(self, user: discord.User, file_path: str):
"""Send a file to the specified user via DM, handling size limitations."""
try:
filename = os.path.basename(file_path)
Expand Down
6 changes: 2 additions & 4 deletions Cogs/anime.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,8 +299,7 @@ async def update_embed(self):

return embed

@staticmethod
def get_image_url(images):
def get_image_url(self, images):
size_order = ["large", "medium", "small"]
for size in size_order:
image_url = images.get("jpg", {}).get(f"{size}_image_url")
Expand Down Expand Up @@ -484,8 +483,7 @@ async def update_embed(self):

return embed

@staticmethod
def get_image_url(images):
def get_image_url(self, images):
size_order = ["large", "medium", "small"]
for size in size_order:
image_url = images.get("jpg", {}).get(f"{size}_image_url")
Expand Down
9 changes: 3 additions & 6 deletions Cogs/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,8 +378,7 @@ def _draw_text(self, draw, text_x, text_y):
fill=self.base_font_color,
)

@staticmethod
def _download_image(url):
def _download_image(self, url):
"""Download an image from a URL."""
response = requests.get(url)
response.raise_for_status() # Ensure we notice bad responses
Expand Down Expand Up @@ -513,8 +512,7 @@ def _load_resources(self):

self._resize_character()

@staticmethod
def _download_image(url):
def _download_image(self, url):
"""Download an image from a URL and return it as a PIL Image."""
response = requests.get(url)
response.raise_for_status()
Expand Down Expand Up @@ -654,8 +652,7 @@ def _update_command_mapping(self):
mapping[cog_name][cmd.name] = " "
self._save_command_mapping(mapping)

@staticmethod
def format_cog_commands(cog_name, cog_commands, command_mapping):
def format_cog_commands(self, cog_name, cog_commands, command_mapping):
embed = discord.Embed(
title=f"Commands for {cog_name}", color=primary_color_value
)
Expand Down
3 changes: 1 addition & 2 deletions Cogs/information.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ async def about(self, ctx, id: Union[discord.Member, int, str] = None):
embed = await self.get_information_embed(id, self.bot)
await ctx.reply(embed=embed, mention_author=False)

@staticmethod
async def get_information_embed(id, bot):
async def get_information_embed(self, id, bot):
if isinstance(id, discord.Member):
return await Information_Embed.get_member_embed(bot, id)
elif isinstance(id, int):
Expand Down
9 changes: 3 additions & 6 deletions Cogs/memo.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,13 @@ async def play_emoji_game(self, ctx):
except asyncio.TimeoutError:
await message.edit(embed=self.timeout_embed(), view=None)

@staticmethod
def timeout_embed():
def timeout_embed(self):
return discord.Embed(
title="Time's Up...",
description="||```You didn't click the emoji in time.```||",
)

@staticmethod
def timestamp_gen(timestamp: int) -> str:
def timestamp_gen(self, timestamp: int) -> str:
dt = datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc)
formatted_timestamp = f"<t:{int(dt.timestamp())}:R>"
return formatted_timestamp
Expand Down Expand Up @@ -403,8 +401,7 @@ async def handle_error(self, interaction, error, title):
"""Handles errors and sends a custom embed."""
await error_custom_embed(self.bot, interaction, str(error), title=title)

@staticmethod
async def validate_input(**kwargs):
async def validate_input(self, **kwargs):
"""Validates input values to ensure they are not None or empty."""
for key, value in kwargs.items():
if value is None or value == "":
Expand Down
30 changes: 10 additions & 20 deletions Cogs/pokemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,7 @@ def process_image(self, path, filename):
}
self.cache[filename] = metadata

@staticmethod
def evaluate_image_quality(image):
def evaluate_image_quality(self, image):
"""Evaluates image quality based on sharpness."""
sharpness = cv.Laplacian(image, cv.CV_64F).var()
return sharpness
Expand All @@ -124,8 +123,7 @@ def cross_match(self, descriptors, image, k=2):

return best_match, max_accuracy

@staticmethod
def evaluate_accuracy(matches):
def evaluate_accuracy(self, matches):
"""Evaluates accuracy based on good matches."""
good_matches = sum(
1
Expand Down Expand Up @@ -323,17 +321,15 @@ async def download_image(self, session, pokemon_name, semaphore):
f"Image for {pokemon_name} already exists, skipping download."
)

@staticmethod
def remove_srgb_profile(img_path):
def remove_srgb_profile(self, img_path):
try:
with Image.open(img_path) as img:
img.save(img_path, icc_profile=None)
logger.debug(f"Removed sRGB profile from {img_path}")
except Exception as e:
logger.error(f"Error removing sRGB profile: {e}")

@staticmethod
def ensure_correct_color_format(img):
def ensure_correct_color_format(self, img):
"""
Convert image to RGB format.
"""
Expand All @@ -344,8 +340,7 @@ def ensure_correct_color_format(img):
return cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
return img

@staticmethod
def download_file(url, filename):
def download_file(self, url, filename):
response = urlopen(url)
with open(filename, "wb") as f:
f.write(response.read())
Expand Down Expand Up @@ -1722,8 +1717,7 @@ async def show_evolutions(self, interaction: discord.Interaction):
f"Error fetching Pokémon evolution chain: {str(e)}", ephemeral=True
)

@staticmethod
async def get_pokemon_evolution_chain(pokemon_name):
async def get_pokemon_evolution_chain(self, pokemon_name):
async with aiohttp.ClientSession() as session:
species_url = (
f"https://pokeapi.co/api/v2/pokemon-species/{pokemon_name.lower()}/"
Expand Down Expand Up @@ -1790,9 +1784,8 @@ async def display_evolution_chain(self, chain):

return embeds

@staticmethod
async def determine_evolution_method(
current_pokemon, evolution_details, next_pokemon
self, current_pokemon, evolution_details, next_pokemon
):
trigger = evolution_details.get("trigger", {}).get("name")
item = evolution_details.get("item")
Expand Down Expand Up @@ -2019,9 +2012,8 @@ def __init__(
def get_flag(self, lang):
return self.flag_mapping.get(lang)

@staticmethod
def get_pokemon_description(
pokemon_id, file_path="Data/pokemon/pokemon_description.csv"
self, pokemon_id, file_path="Data/pokemon/pokemon_description.csv"
):
try:
with open(file_path, mode="r", encoding="utf-8") as csv_file:
Expand All @@ -2038,9 +2030,8 @@ def get_pokemon_description(
return f"An error occurred: {e}"
return "Pokémon ID not found"

@staticmethod
def get_pokemon_region(
pokemon_id, file_path="Data/pokemon/pokemon_description.csv"
self, pokemon_id, file_path="Data/pokemon/pokemon_description.csv"
):
try:
with open(file_path, mode="r", encoding="utf-8") as csv_file:
Expand Down Expand Up @@ -2314,8 +2305,7 @@ async def get_pokemon_moves(self):
)
return moves_data

@staticmethod
async def fetch_move_details(move_url):
async def fetch_move_details(self, move_url):
response = requests.get(move_url)
if response.status_code == 200:
move_data = response.json()
Expand Down
12 changes: 4 additions & 8 deletions Cogs/quest.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,8 +397,7 @@ async def shop(self, ctx):
except Exception as e:
await ctx.send(f"An error occurred while processing the shop: {e}")

@staticmethod
def read_shop_file(filename):
def read_shop_file(self, filename):
with open(filename, "r", encoding="utf-8") as file:
shop_data = json.load(file)
return shop_data
Expand Down Expand Up @@ -1030,8 +1029,7 @@ def _draw_text(self, draw, text_x, text_y):
fill=self.base_font_color,
)

@staticmethod
def _download_image(url):
def _download_image(self, url):
"""Download an image from a URL."""
try:
response = requests.get(url)
Expand Down Expand Up @@ -1086,8 +1084,7 @@ def __init__(self, bot):
async def handle_error(self, interaction, error, title):
await error_custom_embed(self.bot, interaction, str(error), title=title)

@staticmethod
async def validate_input(**kwargs):
async def validate_input(self, **kwargs):
for key, value in kwargs.items():
if value is None or value == "":
raise ValueError(f"{key} cannot be None or empty")
Expand Down Expand Up @@ -2672,8 +2669,7 @@ async def start(self, ctx):
except Exception as e:
await self.handle_error(ctx, e)

@staticmethod
async def handle_error(interaction, exception):
async def handle_error(self, interaction, exception):
traceback_msg = "".join(
traceback.format_exception(
type(exception), exception, exception.__traceback__
Expand Down
12 changes: 4 additions & 8 deletions Cogs/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ def __init__(self, bot):
self.memory_check.start()
self.image_file = "Data/commands/help/help_embed_images.json"

@staticmethod
async def get_latest_python_version():
async def get_latest_python_version(self):
latest_version = (
subprocess.check_output(
[
Expand Down Expand Up @@ -82,8 +81,7 @@ async def ping(self, ctx):
logger.error(
f"[System cog] Error occurred while sending ping embed: {e}")

@staticmethod
def cog_unload():
def cog_unload(self):
logger.info(f"{Fore.RED}[System cog] Unloaded{Style.RESET_ALL}")

@commands.command(name="uptime")
Expand Down Expand Up @@ -119,8 +117,7 @@ def optimize_memory(self):
self.bot._connection.clear()
print(f"Optimized memory. Garbage collected: {collected} objects.")

@staticmethod
def log_memory_usage():
def log_memory_usage(self):
"""Logs the bot's current memory usage."""
process = psutil.Process(os.getpid())
memory_info = process.memory_info()
Expand All @@ -144,8 +141,7 @@ async def memory_info(self, ctx):
memory_usage = self.get_memory_usage()
await ctx.send(f"Current memory usage: {memory_usage:.2f} MB")

@staticmethod
def get_memory_usage():
def get_memory_usage(self):
"""Returns the current memory usage of the bot."""
process = psutil.Process(os.getpid())
memory_info = process.memory_info()
Expand Down
12 changes: 4 additions & 8 deletions Data/pokemon/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ def __init__(self, db_file='Data/pokemon/pokemon_images.db', processed_file='Dat
print(f"Initializing processed entries database at {self.processed_file}...")
self._init_processed_db()

@staticmethod
def _db_connect(db_name):
def _db_connect(self, db_name):
return sqlite3.connect(db_name)

def _init_db(self):
Expand Down Expand Up @@ -184,18 +183,15 @@ def _process_image(self, image_path):
print(f"Error processing image {image_path}: {e}")
return None

@staticmethod
def serialize_keypoints(keypoints):
def serialize_keypoints(self, keypoints):
"""Convert cv2.KeyPoint objects to a serializable format."""
return [{'pt': kp.pt, 'size': kp.size, 'angle': kp.angle, 'response': kp.response, 'octave': kp.octave, 'class_id': kp.class_id} for kp in keypoints]

@staticmethod
def deserialize_keypoints(serialized_keypoints):
def deserialize_keypoints(self, serialized_keypoints):
"""Convert serialized keypoints back to cv2.KeyPoint objects."""
return [cv2.KeyPoint(kp['pt'][0], kp['pt'][1], kp['size'], kp['angle'], kp['response'], kp['octave'], kp['class_id']) for kp in serialized_keypoints]

@staticmethod
def _clear_console():
def _clear_console(self):
os.system("cls" if os.name == "nt" else "clear")

def _get_cache_items(self):
Expand Down
3 changes: 1 addition & 2 deletions Events/appearance.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,7 @@ async def update_grid_message(self, ctx, grid_index, total_pages):
logger.error(f"An error occurred while updating grid message: {e}")
raise

@staticmethod
async def update_grid_reactions(message, grid_index, total_pages):
async def update_grid_reactions(self, message, grid_index, total_pages):
try:
# Add reactions for image selection if there are any images
if total_pages > 1:
Expand Down
9 changes: 3 additions & 6 deletions Events/code_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,7 @@ async def send_log_embed(self, message):
await const.error_custom_embed(self.bot, None, e, title="Log Embed Error")

# Method to send an embed message
@staticmethod
async def send_embed(channel, title, description):
async def send_embed(self, channel, title, description):
embed = discord.Embed(
title=title,
description=description,
Expand All @@ -164,15 +163,13 @@ async def send_embed(channel, title, description):
await channel.send(embed=embed)

# Method to send a file
@staticmethod
async def send_file(channel, file_path, title, description):
async def send_file(self, channel, file_path, title, description):
with open(file_path, "w") as file:
file.write(description)
await channel.send(file=discord.File(file_path), content=f"**{title}**")

# Method to get updated commands
@staticmethod
async def get_updated_commands():
async def get_updated_commands(self):
root_dir = os.getcwd()
repo = Repo(root_dir)
diff = repo.head.commit.diff(None)
Expand Down
12 changes: 4 additions & 8 deletions Events/poketwo_anti_thief.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,7 @@ def __init__(self, bot, anti_thief=None):
self.shiny_ping_phrase = load_ping_phrase()


@staticmethod
def timestamp_gen(timestamp: int) -> str:
def timestamp_gen(self, timestamp: int) -> str:
dt = datetime.datetime.utcfromtimestamp(timestamp).replace(tzinfo=datetime.timezone.utc)
return f'<t:{int(dt.timestamp())}:R>'

Expand Down Expand Up @@ -280,16 +279,14 @@ async def process_congratulations(self, congrats_message, original_message, refe
logger.error(f"Unexpected error in process_congratulations: {e}")
traceback.print_exc()

@staticmethod
async def allow_all_to_catch(message):
async def allow_all_to_catch(self, message):
embed = message.embeds[0]
embed.description = "✅ Everyone may catch the Pokémon now! No restrictions."
embed.color = 0x00FF00
await message.edit(embed=embed)
logger.info("Everyone is allowed to catch the Pokémon now.")

@staticmethod
async def timeout_user(user, message):
async def timeout_user(self, user, message):
BOT_TOKEN = os.getenv("TOKEN")
GUILD_ID = message.guild.id
USER_ID = user.id
Expand All @@ -315,8 +312,7 @@ async def timeout_user(user, message):
else:
logger.error(f"Failed to timeout user {user.mention}: {response.status_code}")

@staticmethod
async def delete_embed_on_catch(message):
async def delete_embed_on_catch(self, message):
try:
await message.delete()
logger.info("Embed deleted after successful catch.")
Expand Down
Loading

0 comments on commit ac148ac

Please sign in to comment.