1
Fork 0
mirror of https://github.com/allthingslinux/tux.git synced 2024-10-02 16:43:12 +00:00

feat(neofetch.py): add new neofetch command to display system and server stats

chore(.pre-commit-config.yaml): add new pre-commit hooks for trailing commas and gitleaks
refactor(cog_loader.py): improve error logging for cog loading failures
style(.pre-commit-config.yaml, cog_loader.py): apply code formatting rules

style(dev.py, eval.py, git.py, mail.py, random.py): improve code readability by breaking down long lines of code into multiple lines
refactor(eval.py): add trailing comma to logger.warning for better code formatting
refactor(git.py): simplify import statement for Issue from githubkit.versions.latest.models
refactor(mail.py): add line breaks for better readability and code consistency
refactor(random.py): add line breaks in function parameters and conditions for better readability

style(xkcd.py, config.py, export.py): refactor function arguments to multi-line for better readability

style: reformat code for better readability in audit.py, commands.py, gate.py, member.py, run.py, temp_vc.py, tty_roles.py, purge.py
refactor: improve code readability by breaking down complex expressions and function calls into multiple lines

style: reformat code for better readability and PEP8 compliance in multiple files

refactor: simplify list declaration in guide.py for better readability

refactor: improve function parameter formatting in multiple files for better readability

refactor: improve string formatting in multiple files for better readability

refactor: improve function declaration formatting in multiple files for better readability

refactor: improve embed creation in rolecount.py for better readability

style(snippets.py, tldr.py, tools.py, wiki.py): reformat code for better readability
refactor(tools.py): simplify dictionary initialization for encodings and decodings
perf(tldr.py, tools.py): reduce subprocess.run arguments to improve performance
fix(wiki.py): correct the order of error handling and embed creation for better error management

refactor(case.py): improve readability by breaking down long function signatures into multiple lines
style(case.py): add trailing commas to improve code formatting and ease of future changes

style(case.py): improve readability by breaking down long function parameters into multiple lines
refactor(case.py): add trailing commas in dictionary to make future changes cleaner and more readable

style(guild_config.py): refactor function definitions to improve readability and adhere to PEP8 line length standards

style: apply PEP 8 style guide to improve readability and maintainability
refactor: add trailing commas to improve diff readability in future changes
fix(event_handler.py): add missing comma in message string to fix syntax error

style: apply black formatting to improve code readability and maintain consistency across the codebase
This commit is contained in:
kzndotsh 2024-07-02 03:41:57 +00:00
parent 2625d93419
commit fe57c02b99
48 changed files with 890 additions and 330 deletions

View file

@ -24,7 +24,7 @@ class Neofetch(commands.Cog):
async def neofetch(self, interaction: discord.Interaction) -> None:
if interaction.guild is None:
await interaction.response.send_message(
content="This command cannot be used in direct messages.", ephemeral=True
content="This command cannot be used in direct messages.", ephemeral=True,
)
return
@ -52,13 +52,15 @@ class Neofetch(commands.Cog):
"""
# get uptime in the format of days, hours, minutes
uptime = time.strftime("%d days, %H hours, %M minutes", time.gmtime(time.time() - psutil.boot_time()))
cpuusage = psutil.cpu_percent()
memusage = psutil.virtual_memory().percent
lines = f"""{yellow}tux{reset}@{yellow}{interaction.guild.name.lower().replace(" ", "")}{reset}
------------------
------------------
Tux Stats{reset}
{red}OS{reset}: Tux Alpha
{yellow}Kernel{reset}: 6.9
@ -66,7 +68,7 @@ class Neofetch(commands.Cog):
{cyan}CPU{reset}: {cpuusage}%
{blue}Memory{reset}: {memusage}%
{pink}Ping{reset}: {round(self.bot.latency * 1000)}ms
------------------
------------------
Server Stats{reset}
{red}Name{reset}: {interaction.guild.name}
{yellow}Owner{reset}: {interaction.guild.owner}

View file

@ -1,4 +1,9 @@
repos:
- repo: https://github.com/asottile/add-trailing-comma
rev: v3.1.0
hooks:
- id: add-trailing-comma
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.5.0
hooks:
@ -7,3 +12,10 @@ repos:
args: [--fix]
# Run the formatter.
- id: ruff-format
- repo: https://github.com/gitleaks/gitleaks
rev: v8.16.1
hooks:
- id: gitleaks
exclude: ".archive/"

View file

@ -76,7 +76,9 @@ class CogLoader(commands.Cog):
logger.debug(f"Successfully loaded cog: {module}")
except Exception as e:
logger.error(f"Failed to load cog {module}. Error: {e}\n{traceback.format_exc()}")
logger.error(
f"Failed to load cog {module}. Error: {e}\n{traceback.format_exc()}",
)
except Exception as e:
logger.error(f"An error occurred while processing {apath}: {e}")

View file

@ -15,7 +15,11 @@ class Dev(commands.Cog):
await ctx.send_help("dev")
@commands.has_guild_permissions(administrator=True)
@dev.command(name="sync_tree", description="Syncs the app command tree.", usage="dev sync_tree <guild>")
@dev.command(
name="sync_tree",
description="Syncs the app command tree.",
usage="dev sync_tree <guild>",
)
async def sync_tree(self, ctx: commands.Context[commands.Bot], guild: discord.Guild) -> None:
"""
Syncs the application commands to Discord.
@ -47,7 +51,11 @@ class Dev(commands.Cog):
await ctx.reply("Application command tree synced.")
@commands.has_guild_permissions(administrator=True)
@dev.command(name="clear_tree", description="Clears the app command tree.", usage="dev clear_tree")
@dev.command(
name="clear_tree",
description="Clears the app command tree.",
usage="dev clear_tree",
)
async def clear_tree(self, ctx: commands.Context[commands.Bot]) -> None:
"""
Parameters
@ -79,7 +87,11 @@ class Dev(commands.Cog):
await ctx.reply("Slash command tree cleared.")
@commands.has_guild_permissions(administrator=True)
@dev.command(name="load_cog", description="Loads a cog into the bot.", usage="dev load_cog <cog>")
@dev.command(
name="load_cog",
description="Loads a cog into the bot.",
usage="dev load_cog <cog>",
)
@app_commands.describe(cog="The name of the cog to load.")
async def load_cog(self, ctx: commands.Context[commands.Bot], *, cog: str) -> None:
"""
@ -120,7 +132,11 @@ class Dev(commands.Cog):
logger.info(f"Cog {cog} loaded.")
@commands.has_guild_permissions(administrator=True)
@dev.command(name="unload_cog", description="Unloads a cog from the bot.", usage="dev unload_cog <cog>")
@dev.command(
name="unload_cog",
description="Unloads a cog from the bot.",
usage="dev unload_cog <cog>",
)
async def unload_cog(self, ctx: commands.Context[commands.Bot], *, cog: str) -> None:
"""
Unloads an cog from the bot.
@ -154,7 +170,11 @@ class Dev(commands.Cog):
await ctx.send(f"Cog {cog} unloaded.")
@commands.has_guild_permissions(administrator=True)
@dev.command(name="reload_cog", description="Reloads a cog into the bot.", usage="dev reload_cog <cog>")
@dev.command(
name="reload_cog",
description="Reloads a cog into the bot.",
usage="dev reload_cog <cog>",
)
async def reload_cog(self, ctx: commands.Context[commands.Bot], *, cog: str) -> None:
"""
Reloads a cog in the bot.

View file

@ -57,7 +57,7 @@ class Eval(commands.Cog):
# Check if the user is the bot owner
if ctx.author.id != CONST.BOT_OWNER_ID:
logger.warning(
f"{ctx.author} tried to run eval but is not the bot owner. (Owner ID: {self.bot.owner_id}, User ID: {ctx.author.id})"
f"{ctx.author} tried to run eval but is not the bot owner. (Owner ID: {self.bot.owner_id}, User ID: {ctx.author.id})",
)
await ctx.send("You are not the bot owner. Better luck next time!")
return

View file

@ -1,9 +1,7 @@
import discord
from discord import app_commands
from discord.ext import commands
from githubkit.versions.latest.models import (
Issue,
)
from githubkit.versions.latest.models import Issue
from loguru import logger
from tux.services.github import GitHubService
@ -15,11 +13,7 @@ class LinkButton(discord.ui.View):
def __init__(self, url: str) -> None:
super().__init__()
self.add_item(
discord.ui.Button(
style=discord.ButtonStyle.link,
label="View on Github",
url=url,
)
discord.ui.Button(style=discord.ButtonStyle.link, label="View on Github", url=url),
)
@ -88,12 +82,7 @@ class Git(commands.Cog):
@app_commands.checks.has_any_role("Contributor", "Root", "Admin")
@git.command(name="create_issue", description="Create an issue.")
async def create_issue(
self,
interaction: discord.Interaction,
title: str,
body: str,
) -> None:
async def create_issue(self, interaction: discord.Interaction, title: str, body: str) -> None:
"""
Create an issue.
@ -168,16 +157,15 @@ class Git(commands.Cog):
logger.error(f"Error creating comment: {e}")
else:
await interaction.followup.send(embed=embed, view=LinkButton(created_issue_comment.html_url))
await interaction.followup.send(
embed=embed,
view=LinkButton(created_issue_comment.html_url),
)
logger.info(f"{interaction.user} created a comment.")
@app_commands.checks.has_any_role("Contributor", "Root", "Admin")
@git.command(name="close_issue", description="Close an issue.")
async def close_issue(
self,
interaction: discord.Interaction,
issue_number: int,
) -> None:
async def close_issue(self, interaction: discord.Interaction, issue_number: int) -> None:
"""
Close an issue.
@ -211,11 +199,7 @@ class Git(commands.Cog):
@app_commands.checks.has_any_role("Contributor", "Root", "Admin")
@git.command(name="get_issue", description="Get an issue.")
async def get_issue(
self,
interaction: discord.Interaction,
issue_number: int,
) -> None:
async def get_issue(self, interaction: discord.Interaction, issue_number: int) -> None:
"""
Get an issue.
@ -321,7 +305,9 @@ class Git(commands.Cog):
else:
await interaction.followup.send(
embed=embed,
view=LinkButton("https://github.com/allthingslinux/tux/issues?q=is%3Aissue+is%3Aclosed"),
view=LinkButton(
"https://github.com/allthingslinux/tux/issues?q=is%3Aissue+is%3Aclosed",
),
)
logger.info(f"{interaction.user} fetched closed issues.")
@ -401,11 +387,7 @@ class Git(commands.Cog):
@app_commands.checks.has_any_role("Contributor", "Root", "Admin")
@git.command(name="get_pull", description="Get a pull request.")
async def get_pull(
self,
interaction: discord.Interaction,
pull_number: int,
) -> None:
async def get_pull(self, interaction: discord.Interaction, pull_number: int) -> None:
"""
Get a pull request.

View file

@ -35,10 +35,16 @@ class Mail(commands.Cog):
@mail.command(name="register", description="Registers a user for mail.")
@app_commands.checks.has_any_role("Root", "Admin", "Mod")
async def register(self, interaction: discord.Interaction, member: discord.Member, username: str) -> None:
async def register(
self,
interaction: discord.Interaction,
member: discord.Member,
username: str,
) -> None:
if not username.isalnum():
await interaction.response.send_message(
"Username must be alphanumeric and contain no spaces.", ephemeral=True
"Username must be alphanumeric and contain no spaces.",
ephemeral=True,
)
return
@ -71,7 +77,11 @@ class Mail(commands.Cog):
async with httpx.AsyncClient(timeout=10.0) as client:
try:
response = await client.post(api_endpoint, headers=self.headers, json=mailbox_data)
response = await client.post(
api_endpoint,
headers=self.headers,
json=mailbox_data,
)
if response.status_code == 200:
result = response.json()
logger.info(f"Response JSON: {result}")
@ -93,7 +103,8 @@ class Mail(commands.Cog):
return
await interaction.response.send_message(
f"Successfully registered {mailbox_info} for mail.", ephemeral=True
f"Successfully registered {mailbox_info} for mail.",
ephemeral=True,
)
dm_message = f"""
@ -123,7 +134,8 @@ If you have any questions or need assistance, please feel free to reach out to t
elif response.status_code == 401:
await interaction.response.send_message(
"Unauthorized. Check your API credentials.", ephemeral=True
"Unauthorized. Check your API credentials.",
ephemeral=True,
)
else:
await interaction.response.send_message(
@ -132,12 +144,14 @@ If you have any questions or need assistance, please feel free to reach out to t
)
except httpx.RequestError as exc:
await interaction.response.send_message(
f"An error occurred while requesting {exc.request.url!r}.", ephemeral=True
f"An error occurred while requesting {exc.request.url!r}.",
ephemeral=True,
)
logger.error(f"An error occurred while requesting, {exc}")
else:
await interaction.response.send_message(
"This command can only be used in a guild (server).", ephemeral=True
"This command can only be used in a guild (server).",
ephemeral=True,
)

