Skip to content

Commit

Permalink
Refactor code for better readability and maintainability
Browse files Browse the repository at this point in the history
  • Loading branch information
rtk-rnjn committed Jun 28, 2024
1 parent 1e99515 commit 2fbc0c7
Show file tree
Hide file tree
Showing 14 changed files with 39 additions and 175 deletions.
8 changes: 4 additions & 4 deletions cogs/automod/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,8 +250,8 @@ async def automod_add(self, ctx: Context, *, rule: str) -> None:
"trigger": view.triggers,
"condition": view.conditions,
"action": view.actions,
}
}
},
},
},
upsert=True,
)
Expand Down Expand Up @@ -283,8 +283,8 @@ async def automod_edit(self, ctx: Context, *, rule: str) -> None:
"trigger": view.triggers,
"condition": view.conditions,
"action": view.actions,
}
}
},
},
},
)
await self.refresh_cache_specific(ctx.guild.id)
Expand Down
26 changes: 13 additions & 13 deletions cogs/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,19 +386,19 @@ async def telephone(self, ctx: Context):
"""To set the telephone phone line, in the server to call and receive the call from other server."""
if not ctx.invoked_subcommand:
data = await self.bot.guild_configurations.find_one({"_id": ctx.guild.id})
if data:
role = str(ctx.guild.get_role(data["pingrole"])) if data.get("pingrole") else None
channel = str(ctx.guild.get_channel(data["channel"])) if data.get("channel") else None
member = (
await self.bot.get_or_fetch_member(ctx.guild, data["memberping"]) if data.get("memberping") else None
)
await ctx.reply(
f"Configuration of this server [telsetup]\n\n"
f"`Channel :` **{channel}**\n"
f"`Pingrole :` **{role} ({data['pingrole'] or None})**\n"
f"`MemberPing:` **{member} ({data['memberping'] or None})**\n"
f"`Blocked :` **{', '.join(data['blocked']) or None}**",
)
if data is None:
return

role = str(ctx.guild.get_role(data["pingrole"])) if data.get("pingrole") else None
channel = str(ctx.guild.get_channel(data["channel"])) if data.get("channel") else None
member = await self.bot.get_or_fetch_member(ctx.guild, data["memberping"]) if data.get("memberping") else None
await ctx.reply(
f"Configuration of this server [telsetup]\n\n"
f"`Channel :` **{channel}**\n"
f"`Pingrole :` **{role} ({data['pingrole'] or None})**\n"
f"`MemberPing:` **{member} ({data['memberping'] or None})**\n"
f"`Blocked :` **{', '.join(data['blocked']) or None}**",
)

@telephone.command(name="channel")
@commands.has_permissions(administrator=True)
Expand Down
2 changes: 1 addition & 1 deletion cogs/defcon/defcon.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ async def defcon_broadcast(self, ctx: Context, channel: discord.TextChannel = No
"$set": {
"default_defcon.broadcast.enabled": True,
"default_defcon.broadcast.channel": channel.id,
}
},
},
upsert=True,
)
Expand Down
7 changes: 1 addition & 6 deletions cogs/mod/mod.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,7 @@

import discord
from cogs.mod import method as mod_method
from cogs.mod.embeds import (
MEMBER_EMBED,
ROLE_EMBED,
TEXT_CHANNEL_EMBED,
VOICE_CHANNEL_EMBED,
)
from cogs.mod.embeds import MEMBER_EMBED, ROLE_EMBED, TEXT_CHANNEL_EMBED, VOICE_CHANNEL_EMBED
from core import Cog, Context, Parrot
from discord.ext import commands
from utilities.checks import in_temp_channel, is_mod
Expand Down
3 changes: 2 additions & 1 deletion cogs/nasa/nasa.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,8 @@ async def apod_loop(self) -> None:

await channel.send(embed=embed)
await self.bot.guild_configurations.update_one(
{"_id": data["_id"]}, {"$set": {"apod_last": discord.utils.utcnow()}}
{"_id": data["_id"]},
{"$set": {"apod_last": discord.utils.utcnow()}},
)

@commands.command()
Expand Down
10 changes: 2 additions & 8 deletions cogs/reminder/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,7 @@ async def _list(self, ctx: Context) -> None:
@remindme.command(name="info", aliases=["details", "detail", "i"])
async def info(self, ctx: Context, *, id: str) -> None:
"""Shows the details of the reminder."""
if not id.isdigit():
message = str_to_snowflake(id)
else:
message = int(id)
message = int(id) if id.isdigit() else str_to_snowflake(id)
data = await self.collection.find_one({"messageAuthor": ctx.author.id, "_id": message})
if not data:
await ctx.reply(f"{ctx.author.mention} reminder of ID: **{id}** not found. ID is case sensitive")
Expand All @@ -172,10 +169,7 @@ async def info(self, ctx: Context, *, id: str) -> None:
@remindme.command(name="del", aliases=["delete", "remove", "rm"])
async def delremind(self, ctx: Context, *, id: str) -> None:
"""To delete the reminder."""
if not id.isdigit():
message = str_to_snowflake(id)
else:
message = int(id)
message = int(id) if id.isdigit() else str_to_snowflake(id)
timer = await self.bot.get_timer(_id=message)
if not timer:
await ctx.reply(f"{ctx.author.mention} reminder of ID: **{id}** not found. ID is case sensitive")
Expand Down
2 changes: 1 addition & 1 deletion cogs/rtfm/rtfm.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from utilities.converters import WrappedMessageConverter

