Skip to content

Commit

Permalink
Optimize pre-commit workflow (#215)
Browse files Browse the repository at this point in the history
  • Loading branch information
No767 authored Oct 21, 2024
1 parent 79c3901 commit 11345f3
Show file tree
Hide file tree
Showing 20 changed files with 1,139 additions and 870 deletions.
7 changes: 0 additions & 7 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,6 @@ updates:
prefix: "[pip]"
include: "scope"
target-branch: "main"
ignore:
# I've chose to ignroe pyright from Dependabot
# As most of the time, it's pulled from upstream, which is Microsoft
# Most of the time there isn't much changes that need to be addressed
# Poetry should always install the latest version instead
- dependency-name: "pyright"
update-types: ["version-update:semver-patch"]
groups:
dev-deps:
dependency-type: "development"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:

# We want to filter out dependabot and pre-commit
# automated pushes to main
if: ${{ github.actor != 'dependabot[bot]' && 'pre-commit-ci[bot]'}}
if: ${{ github.actor != 'dependabot[bot]'}}
steps:
- name: Checkout
uses: actions/checkout@v4
Expand Down
47 changes: 0 additions & 47 deletions .pre-commit-config.yaml

This file was deleted.

13 changes: 10 additions & 3 deletions bot/cogs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,9 @@ async def setup(self, ctx: GuildContext, *, flags: SetupFlags) -> None:
name="rodhaj", overwrites=rodhaj_overwrites, position=0
)
logging_channel = await rodhaj_category.create_text_channel(
name=flags.log_name or "rodhaj-logs", reason=lgc_reason, position=0
name=flags.log_name or "rodhaj-logs",
reason=lgc_reason,
position=0,
)
lgc_webhook = await logging_channel.create_webhook(
name="Rodhaj Ticket Logs", avatar=avatar_bytes
Expand Down Expand Up @@ -829,7 +831,8 @@ async def config_set_age(
type: Literal["guild", "account"],
*,
duration: Annotated[
FriendlyTimeResult, UserFriendlyTime(commands.clean_content, default="…")
FriendlyTimeResult,
UserFriendlyTime(commands.clean_content, default="…"),
],
) -> None:
"""Sets an minimum duration for age-related options
Expand Down Expand Up @@ -890,7 +893,11 @@ async def config_set(
value="Boolean option to set the configuration",
)
async def config_toggle(
self, ctx: GuildContext, key: Annotated[str, ConfigKeyConverter], *, value: bool
self,
ctx: GuildContext,
key: Annotated[str, ConfigKeyConverter],
*,
value: bool,
) -> None:
"""Toggles an boolean option for configuration
Expand Down
13 changes: 10 additions & 3 deletions bot/cogs/ext/prometheus.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from discord.ext import commands, tasks

try:

from prometheus_async.aio.web import start_http_server
from prometheus_client import Counter, Enum, Gauge, Info, Summary
except ImportError:
Expand Down Expand Up @@ -37,7 +36,8 @@ def __init__(self, bot: Rodhaj):
f"{METRIC_PREFIX}active_tickets", "Amount of active tickets"
)
self.closed_tickets = Counter(
f"{METRIC_PREFIX}closed_tickets", "Number of closed tickets in this session"
f"{METRIC_PREFIX}closed_tickets",
"Number of closed tickets in this session",
)
self.locked_tickets = Gauge(
f"{METRIC_PREFIX}locked_tickets",
Expand All @@ -50,7 +50,14 @@ def __init__(self, bot: Rodhaj):

# Maybe load all of these from an json file next time
class Metrics:
__slots__ = ("bot", "connected", "latency", "commands", "version", "features")
__slots__ = (
"bot",
"connected",
"latency",
"commands",
"version",
"features",
)

def __init__(self, bot: Rodhaj):
self.bot = bot
Expand Down
25 changes: 19 additions & 6 deletions bot/cogs/tickets.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,9 @@ async def create_ticket(self, ticket: TicketThread) -> Optional[TicketOutput]:
reason=f"Failed to create ticket (User ID: {ticket.user.id})",
)
return TicketOutput(
status=False, ticket=created_ticket, msg="Could not create ticket"
status=False,
ticket=created_ticket,
msg="Could not create ticket",
)
else:
self.bot.metrics.features.active_tickets.inc()
Expand Down Expand Up @@ -317,7 +319,8 @@ async def tick_post(self, ctx: RoboContext) -> None:
await ctx.message.add_reaction(discord.PartialEmoji(name="\U00002705"))