View file

@ -27,7 +27,9 @@ class Random(commands.Cog):
The context object for the command.
"""
await ctx.send(content="You got heads!" if random.choice([True, False]) else "You got tails!")
await ctx.send(
content="You got heads!" if random.choice([True, False]) else "You got tails!",
)
@random.command(name="8ball", description="Ask the magic 8ball a question.")
@app_commands.describe(question="The question to ask the 8ball.")
@ -123,7 +125,12 @@ class Random(commands.Cog):
minimum="The minimum value of the random number. (default: 0)",
maximum="The maximum value of the random number. (default: 100)",
)
async def random_number(self, ctx: commands.Context[commands.Bot], minimum: int = 0, maximum: int = 100) -> None:
async def random_number(
self,
ctx: commands.Context[commands.Bot],
minimum: int = 0,
maximum: int = 100,
) -> None:
"""
Generate a random number.
@ -138,7 +145,10 @@ class Random(commands.Cog):
"""
if minimum > maximum:
await ctx.reply(content="The minimum value must be less than the maximum value.", ephemeral=True)
await ctx.reply(
content="The minimum value must be less than the maximum value.",
ephemeral=True,
)
return
await ctx.reply(content=f"Your random number is: {random.randint(minimum, maximum)}")

View file

@ -11,18 +11,10 @@ class XkcdLinkButtons(discord.ui.View):
def __init__(self, explain_url: str, webpage_url: str) -> None:
super().__init__()
self.add_item(
discord.ui.Button(
style=discord.ButtonStyle.link,
label="Explainxkcd",
url=explain_url,
)
discord.ui.Button(style=discord.ButtonStyle.link, label="Explainxkcd", url=explain_url),
)
self.add_item(
discord.ui.Button(
style=discord.ButtonStyle.link,
label="Webpage",
url=webpage_url,
)
discord.ui.Button(style=discord.ButtonStyle.link, label="Webpage", url=webpage_url),
)
@ -61,7 +53,9 @@ class Xkcd(commands.Cog):
await interaction.response.send_message(embed=embed, ephemeral=ephemeral)
async def get_comic_and_embed(
self, latest: bool = False, number: int | None = None
self,
latest: bool = False,
number: int | None = None,
) -> tuple[discord.Embed, discord.ui.View | None, bool]:
"""
Get the xkcd comic and create an embed.

View file