from . import _doc, _ref
from ._kontests import AtCoder, CodeChef, CodeForces, CSAcademy, HackerEarth, HackerRank
from ._kontests import AtCoder, CodeForces, CSAcademy, HackerEarth, HackerRank
from ._used import execute_run, get_raw, prepare_payload
from ._utils import (
ANSI_RE,
Expand Down
2 changes: 1 addition & 1 deletion cogs/suggestion/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ async def __notify_on_suggestion(self, ctx: Context, *, message: discord.Message
_id: int = message.id
content = (
f"{ctx.author.mention} your suggestion being posted.\n"
f"To delete the suggestion type: `{ctx.clean_prefix or await ctx.bot.get_guild_prefixes(ctx.guild.id)}suggest delete {_id}`\n"
f"To delete the suggestion type: `{ctx.clean_prefix or await ctx.bot.get_guild_prefixes(ctx.guild)}suggest delete {_id}`\n"
f"> {jump_url}"
)
try:
Expand Down
107 changes: 8 additions & 99 deletions core/Parrot.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,7 @@
import traceback
import types
from collections import Counter, defaultdict, deque
from collections.abc import (
AsyncGenerator,
Awaitable,
Callable,
Collection,
Iterable,
Mapping,
Sequence,
)
from collections.abc import AsyncGenerator, Awaitable, Callable, Collection, Iterable, Mapping, Sequence
from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast, overload

import aiohttp
Expand Down Expand Up @@ -129,7 +121,7 @@ class Parrot(commands.AutoShardedBot):
help_command: commands.HelpCommand | None

http_session: ClientSession
mongo: AsyncMongoClient
mongo: AsyncMongoClient[dict]
sql: aiosqlite.Connection
redis: aioredis.Redis

Expand Down Expand Up @@ -242,7 +234,7 @@ async def init_db(self) -> None:
# MongoDB Database variables
# Main DB
self.main_db: MongoDatabase = self.mongo["mainDB"]
self.guild_configurations: MongoCollection = self.main_db["guildConfigurations"]
self.guild_configurations: MongoCollection[PostType] = self.main_db["guildConfigurations"]
self.game_collections: MongoCollection = self.main_db["gameCollections"]
self.command_collections: MongoCollection = self.main_db["commandCollections"]
self.timers: MongoCollection = self.main_db["timers"]
Expand Down Expand Up @@ -277,17 +269,6 @@ async def init_db(self) -> None:
def __repr__(self) -> str:
return f"<core.{self.user.name}>"

def __getattribute__(self, __item) -> Any:
try:
return super().__getattribute__(__item)
except AttributeError:
cog = self.get_cog(__item)
if cog is not None:
return cog

msg = f"'{self.__class__.__name__}' object has no attribute {__item!r}"
raise AttributeError(msg)

@property
def config(self) -> Cache[int, PostType]:
return cast(Cache[int, PostType], self.guild_configurations_cache)
Expand Down Expand Up @@ -497,7 +478,7 @@ async def _execute_webhook(
_CONTENT = content
_FILE = kwargs.pop("file", discord.utils.MISSING)

if content and len(content) > 1990 or force_file:
if content is not None and len(content) > 1990 or force_file:
_FILE: discord.File = discord.File(
io.BytesIO(content.encode("utf-8") if isinstance(content, str) else content),
filename=filename or "content.txt",
Expand All @@ -512,7 +493,7 @@ async def _execute_webhook(
content,
)
return await webhook.send(
content=_CONTENT,
_CONTENT,
file=_FILE,
avatar_url=kwargs.pop("avatar_url", self.user.display_avatar.url),
username=kwargs.pop("username", self.user.name),
Expand Down Expand Up @@ -911,10 +892,7 @@ async def get_prefix(self, message: discord.Message) -> list[str]:
prefix = match[1]
return commands.when_mentioned_or(prefix)(self, message)

async def get_guild_prefixes(self, guild: discord.Guild | int) -> str:
if isinstance(guild, int):
guild: discord.Object = discord.Object(id=guild)

async def get_guild_prefixes(self, guild: discord.Guild) -> str:
try:
return self.guild_configurations_cache[guild.id]["prefix"]
except KeyError:
Expand Down Expand Up @@ -1543,9 +1521,9 @@ async def wait_and_delete(
timestamp: float | None = None,
channel_id: int | None = None,
message_id: int | None = None,
message: discord.Message = None,
message: discord.Message | None = None,
) -> None:
if message and delay:
if message is not None and delay:
await message.delete(delay=delay)
return

Expand All @@ -1565,72 +1543,3 @@ async def wait_and_delete(
},
},
)

# CREATE TABLE IF NOT EXISTS logs (
# id INTEGER PRIMARY KEY AUTOINCREMENT,
# level INT NOT NULL,
# message TEXT NOT NULL,
# created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
# extra TEXT,
# UNIQUE(message, created_at)
# );

@overload
def log(
level: int | str,
message: str,
extra: dict[str, Any] | None = None,
) -> None:
...

@overload
def log(
*,
level: int | str,
message: str,
extra: dict[str, Any] | None = None,
) -> None:
...

@overload
def log(
level: int | str,
*,
message: str,
extra: dict[str, Any] | None = None,
) -> None:
...

@staticmethod
def log(
*args: Any,
**kwargs: Any,
) -> None:
mapping = {
"debug": "DEBUG",
"info": "INFO",
"warning": "WARNING",
"error": "ERROR",
"critical": "CRITICAL",
"0": "DEBUG",
"1": "INFO",
"2": "WARNING",
"3": "ERROR",
"4": "CRITICAL",
}
level = kwargs.get("level") or args[0]
message = kwargs.get("message") or args[1]
extra = kwargs.get("extra") or args[2]
level = mapping.get(str(level).lower(), "INFO")
Parrot.recieved_logs.append([level, message or "None", extra])

async def _log(self) -> None:
if self.recieved_logs:
query = """
INSERT INTO logs (level, message, extra) VALUES (?, ?, ?) ON CONFLICT DO NOTHING;
"""
await self.sql.executemany(query, self.recieved_logs)

@tasks.loop(minutes=1)
async def log_loop(self):
await self._log()
10 changes: 2 additions & 8 deletions core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,7 @@
_IndexList,
)
from pymongo.read_concern import ReadConcern
from pymongo.results import (
BulkWriteResult,
DeleteResult,
InsertManyResult,
InsertOneResult,
UpdateResult,
)
from pymongo.results import BulkWriteResult, DeleteResult, InsertManyResult, InsertOneResult, UpdateResult
from pymongo.typings import _CollationIn, _DocumentType, _Pipeline

_WriteOp = Union[ # noqa: UP007
Expand Down Expand Up @@ -179,7 +173,7 @@ async def delete_many(
) -> DeleteResult:
...

async def find_one(self, filter: Any | None = None, *args: Any, **kwargs: Any) -> Any: # noqa: A002
async def find_one(self, filter: Any | None = None, *args: Any, **kwargs: Any) -> _DocumentType: # noqa: A002
...

def find(self, *args: Any, **kwargs: Any) -> AsyncIterator[Cursor[_DocumentType] | dict]:
Expand Down
8 changes: 1 addition & 7 deletions interactions/buttons/__aki.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,7 @@
from enum import Enum
from typing import TYPE_CHECKING, Any, ClassVar, Final

from akinator import (
Answer,
AsyncAkinator as AkinatorGame,
CantGoBackAnyFurther,
Language,
Theme,
)
from akinator import Answer, AsyncAkinator as AkinatorGame, CantGoBackAnyFurther, Language, Theme

import discord
from core import Context, Parrot
Expand Down
9 changes: 1 addition & 8 deletions interactions/buttons/__number_slider.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,7 @@
Board: TypeAlias = list[list[int | None]]


from .utils import (
DEFAULT_COLOR,
BaseView,
DiscordColor,
chunk,
double_wait,
wait_for_delete,
)
from .utils import DEFAULT_COLOR, BaseView, DiscordColor, chunk, double_wait, wait_for_delete


class SlideButton(discord.ui.Button["SlideView"]):
Expand Down
11 changes: 1 addition & 10 deletions interactions/buttons/games.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,7 @@
from .__black_jack import BlackJackView
from .__chess import Chess
from .__chimp import ChimpTest
from .__constants import (
_2048_GAME,
CHOICES,
CROSS_EMOJI,
EMOJI_CHECK,
HAND_RAISED_EMOJI,
SHORT_CHOICES,
WINNER_DICT,
Emojis,
)
from .__constants import _2048_GAME, CHOICES, CROSS_EMOJI, EMOJI_CHECK, HAND_RAISED_EMOJI, SHORT_CHOICES, WINNER_DICT, Emojis
from .__country_guess import BetaCountryGuesser
from .__duckgame import (
ANSWER_REGEX,
Expand Down
9 changes: 1 addition & 8 deletions utilities/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,7 @@
from collections.abc import Callable, Container, Iterable
from typing import TYPE_CHECKING, TypeAlias

from discord.ext.commands import (
BucketType,
Cog,
Command,
CommandOnCooldown,
Cooldown,
CooldownMapping,
)
from discord.ext.commands import BucketType, Cog, Command, CommandOnCooldown, Cooldown, CooldownMapping
from pymongo.collection import Collection

import discord
Expand Down

0 comments on commit 2fbc0c7

Please sign in to comment.