def get_solved_tag(
self, channel: Optional[Union[discord.ForumChannel, discord.TextChannel]]
self,
channel: Optional[Union[discord.ForumChannel, discord.TextChannel]],
):
if not isinstance(channel, discord.ForumChannel):
return None
Expand All @@ -330,7 +333,8 @@ def get_solved_tag(
return solved_tag

def get_locked_tag(
self, channel: Optional[Union[discord.ForumChannel, discord.TextChannel]]
self,
channel: Optional[Union[discord.ForumChannel, discord.TextChannel]],
):
if not isinstance(channel, discord.ForumChannel):
return None
Expand Down Expand Up @@ -396,7 +400,10 @@ async def close(self, ctx: RoboContext) -> None:
@commands.cooldown(10, 12, commands.BucketType.member)
@commands.command(name="reply", aliases=["r"])
async def reply(
self, ctx: GuildContext, *, message: Annotated[str, commands.clean_content]
self,
ctx: GuildContext,
*,
message: Annotated[str, commands.clean_content],
) -> None:
"""Replies back to the owner of the active ticket with a message"""
ticket_owner = await self.get_ticket_owner_id(ctx.channel.id)
Expand Down Expand Up @@ -475,9 +482,15 @@ async def ticket_info(self, ctx: RoboContext) -> None:
)
embed.add_field(name="Ticket Owner", value=ticket_owner.mention, inline=False)
embed.add_field(
name="Associated Guild", value=ticket.source_guild.name, inline=False
name="Associated Guild",
value=ticket.source_guild.name,
inline=False,
)
embed.add_field(name="Created At", value=format_dt(ticket.thread.created_at), inline=False) # type: ignore
embed.add_field(
name="Created At",
value=format_dt(ticket.thread.created_at),
inline=False,
) # type: ignore
await ctx.send(embed=embed)