@ -32,7 +32,11 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_senior_role", description="Set the senior role for the guild.")
async def set_senior_role(self, ctx: commands.Context[commands.Bot], role: discord.Role) -> None:
async def set_senior_role(
self,
ctx: commands.Context[commands.Bot],
role: discord.Role,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_senior_role_id(ctx.guild.id, role.id)
@ -48,7 +52,11 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_member_role", description="Set the base member role for the guild.")
async def set_member_role(self, ctx: commands.Context[commands.Bot], role: discord.Role) -> None:
async def set_member_role(
self,
ctx: commands.Context[commands.Bot],
role: discord.Role,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_base_member_role_id(ctx.guild.id, role.id)
@ -56,7 +64,11 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_junior_role", description="Set the junior role for the guild.")
async def set_junior_role(self, ctx: commands.Context[commands.Bot], role: discord.Role) -> None:
async def set_junior_role(
self,
ctx: commands.Context[commands.Bot],
role: discord.Role,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_junior_role_id(ctx.guild.id, role.id)
@ -71,8 +83,15 @@ class Config(commands.Cog):
await ctx.reply(f"Jail role set to {role.mention}.", ephemeral=True)
@commands.has_permissions(administrator=True)
@config.command(name="set_quarantine_role", description="Set the quarantine role for the guild.")
async def set_quarantine_role(self, ctx: commands.Context[commands.Bot], role: discord.Role) -> None:
@config.command(
name="set_quarantine_role",
description="Set the quarantine role for the guild.",
)
async def set_quarantine_role(
self,
ctx: commands.Context[commands.Bot],
role: discord.Role,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_quarantine_role_id(ctx.guild.id, role.id)
@ -88,7 +107,11 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_mod_log", description="Set the mod log channel for the guild.")
async def set_mod_log(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
async def set_mod_log(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_mod_log_channel_id(ctx.guild.id, channel.id)
@ -96,7 +119,11 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_audit_log", description="Set the audit log channel for the guild.")
async def set_audit_log(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
async def set_audit_log(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_audit_log_channel_id(ctx.guild.id, channel.id)
@ -104,15 +131,26 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_join_log", description="Set the join log channel for the guild.")
async def set_join_log(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
async def set_join_log(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_join_log_channel_id(ctx.guild.id, channel.id)
await ctx.reply(f"Join log channel set to {channel.mention}.", ephemeral=True)
@commands.has_permissions(administrator=True)
@config.command(name="set_private_log", description="Set the private log channel for the guild.")
async def set_private_log(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
@config.command(
name="set_private_log",
description="Set the private log channel for the guild.",
)
async def set_private_log(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_private_log_channel_id(ctx.guild.id, channel.id)
@ -120,7 +158,11 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_report_log", description="Set the report log channel for the guild.")
async def set_report_log(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
async def set_report_log(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_report_log_channel_id(ctx.guild.id, channel.id)
@ -128,7 +170,11 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_dev_log", description="Set the dev log channel for the guild.")
async def set_dev_log(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
async def set_dev_log(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_dev_log_channel_id(ctx.guild.id, channel.id)
@ -136,15 +182,26 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_jail_channel", description="Set the jail channel for the guild.")
async def set_jail_channel(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
async def set_jail_channel(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_jail_channel_id(ctx.guild.id, channel.id)
await ctx.reply(f"Jail channel set to {channel.mention}.", ephemeral=True)
@commands.has_permissions(administrator=True)
@config.command(name="set_starboard_channel", description="Set the starboard channel for the guild.")
async def set_starboard_channel(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
@config.command(
name="set_starboard_channel",
description="Set the starboard channel for the guild.",
)
async def set_starboard_channel(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_starboard_channel_id(ctx.guild.id, channel.id)
@ -152,7 +209,11 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_mod_channel", description="Set the mod channel for the guild.")
async def set_mod_channel(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
async def set_mod_channel(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_mod_channel_id(ctx.guild.id, channel.id)
@ -160,7 +221,11 @@ class Config(commands.Cog):
@commands.has_permissions(administrator=True)
@config.command(name="set_bot_channel", description="Set the bot channel for the guild.")
async def set_bot_channel(self, ctx: commands.Context[commands.Bot], channel: discord.TextChannel) -> None:
async def set_bot_channel(
self,
ctx: commands.Context[commands.Bot],
channel: discord.TextChannel,
) -> None:
if ctx.guild is None:
return
await self.db.update_guild_bot_channel_id(ctx.guild.id, channel.id)

View file

@ -38,7 +38,12 @@ class Export(commands.Cog):
return await interaction.response.send_message(embed=embed)
if flags and "--help" not in flags:
file = await exports.get_ban_list_csv(interaction, bans, valid_flags, flags.split(sep=" ") if flags else [])
file = await exports.get_ban_list_csv(
interaction,
bans,
valid_flags,
flags.split(sep=" ") if flags else [],
)
return await interaction.response.send_message(file=file)
title = f"Total Bans in {interaction.guild}: {len(bans)}"
@ -65,7 +70,10 @@ class Export(commands.Cog):
if flags and "--help" not in flags:
file = await exports.get_member_list_csv(
interaction, members, valid_flags, flags.split(sep=" ") if flags else []
interaction,
members,
valid_flags,
flags.split(sep=" ") if flags else [],
)
return await interaction.response.send_message(file=file)

View file

@ -74,7 +74,11 @@ class AuditLogging(commands.Cog):
await self.send_to_audit_log(audit_embed)
@commands.Cog.listener()
async def on_guild_channel_update(self, before: discord.abc.GuildChannel, after: discord.abc.GuildChannel) -> None:
async def on_guild_channel_update(
self,
before: discord.abc.GuildChannel,
after: discord.abc.GuildChannel,
) -> None:
"""
Logs when a channel is updated in a guild.
@ -164,7 +168,10 @@ class AuditLogging(commands.Cog):
@commands.Cog.listener()
async def on_guild_emojis_update(
self, guild: discord.Guild, before: list[discord.Emoji], after: list[discord.Emoji]
self,
guild: discord.Guild,
before: list[discord.Emoji],
after: list[discord.Emoji],
) -> None:
"""
Logs when emojis are updated in a guild.
@ -193,16 +200,16 @@ class AuditLogging(commands.Cog):
if deleted_emoji:
emojis_str = ", ".join([emoji.name for emoji in deleted_emoji])
embed.add_field(
name="Deleted Emoji",
value=emojis_str[:1024],
)
embed.add_field(name="Deleted Emoji", value=emojis_str[:1024])
await self.send_to_audit_log(embed)
@commands.Cog.listener()
async def on_guild_stickers_update(
self, guild: discord.Guild, before: list[discord.Sticker], after: list[discord.Sticker]
self,
guild: discord.Guild,
before: list[discord.Sticker],
after: list[discord.Sticker],
) -> None:
"""
Logs when stickers are updated in a guild.
@ -226,7 +233,9 @@ class AuditLogging(commands.Cog):
deleted_stickers = [sticker for sticker in before if sticker not in after]
if new_stickers:
stickers_str = "\n".join([f"[{sticker.name}]({sticker.url})" for sticker in new_stickers])
stickers_str = "\n".join(
[f"[{sticker.name}]({sticker.url})" for sticker in new_stickers],
)
embed.add_field(name="Added Stickers", value=stickers_str[:1024])
embed.set_image(url=new_stickers[0].url)
@ -408,7 +417,11 @@ class AuditLogging(commands.Cog):
await self.send_to_audit_log(embed)
@commands.Cog.listener()
async def on_scheduled_event_update(self, before: discord.ScheduledEvent, after: discord.ScheduledEvent) -> None:
async def on_scheduled_event_update(
self,
before: discord.ScheduledEvent,
after: discord.ScheduledEvent,
) -> None:
"""
Logs when a scheduled event is updated.
@ -466,7 +479,11 @@ class AuditLogging(commands.Cog):
await self.send_to_audit_log(embed)
@commands.Cog.listener()
async def on_stage_instance_update(self, before: discord.StageInstance, after: discord.StageInstance) -> None:
async def on_stage_instance_update(
self,
before: discord.StageInstance,
after: discord.StageInstance,
) -> None:
"""
Logs when a stage instance is updated.

View file

@ -13,7 +13,9 @@ class CommandEventsCog(commands.Cog, name="Command Events Handler"):
@commands.Cog.listener()
async def on_app_command_completion(
self, interaction: discord.Interaction, command: discord.app_commands.AppCommand
self,
interaction: discord.Interaction,
command: discord.app_commands.AppCommand,
) -> None:
logger.info(f"Command {command.name} completed by {interaction.user}")

View file

@ -27,14 +27,21 @@ class GateLogging(commands.Cog):
The member that joined the server.
"""
gate_embed = EmbedCreator.create_log_embed(title="Member Joined", description=f"Welcome {member.mention}!")
gate_embed = EmbedCreator.create_log_embed(
title="Member Joined",
description=f"Welcome {member.mention}!",
)
created_at = datetime_to_unix(member.created_at)
account_age = datetime_to_elapsed_time(member.created_at)
gate_embed.add_field(name="User", value=member)
gate_embed.add_field(name="ID", value=f"`{member.id}`")
gate_embed.add_field(name="Account Age", value=f"{account_age} ago ({created_at})", inline=False)
gate_embed.add_field(
name="Account Age",
value=f"{account_age} ago ({created_at})",
inline=False,
)
gate_embed.set_thumbnail(url=member.display_avatar)
await self.send_to_gate_log(gate_embed)

View file

@ -37,10 +37,16 @@ class MemberLogging(commands.Cog):
embed.add_field(name="Name", value=f"`{before.name}` -> `{after.name}`")
if before.display_name != after.display_name:
embed.add_field(name="Display Name", value=f"`{before.display_name}` -> `{after.display_name}`")
embed.add_field(
name="Display Name",
value=f"`{before.display_name}` -> `{after.display_name}`",
)
if before.global_name != after.global_name:
embed.add_field(name="Global Name", value=f"`{before.global_name}` -> `{after.global_name}`")
embed.add_field(
name="Global Name",
value=f"`{before.global_name}` -> `{after.global_name}`",
)
await self.send_to_audit_log(embed)

View file

@ -109,7 +109,9 @@ class Run(commands.Cog):
if normalized_lang not in compiler_map:
embed = EmbedCreator.create_error_embed(
title="Fatal exception occurred!", description="Bad Formatting", ctx=ctx
title="Fatal exception occurred!",
description="Bad Formatting",
ctx=ctx,
)
await ctx.send(embed=embed)
return ("", "", "")
@ -165,7 +167,9 @@ class Run(commands.Cog):
if normalized_lang not in compiler_map:
embed = EmbedCreator.create_error_embed(
title="Fatal exception occurred!", description="Bad Formatting", ctx=ctx
title="Fatal exception occurred!",
description="Bad Formatting",
ctx=ctx,
)
await ctx.send(embed=embed)
return ("", "", "")
@ -235,12 +239,7 @@ class Run(commands.Cog):
help="Run code in various languages.",
usage="$run `language`\n```code```",
)
async def run(
self,
ctx: commands.Context[commands.Bot],
*,
code: str,
):
async def run(self, ctx: commands.Context[commands.Bot], *, code: str):
"""
A code evaluator. The code must be provided in backticks along with the syntax highlighting to identify the language. Use short form syntax for the language. Available languages are Haskell, C, Rust, Julia, Python, C++.
@ -258,11 +257,20 @@ class Run(commands.Cog):
msg = await ctx.send("<a:typing:1236671731859722270>")
(filtered_output, gen_one, normalized_lang) = await self.generalized_code_executor(ctx, compiler_map, code)
(filtered_output, gen_one, normalized_lang) = await self.generalized_code_executor(
ctx,
compiler_map,
code,
)
await msg.delete()
if filtered_output == "" and gen_one == "" and normalized_lang == "":
return
await self.send_embedded_reply(ctx, gen_one, self.remove_ansi(filtered_output), normalized_lang)
await self.send_embedded_reply(
ctx,
gen_one,
self.remove_ansi(filtered_output),
normalized_lang,
)
@run.error
async def run_error(self, ctx: commands.Context[commands.Bot], error: Exception):
@ -283,7 +291,11 @@ class Run(commands.Cog):
if isinstance(error, commands.MissingRequiredArgument):
desc = f"Missing required argument: `{error.param.name}`"
embed = EmbedCreator.create_error_embed(title="Fatal exception occurred!", description=str(desc), ctx=ctx)
embed = EmbedCreator.create_error_embed(
title="Fatal exception occurred!",
description=str(desc),
ctx=ctx,
)
await ctx.send(embed=embed)

View file

@ -46,7 +46,10 @@ class TempVc(commands.Cog):
return
if before.channel is not None:
category = discord.utils.get(before.channel.guild.categories, id=int(CONST.TEMPVC_CATEGORY_ID or "0"))
category = discord.utils.get(
before.channel.guild.categories,
id=int(CONST.TEMPVC_CATEGORY_ID or "0"),
)
if (
not category
@ -59,7 +62,9 @@ class TempVc(commands.Cog):
if len(before.channel.members) == 0:
await before.channel.delete()
logger.info(f"Deleted temporary channel {before.channel.name} as it has no members.")
logger.info(
f"Deleted temporary channel {before.channel.name} as it has no members.",
)
# Search all lost temporary channels and delete them
for channel in category.voice_channels:

View file

@ -25,7 +25,10 @@ class TtyRoles(commands.Cog):
role_name = self.compute_role_name(user_count)
role = self.get_role_by_name(member, role_name) or await self.try_create_role(member, role_name)
role = self.get_role_by_name(member, role_name) or await self.try_create_role(
member,
role_name,
)
if role:
await self.try_assign_role(member, role)

View file

@ -11,9 +11,16 @@ class Purge(commands.Cog):
self.bot = bot
@app_commands.checks.has_any_role("Root", "Admin", "Sr. Mod", "Mod")
@app_commands.command(name="purge", description="Deletes a set number of messages in a channel.")
@app_commands.command(
name="purge",
description="Deletes a set number of messages in a channel.",
)
@app_commands.describe(number_messages="The number of messages to be purged.")
async def purge_messages(self, interaction: discord.Interaction, number_messages: int = 10) -> None:
async def purge_messages(
self,
interaction: discord.Interaction,
number_messages: int = 10,
) -> None:
"""
Deletes a set number of messages in a channel.
@ -27,7 +34,8 @@ class Purge(commands.Cog):
if not interaction.channel or interaction.channel.type != discord.ChannelType.text:
return await interaction.response.send_message(
"This command can only be used in text channels.", ephemeral=True
"This command can only be used in text channels.",
ephemeral=True,
)
if number_messages <= 0:
@ -52,7 +60,9 @@ class Purge(commands.Cog):
interaction=interaction,
)
logger.info(f"{interaction.user} purged {len(deleted)} messages from {interaction.channel.name}")
logger.info(
f"{interaction.user} purged {len(deleted)} messages from {interaction.channel.name}",
)
await interaction.edit_original_response(embed=embed)

View file

@ -46,7 +46,10 @@ class ReportModal(discord.ui.Modal):
channel = self.bot.get_channel(self.channel) or await self.bot.fetch_channel(self.channel)
if isinstance(channel, discord.TextChannel):
await interaction.response.send_message("Your report has been submitted.", ephemeral=True)
await interaction.response.send_message(
"Your report has been submitted.",
ephemeral=True,
)
await channel.send(embed=embed)

View file

@ -13,7 +13,11 @@ class Avatar(commands.Cog):
self.bot = bot
@commands.command(name="avatar", description="Get the avatar of a member.")
async def prefix_avatar(self, ctx: commands.Context[commands.Bot], member: discord.Member) -> None:
async def prefix_avatar(
self,
ctx: commands.Context[commands.Bot],
member: discord.Member,
) -> None:
"""
Get the avatar of a member.

View file

@ -12,11 +12,7 @@ meta_fields = [
"<#1193304492226129971>",
]
support_fields = [
"<#1172312602181902357>",
"<#1172312653797007461>",
"<#1172312674298761216>",
]
support_fields = ["<#1172312602181902357>", "<#1172312653797007461>", "<#1172312674298761216>"]
resources_fields = [
"<#1221117147091304548>",
@ -45,7 +41,10 @@ class Guide(commands.Cog):
guild = interaction.guild
if not guild:
await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
await interaction.response.send_message(
"This command can only be used in a server.",
ephemeral=True,
)
return
embed = EmbedCreator.create_info_embed(

View file

@ -66,7 +66,10 @@ class Info(commands.Cog):
description="Tux is a Discord bot written in Python using discord.py.",
interaction=interaction,
)
embed.add_field(name="GitHub", value="[View the source code](https://github.com/allthingslinux/tux)")
embed.add_field(
name="GitHub",
value="[View the source code](https://github.com/allthingslinux/tux)",
)
await interaction.response.send_message(embed=embed)

View file

@ -11,10 +11,7 @@ class MemberCount(commands.Cog):
self.bot = bot
@app_commands.command(name="membercount", description="Shows server member count")
async def membercount(
self,
interaction: discord.Interaction,
) -> None:
async def membercount(self, interaction: discord.Interaction) -> None:
"""
Show the member count for the server.
@ -44,7 +41,9 @@ class MemberCount(commands.Cog):
await interaction.response.send_message(embed=embed)
logger.info(f"{interaction.user} used the membercount command in {interaction.channel}.")
logger.info(
f"{interaction.user} used the membercount command in {interaction.channel}.",
)
async def setup(bot: commands.Bot) -> None:

View file

@ -36,7 +36,9 @@ class Ping(commands.Cog):
ram_amount_formatted = f"{ram_amount // (1024**2)}MB"
embed = EmbedCreator.create_success_embed(
title="Pong!", description="Here are some stats about the bot.", interaction=interaction
title="Pong!",
description="Here are some stats about the bot.",
interaction=interaction,
)
embed.add_field(name="API Latency", value=f"{discord_ping}ms", inline=True)

View file

@ -46,7 +46,9 @@ class Poll(commands.Cog):
return
# Create the description for the poll embed
description = "\n".join([f"{num + 1}\u20e3 {option}" for num, option in enumerate(options_list)])
description = "\n".join(
[f"{num + 1}\u20e3 {option}" for num, option in enumerate(options_list)],
)
embed = EmbedCreator.create_poll_embed(
title=title,

View file

@ -70,7 +70,8 @@ class RemindMe(commands.Cog):
)
if channel is not None and isinstance(
channel, discord.TextChannel | discord.Thread | discord.VoiceChannel
channel,
discord.TextChannel | discord.Thread | discord.VoiceChannel,
):
with contextlib.suppress(discord.Forbidden):
await channel.send(
@ -79,7 +80,9 @@ class RemindMe(commands.Cog):
)
else:
logger.error(f"Failed to send reminder to {user.id}, DMs closed and channel not found.")
logger.error(
f"Failed to send reminder to {user.id}, DMs closed and channel not found.",
)
else:
logger.error(f"Failed to send reminder to {reminder.reminder_user_id}, user not found.")
@ -137,7 +140,10 @@ class RemindMe(commands.Cog):
# Create a task to wait until the reminder expires
self.bot.loop.create_task(self.end_timer(closest_reminder))
@app_commands.command(name="remindme", description="Reminds you after a certain amount of time.")
@app_commands.command(
name="remindme",
description="Reminds you after a certain amount of time.",
)
async def remindme(self, interaction: discord.Interaction, time: str, *, reminder: str) -> None:
"""
Set a reminder for a certain amount of time.

View file

@ -165,9 +165,13 @@ class RoleCount(commands.Cog):
app_commands.Choice(name="DE/WM", value="de"),
app_commands.Choice(name="Misc", value="misc"),
app_commands.Choice(name="Vanity", value="vanity"),
]
],
)
async def rolecount(self, interaction: discord.Interaction, which: discord.app_commands.Choice[str]) -> None:
async def rolecount(
self,
interaction: discord.Interaction,
which: discord.app_commands.Choice[str],
) -> None:
if interaction.guild:
roles_emojis: list[list[int | str]] = self.roles_emoji_mapping.get(which.value, [])
await self.process_roles(interaction, roles_emojis, which)
@ -215,7 +219,10 @@ class RoleCount(commands.Cog):
# Check if current embed field count has reached max limit of 12 fields
if role_count >= 12:
pages.append(embed) # Append current embed to the page list
embed = self.create_embed(interaction, which) # Create a new embed for the next set of fields
embed = self.create_embed(
interaction,
which,
) # Create a new embed for the next set of fields
role_count = 0 # Reset the role count for new page
# Fetch an emoji for the role from available emojis or the predefined emoji identifier
@ -232,7 +239,11 @@ class RoleCount(commands.Cog):
return role_count, embed
def create_embed(self, interaction: discord.Interaction, which: discord.app_commands.Choice[str]):
def create_embed(
self,
interaction: discord.Interaction,
which: discord.app_commands.Choice[str],
):
return EmbedCreator.create_info_embed(
title=f"{which.name} Roles",
description="Number of users in each role",

View file

@ -48,13 +48,21 @@ class Snippets(commands.Cog):
# If there are no snippets, send an error message
if not snippets:
embed = EmbedCreator.create_error_embed(title="Error", description="No snippets found.", ctx=ctx)
embed = EmbedCreator.create_error_embed(
title="Error",
description="No snippets found.",
ctx=ctx,
)
await ctx.send(embed=embed, delete_after=5)
return
# If the page number is invalid, send an error message
if page < 1 or page > pages:
embed = EmbedCreator.create_error_embed(title="Error", description="Invalid page number.", ctx=ctx)
embed = EmbedCreator.create_error_embed(
title="Error",
description="Invalid page number.",
ctx=ctx,
)
await ctx.send(embed=embed)
return
@ -71,7 +79,7 @@ class Snippets(commands.Cog):
[
f"`{str(index + 1).zfill(2)}. {snippet.snippet_name.ljust(20)} | author: {self.bot.get_user(snippet.snippet_user_id) or 'Unknown'}`"
for index, snippet in enumerate(snippets)
]
],
),
ctx=ctx,
)
@ -79,7 +87,12 @@ class Snippets(commands.Cog):
await ctx.send(embed=embed)
@commands.command(name="deletesnippet", usage="$ds <name>", description="Delete a snippet.", aliases=["ds"])
@commands.command(
name="deletesnippet",
usage="$ds <name>",
description="Delete a snippet.",
aliases=["ds"],
)
async def delete_snippet(self, ctx: commands.Context[commands.Bot], name: str) -> None:
"""
Delete a snippet.
@ -99,7 +112,11 @@ class Snippets(commands.Cog):
snippet = await self.db_controller.get_snippet_by_name_and_guild_id(name, ctx.guild.id)
if snippet is None:
embed = EmbedCreator.create_error_embed(title="Error", description="Snippet not found.", ctx=ctx)
embed = EmbedCreator.create_error_embed(
title="Error",
description="Snippet not found.",
ctx=ctx,
)
await ctx.send(embed=embed, delete_after=5)
return
@ -107,7 +124,9 @@ class Snippets(commands.Cog):
author_id = snippet.snippet_user_id or 0
if author_id != ctx.author.id:
embed = EmbedCreator.create_error_embed(
title="Error", description="You can only delete your own snippets.", ctx=ctx
title="Error",
description="You can only delete your own snippets.",
ctx=ctx,
)
await ctx.send(embed=embed)
return
@ -117,7 +136,12 @@ class Snippets(commands.Cog):
await ctx.send("Snippet deleted.")
logger.info(f"{ctx.author} deleted the snippet with the name {name}.")
@commands.command(name="snippet", usage="$s <name>", description="Get a snippet.", aliases=["s"])
@commands.command(
name="snippet",
usage="$s <name>",
description="Get a snippet.",
aliases=["s"],
)
async def get_snippet(self, ctx: commands.Context[commands.Bot], name: str) -> None:
"""
Get a snippet.
@ -137,7 +161,11 @@ class Snippets(commands.Cog):
snippet = await self.db_controller.get_snippet_by_name_and_guild_id(name, ctx.guild.id)
if snippet is None:
embed = EmbedCreator.create_error_embed(title="Error", description="Snippet not found.", ctx=ctx)
embed = EmbedCreator.create_error_embed(
title="Error",
description="Snippet not found.",
ctx=ctx,
)
await ctx.send(embed=embed, delete_after=5)
return
@ -170,7 +198,11 @@ class Snippets(commands.Cog):
snippet = await self.db_controller.get_snippet_by_name_and_guild_id(name, ctx.guild.id)
if snippet is None:
embed = EmbedCreator.create_error_embed(title="Error", description="Snippet not found.", ctx=ctx)
embed = EmbedCreator.create_error_embed(
title="Error",
description="Snippet not found.",
ctx=ctx,
)
await ctx.send(embed=embed, delete_after=5)
return
@ -186,7 +218,10 @@ class Snippets(commands.Cog):
user=author,
)
embed.timestamp = snippet.snippet_created_at or datetime.datetime.fromtimestamp(0, datetime.UTC)
embed.timestamp = snippet.snippet_created_at or datetime.datetime.fromtimestamp(
0,
datetime.UTC,
)
await ctx.send(embed=embed)
@ -230,7 +265,11 @@ class Snippets(commands.Cog):
# Check if the snippet already exists
if await self.db_controller.get_snippet_by_name_and_guild_id(name, ctx.guild.id) is not None:
embed = EmbedCreator.create_error_embed(title="Error", description="Snippet already exists.", ctx=ctx)
embed = EmbedCreator.create_error_embed(
title="Error",
description="Snippet already exists.",
ctx=ctx,
)
await ctx.send(embed=embed)
return

View file

@ -16,7 +16,11 @@ class Tldr(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
async def get_autocomplete(self, interaction: discord.Interaction, query: str) -> list[app_commands.Choice[str]]:
async def get_autocomplete(
self,
interaction: discord.Interaction,
query: str,
) -> list[app_commands.Choice[str]]:
"""
Provide autocomplete suggestions for TLDR commands based on user query.
@ -61,7 +65,9 @@ class Tldr(commands.Cog):
tldr_page = self.get_tldr_page(command)
embed = EmbedCreator.create_info_embed(
title=f"TLDR for {command}", description=tldr_page, interaction=interaction
title=f"TLDR for {command}",
description=tldr_page,
interaction=interaction,
)
await interaction.response.send_message(embed=embed)
@ -123,12 +129,7 @@ class Tldr(commands.Cog):
"""
try:
process = subprocess.run(
command_list,
capture_output=True,
text=True,
check=True,
)
process = subprocess.run(command_list, capture_output=True, text=True, check=True)
except subprocess.CalledProcessError:
return default_response

View file

@ -21,12 +21,8 @@ COLOR_FORMATS = {"HEX": "hex", "RGB": "rgb", "HSL": "hsl", "CMYK": "cmyk"}
class Tools(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.encodings = {
"base64": self.encode_base64,
}
self.decodings = {
"base64": self.decode_base64,
}
self.encodings = {"base64": self.encode_base64}
self.decodings = {"base64": self.decode_base64}
def encode_base64(self, input_string: str):
return b64encode(input_string.encode()).decode()
@ -41,7 +37,7 @@ class Tools(commands.Cog):
@app_commands.choices(
color_format=[
app_commands.Choice[str](name=color_format, value=value) for color_format, value in COLOR_FORMATS.items()
]
],
)
async def colors(
self,
@ -146,16 +142,20 @@ class Tools(commands.Cog):
return embed
async def send_message(self, interaction: discord.Interaction, embed: discord.Embed, png_bio: io.BytesIO) -> None:
await interaction.response.send_message(embed=embed, file=discord.File(png_bio, "color.png"))
async def send_message(
self,
interaction: discord.Interaction,
embed: discord.Embed,
png_bio: io.BytesIO,
) -> None:
await interaction.response.send_message(
embed=embed,
file=discord.File(png_bio, "color.png"),
)
@group.command(name="encode", description="Encodes a string to a specified format.")
@app_commands.describe(encoding="The encoding format to use", string="The string to encode")
@app_commands.choices(
encoding=[
app_commands.Choice[str](name="base64", value="base64"),
]
)
@app_commands.choices(encoding=[app_commands.Choice[str](name="base64", value="base64")])
async def encode(
self,
interaction: discord.Interaction,
@ -190,17 +190,17 @@ class Tools(commands.Cog):
except KeyError:
description = "Invalid encoding selected!"
embed = EmbedCreator.create_info_embed(title=title, description=description, interaction=interaction)
embed = EmbedCreator.create_info_embed(
title=title,
description=description,
interaction=interaction,
)
await interaction.response.send_message(embed=embed)
@group.command(name="decode", description="Decodes a string from a specified format.")
@app_commands.describe(encoding="The decoding format to use", string="The string to decode")
@app_commands.choices(
encoding=[
app_commands.Choice[str](name="base64", value="base64"),
]
)
@app_commands.choices(encoding=[app_commands.Choice[str](name="base64", value="base64")])
async def decode(
self,
interaction: discord.Interaction,
@ -235,7 +235,11 @@ class Tools(commands.Cog):
except KeyError:
description = "Invalid decoding selected!"
embed = EmbedCreator.create_info_embed(title=title, description=description, interaction=interaction)
embed = EmbedCreator.create_info_embed(
title=title,
description=description,
interaction=interaction,
)
await interaction.response.send_message(embed=embed)

View file

@ -104,15 +104,15 @@ class Wiki(commands.Cog):
title: tuple[str, str] = self.query_arch_wiki(query)
if title[0] == "error":
embed = EmbedCreator.create_error_embed(title="Error", description="No search results found.", ctx=ctx)
else:
embed = EmbedCreator.create_info_embed(
title=title[0],
description=title[1],
embed = EmbedCreator.create_error_embed(
title="Error",
description="No search results found.",
ctx=ctx,
)
else:
embed = EmbedCreator.create_info_embed(title=title[0], description=title[1], ctx=ctx)
await ctx.reply(embed=embed)
@wiki.command(name="atl", description="Search the All Things Linux Wiki.")
@ -132,15 +132,15 @@ class Wiki(commands.Cog):
title: tuple[str, str] = self.query_atl_wiki(query)
if title[0] == "error":
embed = EmbedCreator.create_error_embed(title="Error", description="No search results found.", ctx=ctx)
else:
embed = EmbedCreator.create_info_embed(
title=title[0],
description=title[1],
embed = EmbedCreator.create_error_embed(
title="Error",
description="No search results found.",
ctx=ctx,
)
else:
embed = EmbedCreator.create_info_embed(title=title[0], description=title[1], ctx=ctx)
await ctx.reply(embed=embed)

View file

@ -32,14 +32,17 @@ class CaseController:
"case_reason": case_reason,
"case_type": case_type,
"case_expires_at": case_expires_at,
}
},
)
async def delete_case_by_id(self, case_id: int) -> None:
await self.table.delete(where={"case_id": case_id})
async def update_case_by_case_number_and_guild_id(
self, case_number: int, guild_id: int, case_reason: str
self,
case_number: int,
guild_id: int,
case_reason: str,
) -> Case | None:
return await self.table.update(
where={"case_number_guild_id": {"case_number": case_number, "guild_id": guild_id}},
@ -55,121 +58,181 @@ class CaseController:
async def get_cases_by_moderator_id(self, case_moderator_id: int) -> list[Case] | None:
return await self.table.find_many(where={"case_moderator_id": case_moderator_id})
async def get_cases_by_guild_id_and_target_id(self, guild_id: int, case_target_id: int) -> list[Case] | None:
return await self.table.find_many(where={"guild_id": guild_id, "case_target_id": case_target_id})
async def get_cases_by_guild_id_and_target_id(
self,
guild_id: int,
case_target_id: int,
) -> list[Case] | None:
return await self.table.find_many(
where={"guild_id": guild_id, "case_target_id": case_target_id},
)
async def get_cases_by_guild_id_and_moderator_id(self, guild_id: int, case_moderator_id: int) -> list[Case] | None:
return await self.table.find_many(where={"guild_id": guild_id, "case_moderator_id": case_moderator_id})
async def get_cases_by_guild_id_and_moderator_id(
self,
guild_id: int,
case_moderator_id: int,
) -> list[Case] | None:
return await self.table.find_many(
where={"guild_id": guild_id, "case_moderator_id": case_moderator_id},
)
async def get_cases_by_guild_id_and_type(self, guild_id: int, case_type: CaseType) -> list[Case] | None:
async def get_cases_by_guild_id_and_type(
self,
guild_id: int,
case_type: CaseType,
) -> list[Case] | None:
return await self.table.find_many(where={"guild_id": guild_id, "case_type": case_type})
async def get_cases_by_guild_id_and_reason(self, guild_id: int, case_reason: str) -> list[Case] | None:
async def get_cases_by_guild_id_and_reason(
self,
guild_id: int,
case_reason: str,
) -> list[Case] | None:
return await self.table.find_many(where={"guild_id": guild_id, "case_reason": case_reason})
async def get_cases_by_guild_id_and_expires_at(self, guild_id: int, case_expires_at: datetime) -> list[Case] | None:
return await self.table.find_many(where={"guild_id": guild_id, "case_expires_at": case_expires_at})
async def get_cases_by_guild_id_and_expires_at(
self,
guild_id: int,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={"guild_id": guild_id, "case_expires_at": case_expires_at},
)
async def get_cases_by_guild_id_and_target_id_and_moderator_id(
self, guild_id: int, case_target_id: int, case_moderator_id: int
self,
guild_id: int,
case_target_id: int,
case_moderator_id: int,
) -> list[Case] | None:
return await self.table.find_many(
where={
"guild_id": guild_id,
"case_target_id": case_target_id,
"case_moderator_id": case_moderator_id,
}
},
)
async def get_cases_by_guild_id_and_target_id_and_type(
self, guild_id: int, case_target_id: int, case_type: CaseType
self,
guild_id: int,
case_target_id: int,
case_type: CaseType,
) -> list[Case] | None:
return await self.table.find_many(
where={"guild_id": guild_id, "case_target_id": case_target_id, "case_type": case_type}
where={"guild_id": guild_id, "case_target_id": case_target_id, "case_type": case_type},
)
async def get_cases_by_guild_id_and_target_id_and_reason(
self, guild_id: int, case_target_id: int, case_reason: str
self,
guild_id: int,
case_target_id: int,
case_reason: str,
) -> list[Case] | None:
return await self.table.find_many(
where={
"guild_id": guild_id,
"case_target_id": case_target_id,
"case_reason": case_reason,
}
},
)
async def get_cases_by_guild_id_and_target_id_and_expires_at(
self, guild_id: int, case_target_id: int, case_expires_at: datetime
self,
guild_id: int,
case_target_id: int,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={
"guild_id": guild_id,
"case_target_id": case_target_id,
"case_expires_at": case_expires_at,
}
},
)
async def get_cases_by_guild_id_and_moderator_id_and_type(
self, guild_id: int, case_moderator_id: int, case_type: CaseType
self,
guild_id: int,
case_moderator_id: int,
case_type: CaseType,
) -> list[Case] | None:
return await self.table.find_many(
where={
"guild_id": guild_id,
"case_moderator_id": case_moderator_id,
"case_type": case_type,
}
},
)
async def get_cases_by_guild_id_and_moderator_id_and_reason(
self, guild_id: int, case_moderator_id: int, case_reason: str
self,
guild_id: int,
case_moderator_id: int,
case_reason: str,
) -> list[Case] | None:
return await self.table.find_many(
where={
"guild_id": guild_id,
"case_moderator_id": case_moderator_id,
"case_reason": case_reason,
}
},
)
async def get_cases_by_guild_id_and_moderator_id_and_expires_at(
self, guild_id: int, case_moderator_id: int, case_expires_at: datetime
self,
guild_id: int,
case_moderator_id: int,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={
"guild_id": guild_id,
"case_moderator_id": case_moderator_id,
"case_expires_at": case_expires_at,
}
},
)
async def get_cases_by_guild_id_and_type_and_reason(
self, guild_id: int, case_type: CaseType, case_reason: str
self,
guild_id: int,
case_type: CaseType,
case_reason: str,
) -> list[Case] | None:
return await self.table.find_many(
where={"guild_id": guild_id, "case_type": case_type, "case_reason": case_reason}
where={"guild_id": guild_id, "case_type": case_type, "case_reason": case_reason},
)
async def get_cases_by_guild_id_and_type_and_expires_at(
self, guild_id: int, case_type: CaseType, case_expires_at: datetime
self,
guild_id: int,
case_type: CaseType,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={"guild_id": guild_id, "case_type": case_type, "case_expires_at": case_expires_at}
where={"guild_id": guild_id, "case_type": case_type, "case_expires_at": case_expires_at},
)
async def get_cases_by_guild_id_and_reason_and_expires_at(
self, guild_id: int, case_reason: str, case_expires_at: datetime
self,
guild_id: int,
case_reason: str,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={
"guild_id": guild_id,
"case_reason": case_reason,
"case_expires_at": case_expires_at,
}
},
)
async def get_cases_by_guild_id_and_target_id_and_moderator_id_and_type(
self, guild_id: int, case_target_id: int, case_moderator_id: int, case_type: CaseType
self,
guild_id: int,
case_target_id: int,
case_moderator_id: int,
case_type: CaseType,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -177,11 +240,15 @@ class CaseController:
"case_target_id": case_target_id,
"case_moderator_id": case_moderator_id,
"case_type": case_type,
}
},
)
async def get_cases_by_guild_id_and_target_id_and_moderator_id_and_reason(
self, guild_id: int, case_target_id: int, case_moderator_id: int, case_reason: str
self,
guild_id: int,
case_target_id: int,
case_moderator_id: int,
case_reason: str,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -189,11 +256,15 @@ class CaseController:
"case_target_id": case_target_id,
"case_moderator_id": case_moderator_id,
"case_reason": case_reason,
}
},
)
async def get_cases_by_guild_id_and_target_id_and_moderator_id_and_expires_at(
self, guild_id: int, case_target_id: int, case_moderator_id: int, case_expires_at: datetime
self,
guild_id: int,
case_target_id: int,
case_moderator_id: int,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -201,11 +272,15 @@ class CaseController:
"case_target_id": case_target_id,
"case_moderator_id": case_moderator_id,
"case_expires_at": case_expires_at,
}
},
)
async def get_cases_by_guild_id_and_target_id_and_type_and_reason(
self, guild_id: int, case_target_id: int, case_type: CaseType, case_reason: str
self,
guild_id: int,
case_target_id: int,
case_type: CaseType,
case_reason: str,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -213,11 +288,15 @@ class CaseController:
"case_target_id": case_target_id,
"case_type": case_type,
"case_reason": case_reason,
}
},
)
async def get_cases_by_guild_id_and_target_id_and_type_and_expires_at(
self, guild_id: int, case_target_id: int, case_type: CaseType, case_expires_at: datetime
self,
guild_id: int,
case_target_id: int,
case_type: CaseType,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -225,11 +304,15 @@ class CaseController:
"case_target_id": case_target_id,
"case_type": case_type,
"case_expires_at": case_expires_at,
}
},
)
async def get_cases_by_guild_id_and_target_id_and_reason_and_expires_at(
self, guild_id: int, case_target_id: int, case_reason: str, case_expires_at: datetime
self,
guild_id: int,
case_target_id: int,
case_reason: str,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -237,11 +320,15 @@ class CaseController:
"case_target_id": case_target_id,
"case_reason": case_reason,
"case_expires_at": case_expires_at,
}
},
)
async def get_cases_by_guild_id_and_moderator_id_and_type_and_reason(
self, guild_id: int, case_moderator_id: int, case_type: CaseType, case_reason: str
self,
guild_id: int,
case_moderator_id: int,
case_type: CaseType,
case_reason: str,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -249,11 +336,15 @@ class CaseController:
"case_moderator_id": case_moderator_id,
"case_type": case_type,
"case_reason": case_reason,
}
},
)
async def get_cases_by_guild_id_and_moderator_id_and_type_and_expires_at(
self, guild_id: int, case_moderator_id: int, case_type: CaseType, case_expires_at: datetime
self,
guild_id: int,
case_moderator_id: int,
case_type: CaseType,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -261,11 +352,15 @@ class CaseController:
"case_moderator_id": case_moderator_id,
"case_type": case_type,
"case_expires_at": case_expires_at,
}
},
)
async def get_cases_by_guild_id_and_moderator_id_and_reason_and_expires_at(
self, guild_id: int, case_moderator_id: int, case_reason: str, case_expires_at: datetime
self,
guild_id: int,
case_moderator_id: int,
case_reason: str,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -273,11 +368,15 @@ class CaseController:
"case_moderator_id": case_moderator_id,
"case_reason": case_reason,
"case_expires_at": case_expires_at,
}
},
)
async def get_cases_by_guild_id_and_type_and_reason_and_expires_at(
self, guild_id: int, case_type: CaseType, case_reason: str, case_expires_at: datetime
self,
guild_id: int,
case_type: CaseType,
case_reason: str,
case_expires_at: datetime,
) -> list[Case] | None:
return await self.table.find_many(
where={
@ -285,5 +384,5 @@ class CaseController:
"case_type": case_type,
"case_reason": case_reason,
"case_expires_at": case_expires_at,
}
},
)

View file

@ -26,7 +26,11 @@ class GuildConfigController:
async def delete_guild_config_by_id(self, guild_id: int) -> None:
await self.table.delete(where={"guild_id": guild_id})
async def update_guild_mod_log_channel_id(self, guild_id: int, guild_mod_log_channel_id: int) -> GuildConfig | None:
async def update_guild_mod_log_channel_id(
self,
guild_id: int,
guild_mod_log_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -40,7 +44,9 @@ class GuildConfigController:
)
async def update_guild_audit_log_channel_id(
self, guild_id: int, guild_audit_log_channel_id: int
self,
guild_id: int,
guild_audit_log_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
@ -55,7 +61,9 @@ class GuildConfigController:
)
async def update_guild_join_log_channel_id(
self, guild_id: int, guild_join_log_channel_id: int
self,
guild_id: int,
guild_join_log_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
@ -70,7 +78,9 @@ class GuildConfigController:
)
async def update_guild_private_log_channel_id(
self, guild_id: int, guild_private_log_channel_id: int
self,
guild_id: int,
guild_private_log_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
@ -85,7 +95,9 @@ class GuildConfigController:
)
async def update_guild_report_log_channel_id(
self, guild_id: int, guild_report_log_channel_id: int
self,
guild_id: int,
guild_report_log_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
@ -99,7 +111,11 @@ class GuildConfigController:
},
)
async def update_guild_dev_log_channel_id(self, guild_id: int, guild_dev_log_channel_id: int) -> GuildConfig | None:
async def update_guild_dev_log_channel_id(
self,
guild_id: int,
guild_dev_log_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -112,20 +128,25 @@ class GuildConfigController:
},
)
async def update_guild_jail_channel_id(self, guild_id: int, guild_jail_channel_id: int) -> GuildConfig | None:
async def update_guild_jail_channel_id(
self,
guild_id: int,
guild_jail_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
data={
"create": {
"guild_id": guild_id,
"guild_jail_channel_id": guild_jail_channel_id,
},
"create": {"guild_id": guild_id, "guild_jail_channel_id": guild_jail_channel_id},
"update": {"guild_jail_channel_id": guild_jail_channel_id},
},
)
async def update_guild_general_channel_id(self, guild_id: int, guild_general_channel_id: int) -> GuildConfig | None:
async def update_guild_general_channel_id(
self,
guild_id: int,
guild_general_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -139,7 +160,9 @@ class GuildConfigController:
)
async def update_guild_starboard_channel_id(
self, guild_id: int, guild_starboard_channel_id: int
self,
guild_id: int,
guild_starboard_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
@ -153,7 +176,11 @@ class GuildConfigController:
},
)
async def update_guild_mod_channel_id(self, guild_id: int, guild_mod_channel_id: int) -> GuildConfig | None:
async def update_guild_mod_channel_id(
self,
guild_id: int,
guild_mod_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -163,7 +190,11 @@ class GuildConfigController:
},
)
async def update_guild_bot_channel_id(self, guild_id: int, guild_bot_channel_id: int) -> GuildConfig | None:
async def update_guild_bot_channel_id(
self,
guild_id: int,
guild_bot_channel_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -173,7 +204,11 @@ class GuildConfigController:
},
)
async def update_guild_dev_role_id(self, guild_id: int, guild_dev_role_id: int) -> GuildConfig | None:
async def update_guild_dev_role_id(
self,
guild_id: int,
guild_dev_role_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -183,7 +218,11 @@ class GuildConfigController:
},
)
async def update_guild_admin_role_id(self, guild_id: int, guild_admin_role_id: int) -> GuildConfig | None:
async def update_guild_admin_role_id(
self,
guild_id: int,
guild_admin_role_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -193,7 +232,11 @@ class GuildConfigController:
},
)
async def update_guild_senior_role_id(self, guild_id: int, guild_senior_role_id: int) -> GuildConfig | None:
async def update_guild_senior_role_id(
self,
guild_id: int,
guild_senior_role_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -203,7 +246,11 @@ class GuildConfigController:
},
)
async def update_guild_mod_role_id(self, guild_id: int, guild_mod_role_id: int) -> GuildConfig | None:
async def update_guild_mod_role_id(
self,
guild_id: int,
guild_mod_role_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -213,7 +260,11 @@ class GuildConfigController:
},
)
async def update_guild_junior_role_id(self, guild_id: int, guild_junior_role_id: int) -> GuildConfig | None:
async def update_guild_junior_role_id(
self,
guild_id: int,
guild_junior_role_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -223,7 +274,11 @@ class GuildConfigController:
},
)
async def update_guild_base_staff_role_id(self, guild_id: int, guild_base_staff_role_id: int) -> GuildConfig | None:
async def update_guild_base_staff_role_id(
self,
guild_id: int,
guild_base_staff_role_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -237,7 +292,9 @@ class GuildConfigController:
)
async def update_guild_base_member_role_id(
self, guild_id: int, guild_base_member_role_id: int
self,
guild_id: int,
guild_base_member_role_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
@ -251,7 +308,11 @@ class GuildConfigController:
},
)
async def update_guild_jail_role_id(self, guild_id: int, guild_jail_role_id: int) -> GuildConfig | None:
async def update_guild_jail_role_id(
self,
guild_id: int,
guild_jail_role_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -261,7 +322,11 @@ class GuildConfigController:
},
)
async def update_guild_quarantine_role_id(self, guild_id: int, guild_quarantine_role_id: int) -> GuildConfig | None:
async def update_guild_quarantine_role_id(
self,
guild_id: int,
guild_quarantine_role_id: int,
) -> GuildConfig | None:
await self.ensure_guild_exists(guild_id)
return await self.table.upsert(
where={"guild_id": guild_id},
@ -290,9 +355,17 @@ class GuildConfigController:
# data={"guild_disabled_cogs": guild_disabled_cogs},
# )
async def update_guild_config(self, guild_id: int, data: GuildConfigUpdateInput) -> GuildConfig | None:
async def update_guild_config(
self,
guild_id: int,
data: GuildConfigUpdateInput,
) -> GuildConfig | None:
return await self.table.update(where={"guild_id": guild_id}, data=data)
async def get_guild_config_field_value(self, guild_id: int, field: GuildConfigScalarFieldKeys) -> Any:
async def get_guild_config_field_value(
self,
guild_id: int,
field: GuildConfigScalarFieldKeys,
) -> Any:
config = await self.table.find_first(where={"guild_id": guild_id})
return None if config is None else getattr(config, field)

View file

@ -25,7 +25,7 @@ class NoteController:
"note_moderator_id": note_moderator_id,
"note_content": note_content,
"guild_id": guild_id,
}
},
)
async def delete_note_by_id(self, note_id: int) -> None:
@ -46,22 +46,41 @@ class NoteController:
async def get_notes_by_guild_id(self, guild_id: int) -> list[Note]:
return await self.table.find_many(where={"guild_id": guild_id})
async def get_notes_by_target_id_and_guild_id(self, target_id: int, guild_id: int) -> list[Note]:
async def get_notes_by_target_id_and_guild_id(
self,
target_id: int,
guild_id: int,
) -> list[Note]:
return await self.table.find_many(where={"note_target_id": target_id, "guild_id": guild_id})
async def get_notes_by_moderator_id_and_guild_id(self, moderator_id: int, guild_id: int) -> list[Note]:
return await self.table.find_many(where={"note_moderator_id": moderator_id, "guild_id": guild_id})
async def get_notes_by_moderator_id_and_guild_id(
self,
moderator_id: int,
guild_id: int,
) -> list[Note]:
return await self.table.find_many(
where={"note_moderator_id": moderator_id, "guild_id": guild_id},
)
async def get_notes_by_target_id_and_moderator_id(self, target_id: int, moderator_id: int) -> list[Note]:
return await self.table.find_many(where={"note_target_id": target_id, "note_moderator_id": moderator_id})
async def get_notes_by_target_id_and_moderator_id(
self,
target_id: int,
moderator_id: int,
) -> list[Note]:
return await self.table.find_many(
where={"note_target_id": target_id, "note_moderator_id": moderator_id},
)
async def get_notes_by_target_id_moderator_id_and_guild_id(
self, target_id: int, moderator_id: int, guild_id: int
self,
target_id: int,
moderator_id: int,
guild_id: int,
) -> list[Note]:
return await self.table.find_many(
where={
"note_target_id": target_id,
"note_moderator_id": moderator_id,
"guild_id": guild_id,
}
},
)

View file

@ -29,13 +29,17 @@ class ReminderController:
"reminder_expires_at": reminder_expires_at,
"reminder_channel_id": reminder_channel_id,
"guild_id": guild_id,
}
},
)
async def delete_reminder_by_id(self, reminder_id: int) -> None:
await self.table.delete(where={"reminder_id": reminder_id})
async def update_reminder_by_id(self, reminder_id: int, reminder_content: str) -> Reminder | None:
async def update_reminder_by_id(
self,
reminder_id: int,
reminder_content: str,
) -> Reminder | None:
return await self.table.update(
where={"reminder_id": reminder_id},
data={"reminder_content": reminder_content},

View file

@ -12,13 +12,21 @@ class SnippetController:
return await self.table.find_many()
async def get_all_snippets_sorted(self, newestfirst: bool = True) -> list[Snippet]:
return await self.table.find_many(order={"snippet_created_at": "desc" if newestfirst else "asc"})
return await self.table.find_many(
order={"snippet_created_at": "desc" if newestfirst else "asc"},
)
async def get_snippet_by_name(self, snippet_name: str) -> Snippet | None:
return await self.table.find_first(where={"snippet_name": snippet_name})
async def get_snippet_by_name_and_guild_id(self, snippet_name: str, guild_id: int) -> Snippet | None:
return await self.table.find_first(where={"snippet_name": snippet_name, "guild_id": guild_id})
async def get_snippet_by_name_and_guild_id(
self,
snippet_name: str,
guild_id: int,
) -> Snippet | None:
return await self.table.find_first(
where={"snippet_name": snippet_name, "guild_id": guild_id},
)
async def create_snippet(
self,
@ -35,11 +43,14 @@ class SnippetController:
"snippet_created_at": snippet_created_at,
"snippet_user_id": snippet_user_id,
"guild_id": guild_id,
}
},
)
async def delete_snippet_by_id(self, snippet_id: int) -> None:
await self.table.delete(where={"snippet_id": snippet_id})
async def update_snippet_by_id(self, snippet_id: int, snippet_content: str) -> Snippet | None:
return await self.table.update(where={"snippet_id": snippet_id}, data={"snippet_content": snippet_content})
return await self.table.update(
where={"snippet_id": snippet_id},
data={"snippet_content": snippet_content},
)

View file

@ -45,13 +45,17 @@ class ErrorHandler(commands.Cog):
bot.tree.error(self.dispatch_to_app_command_handler)
async def dispatch_to_app_command_handler(
self, interaction: discord.Interaction, error: app_commands.AppCommandError
self,
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
"""Dispatch command error to appropriate handler."""
await self.handle_app_command_error(interaction, error)
async def handle_app_command_error(
self, interaction: discord.Interaction, error: app_commands.AppCommandError
self,
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
"""Handle errors for app commands."""
error_message = error_map.get(type(error), self.error_message).format(error=error)
@ -65,7 +69,11 @@ class ErrorHandler(commands.Cog):
self.log_error_traceback(error)
@commands.Cog.listener()
async def on_command_error(self, ctx: commands.Context[commands.Bot], error: commands.CommandError) -> None:
async def on_command_error(
self,
ctx: commands.Context[commands.Bot],
error: commands.CommandError,
) -> None:
"""Handle errors for traditional commands."""
if (
hasattr(ctx.command, "on_error")
@ -85,7 +93,11 @@ class ErrorHandler(commands.Cog):
if type(error) not in error_map:
self.log_error_traceback(error)
def get_error_message(self, error: Exception, ctx: commands.Context[commands.Bot] | None = None) -> str:
def get_error_message(
self,
error: Exception,
ctx: commands.Context[commands.Bot] | None = None,
) -> str:
"""Generate an error message from the error map."""
if ctx:
return error_map.get(type(error), self.error_message).format(error=error, ctx=ctx)

View file

@ -28,7 +28,7 @@ class EventHandler(commands.Cog):
stripped_content = strip_formatting(message.content)
if is_harmful(stripped_content):
await message.reply(
"Warning: This command is potentially harmful. Please avoid running it unless you are fully aware of it's operation. If this was a mistake, please disregard this message."
"Warning: This command is potentially harmful. Please avoid running it unless you are fully aware of it's operation. If this was a mistake, please disregard this message.",
)

View file

@ -20,13 +20,14 @@ class GitHubService:
CONST.GITHUB_INSTALLATION_ID,
CONST.GITHUB_CLIENT_ID,
CONST.GITHUB_CLIENT_SECRET,
)
),
)
async def get_repo(self) -> FullRepository:
try:
response: Response[FullRepository] = await self.github.rest.repos.async_get(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
)
repo: FullRepository = response.parsed_data
@ -41,7 +42,10 @@ class GitHubService:
async def create_issue(self, title: str, body: str) -> Issue:
try:
response: Response[Issue] = await self.github.rest.issues.async_create(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO, title=title, body=body
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
title=title,
body=body,
)
created_issue = response.parsed_data
@ -56,7 +60,10 @@ class GitHubService:
async def create_issue_comment(self, issue_number: int, body: str) -> IssueComment:
try:
response: Response[IssueComment] = await self.github.rest.issues.async_create_comment(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO, issue_number, body=body
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
issue_number,
body=body,
)
created_issue_comment = response.parsed_data
@ -71,7 +78,10 @@ class GitHubService:
async def close_issue(self, issue_number: int) -> Issue:
try:
response: Response[Issue] = await self.github.rest.issues.async_update(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO, issue_number, state="closed"
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
issue_number,
state="closed",
)
closed_issue = response.parsed_data
@ -86,7 +96,9 @@ class GitHubService:
async def get_issue(self, issue_number: int) -> Issue:
try:
response: Response[Issue] = await self.github.rest.issues.async_get(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO, issue_number
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
issue_number,
)
issue = response.parsed_data
@ -101,7 +113,9 @@ class GitHubService:
async def get_open_issues(self) -> list[Issue]:
try:
response: Response[list[Issue]] = await self.github.rest.issues.async_list_for_repo(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO, state="open"
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
state="open",
)
open_issues = response.parsed_data
@ -116,7 +130,9 @@ class GitHubService:
async def get_closed_issues(self) -> list[Issue]:
try:
response: Response[list[Issue]] = await self.github.rest.issues.async_list_for_repo(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO, state="closed"
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
state="closed",
)
closed_issues = response.parsed_data
@ -131,7 +147,9 @@ class GitHubService:
async def get_open_pulls(self) -> list[PullRequestSimple]:
try:
response: Response[list[PullRequestSimple]] = await self.github.rest.pulls.async_list(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO, state="open"
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
state="open",
)
open_pulls = response.parsed_data
@ -146,7 +164,9 @@ class GitHubService:
async def get_closed_pulls(self) -> list[PullRequestSimple]:
try:
response: Response[list[PullRequestSimple]] = await self.github.rest.pulls.async_list(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO, state="closed"
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
state="closed",
)
closed_pulls = response.parsed_data
@ -161,7 +181,9 @@ class GitHubService:
async def get_pull(self, pr_number: int) -> PullRequest:
try:
response: Response[PullRequest] = await self.github.rest.pulls.async_get(
CONST.GITHUB_REPO_OWNER, CONST.GITHUB_REPO, pr_number
CONST.GITHUB_REPO_OWNER,
CONST.GITHUB_REPO,
pr_number,
)
pull = response.parsed_data

View file

@ -63,7 +63,11 @@ class Comic:
The date of the comic.
"""
try:
return datetime.date(int(xkcd_dict["year"]), int(xkcd_dict["month"]), int(xkcd_dict["day"]))
return datetime.date(
int(xkcd_dict["year"]),
int(xkcd_dict["month"]),
int(xkcd_dict["day"]),
)
except (KeyError, ValueError):
return None

View file

@ -12,29 +12,65 @@ class ActivityChanger:
def build_activity_list(self):
return [
discord.Activity(
type=discord.ActivityType.watching, name=f"{self.get_member_count()} members"
type=discord.ActivityType.watching,
name=f"{self.get_member_count()} members",
), # submitted by electron271
discord.Activity(type=discord.ActivityType.watching, name="All Things Linux"), # submitted by electron271
discord.Activity(type=discord.ActivityType.playing, name="with fire"), # submitted by electron271
discord.Activity(type=discord.ActivityType.watching, name="linux tech tips"), # submitted by electron271
discord.Activity(type=discord.ActivityType.listening, name="mpd"), # submitted by electron271
discord.Activity(
type=discord.ActivityType.watching, name="a vast field of grain"
type=discord.ActivityType.watching,
name="All Things Linux",
), # submitted by electron271
discord.Activity(
type=discord.ActivityType.playing,
name="with fire",
), # submitted by electron271
discord.Activity(
type=discord.ActivityType.watching,
name="linux tech tips",
), # submitted by electron271
discord.Activity(
type=discord.ActivityType.listening,
name="mpd",
), # submitted by electron271
discord.Activity(
type=discord.ActivityType.watching,
name="a vast field of grain",
), # submitted by electron271
discord.Activity(
type=discord.ActivityType.playing,
name="i am calling about your car's extended warranty",
), # submitted by electron271
discord.Activity(type=discord.ActivityType.playing, name="SuperTuxKart"), # submitted by electron271
discord.Activity(type=discord.ActivityType.playing, name="SuperTux 2"), # submitted by lilliana
discord.Activity(type=discord.ActivityType.watching, name="Gentoo compile..."), # submitted by electron271
discord.Activity(type=discord.ActivityType.watching, name="Brodie Robertson"), # submitted by electron271
discord.Streaming(
name="SuperTuxKart", url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"
discord.Activity(
type=discord.ActivityType.playing,
name="SuperTuxKart",
), # submitted by electron271
discord.Activity(
type=discord.ActivityType.playing,
name="SuperTux 2",
), # submitted by lilliana
discord.Activity(
type=discord.ActivityType.watching,
name="Gentoo compile...",
), # submitted by electron271
discord.Activity(
type=discord.ActivityType.watching,
name="Brodie Robertson",
), # submitted by electron271
discord.Streaming(
name="SuperTuxKart",
url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
), # submitted by electron271
discord.Activity(
type=discord.ActivityType.listening,
name="Terry Davis on YouTube",
), # submitted by kaizen
discord.Activity(
type=discord.ActivityType.playing,
name="with Puffy",
), # submitted by kaizen
discord.Activity(
type=discord.ActivityType.watching,
name="the stars",
), # submitted by electron271
discord.Activity(type=discord.ActivityType.listening, name="Terry Davis on YouTube"), # submitted by kaizen
discord.Activity(type=discord.ActivityType.playing, name="with Puffy"), # submitted by kaizen
discord.Activity(type=discord.ActivityType.watching, name="the stars"), # submitted by electron271
discord.Activity(
type=discord.ActivityType.playing,
name="To see who submitted these, check tux/utils/activities.py on the repo (/info tux)",

View file

@ -341,19 +341,23 @@ class Console:
await channel.send(embed=embed)
async def set_status(self, command: str) -> None:
status_type = await self.get_input("Status type (watching, listening, playing, streaming): ")
status_type = await self.get_input(
"Status type (watching, listening, playing, streaming): ",
)
status_message = await self.get_input("Status message: ")
if status_type == "streaming":
stream_url = await self.get_input("Stream URL: ")
await self.bot.change_presence(activity=discord.Streaming(name=status_message, url=stream_url))
await self.bot.change_presence(
activity=discord.Streaming(name=status_message, url=stream_url),
)
return
await self.bot.change_presence(
activity=discord.Activity(
type=getattr(discord.ActivityType, status_type),
name=status_message,
)
),
)
async def run_console(self) -> None:

View file

@ -41,7 +41,9 @@ class Constants:
GITHUB_CLIENT_SECRET = os.getenv("GITHUB_CLIENT_SECRET")
GITHUB_PUBLIC_KEY = os.getenv("GITHUB_PUBLIC_KEY")
GITHUB_INSTALLATION_ID: Final[int] = int(os.getenv("GITHUB_INSTALLATION_ID", 0))
GITHUB_PRIVATE_KEY: str = base64.b64decode(os.getenv("GITHUB_PRIVATE_KEY_BASE64", "")).decode("utf-8")
GITHUB_PRIVATE_KEY: str = base64.b64decode(os.getenv("GITHUB_PRIVATE_KEY_BASE64", "")).decode(
"utf-8",
)
# Mailcow constants
MAILCOW_API_KEY: Final[str] = os.getenv("MAILCOW_API_KEY", "")

View file

@ -10,14 +10,18 @@ from tux.utils.constants import Constants as CONST
class EmbedCreator:
@staticmethod
def get_timestamp(ctx: commands.Context[commands.Bot] | None, interaction: discord.Interaction | None) -> datetime:
def get_timestamp(
ctx: commands.Context[commands.Bot] | None,
interaction: discord.Interaction | None,
) -> datetime:
if ctx and ctx.message:
return ctx.message.created_at
return interaction.created_at if interaction else discord.utils.utcnow()
@staticmethod
def get_footer(
ctx: commands.Context[commands.Bot] | None, interaction: discord.Interaction | None
ctx: commands.Context[commands.Bot] | None,
interaction: discord.Interaction | None,
) -> tuple[str, str | None]:
user: discord.User | discord.Member | None = None
latency = None
@ -38,10 +42,7 @@ class EmbedCreator:
if ctx is None and interaction is None:
return ("tux@atl $ ", "https://i.imgur.com/4sblrd0.png") # noqa: RUF001
return (
"",
None,
)
return ("", None)
@staticmethod
def add_author(embed: discord.Embed, name: str, icon_url: str) -> None:

View file

@ -16,7 +16,11 @@ _flags = {
}
async def _define_headers(args: list[str], valid_flags: list[str], default: list[str] | None = None) -> list[str]:
async def _define_headers(
args: list[str],
valid_flags: list[str],
default: list[str] | None = None,
) -> list[str]:
"""
Define the headers for the CSV output file.
"""
@ -38,7 +42,9 @@ async def _define_headers(args: list[str], valid_flags: list[str], default: list
async def _create_encoded_string(
headers: list[str], rows: list[dict[str, str]], quoting: int = csv.QUOTE_ALL
headers: list[str],
rows: list[dict[str, str]],
quoting: int = csv.QUOTE_ALL,
) -> io.BytesIO:
"""
Create an encoded string from the retrieved data.
@ -50,7 +56,11 @@ async def _create_encoded_string(
return io.BytesIO(csvfile.getvalue().encode())
async def get_help_embed(valid_flags: list[str], title: str, data_description: str) -> discord.Embed:
async def get_help_embed(
valid_flags: list[str],
title: str,
data_description: str,
) -> discord.Embed:
"""
Create an embed with help information for exporting data.
"""
@ -77,7 +87,9 @@ async def get_ban_list_csv(
Export a list of banned users in CSV format.
"""
headers: list[str] = await _define_headers(
args, valid_flags, default=[_flags["user"], _flags["id"], _flags["reason"]]
args,
valid_flags,
default=[_flags["user"], _flags["id"], _flags["reason"]],
)
rows: list[dict[str, str]] = []

View file

@ -144,7 +144,10 @@ def compare_changes(before: dict[str, Any], after: dict[str, Any]) -> list[str]:
return [f"{key}: {before[key]} -> {after[key]}" for key in before if key in after and before[key] != after[key]]
def compare_guild_channel_changes(before: discord.abc.GuildChannel, after: discord.abc.GuildChannel) -> list[str]:
def compare_guild_channel_changes(
before: discord.abc.GuildChannel,
after: discord.abc.GuildChannel,
) -> list[str]:
"""
Compares the changes between two GuildChannel instances and returns a list of strings representing the changes.
@ -179,7 +182,10 @@ def compare_guild_channel_changes(before: discord.abc.GuildChannel, after: disco
]
def compare_member_changes(before: discord.Member | discord.User, after: discord.Member | discord.User) -> list[str]:
def compare_member_changes(
before: discord.Member | discord.User,
after: discord.Member | discord.User,
) -> list[str]:
"""
Compares changes between two Member instances and returns a list of strings representing the changes.

View file

@ -22,7 +22,14 @@ _LT = TypeVar("_LT", discord.Embed, str, covariant=True)
class InteractionListMenuView(discord.ui.View):
def __init__(self, user_id: int, listmenu: list[_LT], *, timeout: float = 180, ephemeral: bool = False):
def __init__(
self,
user_id: int,
listmenu: list[_LT],
*,
timeout: float = 180,
ephemeral: bool = False,
):
super().__init__(timeout=timeout)
self.user_id = user_id
self.listmenu = listmenu
@ -44,7 +51,11 @@ class InteractionListMenuView(discord.ui.View):
element = self.setup_by_current_index()
if isinstance(element, discord.Embed):
self.message = await response.send_message(embed=element, view=self, ephemeral=self.ephemeral)
self.message = await response.send_message(
embed=element,
view=self,
ephemeral=self.ephemeral,
)
else:
self.message = await response.send_message(element, view=self, ephemeral=self.ephemeral)