# As the guild has an entry in the cache,
Expand Down
11 changes: 8 additions & 3 deletions bot/cogs/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ async def about(self, ctx: RoboContext) -> None:
f"Made with discord.py v{discord.__version__} | Running Python {platform.python_version()}"
)
embed = Embed()
embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.display_avatar.url) # type: ignore
embed.set_author(
name=self.bot.user.name, icon_url=self.bot.user.display_avatar.url
) # type: ignore
embed.title = "Rodhaj"
embed.description = (
"Rodhaj is a modern, improved ModMail bot designed exclusively for "
Expand All @@ -114,7 +116,8 @@ async def about(self, ctx: RoboContext) -> None:
name="User", value=f"{total_members} total\n{total_unique} unique"
)
embed.add_field(
name="Process", value=f"{memory_usage:.2f} MiB\n{cpu_usage:.2f}% CPU"
name="Process",
value=f"{memory_usage:.2f} MiB\n{cpu_usage:.2f}% CPU",
)
embed.add_field(
name="Active Tickets", value=await self.fetch_num_active_tickets()
Expand All @@ -133,7 +136,9 @@ async def ping(self, ctx: RoboContext) -> None:

embed = Embed()
embed.add_field(
name="DB Latency", value=f"```{db_ping * 1000:.2f}ms```", inline=False
name="DB Latency",
value=f"```{db_ping * 1000:.2f}ms```",
inline=False,
)
embed.add_field(
name="Websocket Latency",
Expand Down
6 changes: 5 additions & 1 deletion bot/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@

async def main() -> None:
async with ClientSession() as session, asyncpg.create_pool(
dsn=POSTGRES_URI, min_size=25, max_size=25, init=init, command_timeout=30
dsn=POSTGRES_URI,
min_size=25,
max_size=25,
init=init,
command_timeout=30,
) as pool:
async with Rodhaj(
config=config, intents=intents, session=session, pool=pool
Expand Down
10 changes: 5 additions & 5 deletions bot/libs/tickets/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,8 @@ async def confirm(
status = self.cog.in_progress_tickets.get(interaction.user.id)
if tags is None or status is None:
await interaction.response.send_message(
"Unable to obtain reserved tags and in progress tags", ephemeral=True
"Unable to obtain reserved tags and in progress tags",
ephemeral=True,
)
return

Expand All @@ -254,12 +255,11 @@ async def confirm(

if (self.guild.created_at - interaction.created_at) < guild_settings.guild_age:
await interaction.response.send_message(
"The guild is too young in order to utilize Rodhaj.", ephemeral=True
"The guild is too young in order to utilize Rodhaj.",
ephemeral=True,
)
return
elif (
potential_member
): # Since we are checking join times, if we don't have the proper member, we can only skip it.
elif potential_member: # Since we are checking join times, if we don't have the proper member, we can only skip it.
joined_at = potential_member.joined_at or discord.utils.utcnow()
if (joined_at - interaction.created_at) < guild_settings.account_age:
await interaction.response.send_message(
Expand Down
5 changes: 4 additions & 1 deletion bot/libs/utils/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,10 @@ def is_manager():

def is_mod():
return check_permissions(
ban_members=True, manage_messages=True, kick_members=True, moderate_members=True
ban_members=True,
manage_messages=True,
kick_members=True,
moderate_members=True,
)


Expand Down
2 changes: 1 addition & 1 deletion bot/libs/utils/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


def process_perms_name(
command: Union[commands.Group, commands.Command]
command: Union[commands.Group, commands.Command],
) -> Optional[str]:
merge_list = []
if (
Expand Down
13 changes: 10 additions & 3 deletions bot/libs/utils/pages/paginator.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ async def interaction_check(self, interaction: discord.Interaction) -> bool:
):
return True
await interaction.response.send_message(
"This pagination menu cannot be controlled by you, sorry!", ephemeral=True
"This pagination menu cannot be controlled by you, sorry!",
ephemeral=True,
)
return False

Expand All @@ -134,7 +135,10 @@ async def on_timeout(self) -> None:
await self.message.edit(view=None)

async def on_error(
self, interaction: discord.Interaction, error: Exception, item: discord.ui.Item
self,
interaction: discord.Interaction,
error: Exception,
item: discord.ui.Item,
) -> None:
if interaction.response.is_done():
await interaction.followup.send(
Expand All @@ -148,7 +152,10 @@ async def on_error(
async def start(
self, *, content: Optional[str] = None, ephemeral: bool = False
) -> None:
if self.check_embeds and not self.ctx.channel.permissions_for(self.ctx.me).embed_links: # type: ignore
if (
self.check_embeds
and not self.ctx.channel.permissions_for(self.ctx.me).embed_links
): # type: ignore
await self.ctx.send(
"Bot does not have embed links permission in this channel.",
ephemeral=True,
Expand Down
4 changes: 3 additions & 1 deletion bot/libs/utils/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ async def interaction_check(self, interaction: discord.Interaction, /) -> bool:
return True

async def on_error(
self, interaction: discord.Interaction, error: app_commands.AppCommandError
self,
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
await interaction.response.send_message(embed=FullErrorEmbed(error))
9 changes: 6 additions & 3 deletions bot/migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,8 @@ async def init():
except Exception:
traceback.print_exc()
click.secho(
"failed to initialize and apply migrations due to error", fg="red"
"failed to initialize and apply migrations due to error",
fg="red",
)


Expand All @@ -202,7 +203,8 @@ async def migrate(reason: str):
"an unapplied migration already exists for the next version, exiting"
)
click.secho(
"hint: apply pending migrations with the `upgrade` command", bold=True
"hint: apply pending migrations with the `upgrade` command",
bold=True,
)
return
revision = mg.create_revision(reason)
Expand Down Expand Up @@ -230,7 +232,8 @@ async def upgrade(sql):
try:
applied = await mg.upgrade()
click.secho(
f"Applied {applied} revisions(s) (Current: V{mg.version})", fg="green"
f"Applied {applied} revisions(s) (Current: V{mg.version})",
fg="green",
)
except Exception:
traceback.print_exc()
Expand Down
10 changes: 8 additions & 2 deletions bot/rodhaj.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ async def fetch_partial_config(self) -> Optional[PartialConfig]:
### Bot-related overrides

async def get_context(
self, origin: Union[discord.Interaction, discord.Message], /, *, cls=RoboContext
self,
origin: Union[discord.Interaction, discord.Message],
/,
*,
cls=RoboContext,
) -> RoboContext:
return await super().get_context(origin, cls=cls)

Expand All @@ -119,7 +123,9 @@ async def on_command_error(
elif isinstance(error, commands.CommandInvokeError):
original = error.original
if not isinstance(original, discord.HTTPException):
self.logger.exception("In %s:", ctx.command.qualified_name, exc_info=original) # type: ignore
self.logger.exception(
"In %s:", ctx.command.qualified_name, exc_info=original # type: ignore
)
elif isinstance(error, commands.BadArgument):
await ctx.send(str(error))

Expand Down
2 changes: 1 addition & 1 deletion docs/dev-guide/intro.rst
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ Setup
.. code-block:: bash
pip install -r requirements-dev.txt \
&& pre-commit install
&& lefthook install
5. Copy over the ``config-example.yml`` template over to the ``bot`` directory. Modify the values as appropriate.

Expand Down
Loading

0 comments on commit 11345f3

Please sign in to comment.