Skip to content

Commit

Permalink
Apply final cleanup (#223)
Browse files Browse the repository at this point in the history
  • Loading branch information
No767 authored Oct 28, 2024
1 parent 30c640f commit b883df1
Show file tree
Hide file tree
Showing 34 changed files with 438 additions and 488 deletions.
54 changes: 53 additions & 1 deletion .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,55 @@
# Contributing

See the [contributing guide](https://catherine-chan.readthedocs.io/en/latest/guides/dev/contributing.html) for more information.
Thank you for your interest in contributing to this project! Your effort really does make the project better.
You will need to read the setup instructions before you start working.

The following is a set of guidelines for contributing to the repository. These are not hard rules.

## I'm confused and want to ask questions!

Generally, there are much better resources that are available. These include:

- The official support server: https://discord.gg/ns3e74frqn
- FAQ in the documentation

Make sure to not ask questions in the issue tracker.

## Ways You Can Contribute

The ways you can contribute are not only limited to code changes, but so much more.
Some of the ways you can contribute are:

- Reporting a bug
- Discussing the current state and future of the project
- Submitting a fix
- Proposing new features
- Improving or editing documentation

Note that if you plan on proposing new features, please first discuss them with the owner and others on the issues page.

## Writing Good Bug Reports

Please be aware of the following when you submit a bug report:

1. Ask on the server first (this is preferred). If you are unsure about an issue, please contact the owner for clarification.
2. Don't open duplicate issues. Please search your issue to see if it has been asked already. Duplicate issues will be closed.
3. When filing a bug about exceptions or stacktrace, please include the complete stacktrace. Without the complete stacktrace the issue might be unsolvable and you will be asked to provide more information.

If a bug report is not clear enough, or missing these information, then more than likely
it'll take longer to fix the bug, or it'll be closed. More than likely clarification will
be asked in order to aid in this process.

## Submitting a Pull Request

This process is fairly straight forward, but make sure to focus your pull request on a single aspect doesn't manage to have scope creep and it's probably good to go.
Ideally the style needs to be consistent but this is fine if it is not met. This project follows PEP-8 guidelines, with an column limit of 88.

Ideally for new features, your pull request should also include unit tests. For more detail, please see the `bot/tests` directory.

## Git Commit Guidelines

1. Use present tense and imperative mood when writing commit messages. For example, `Add new feature` instead of `Added new feature`.
2. Reference issues or pull requests outside of the first line.
a. Please use the shorthand ``#123`` and not the full URL.

If these guidelines are not met, chances are they will be fixed during the review process.
4 changes: 3 additions & 1 deletion bot/catherinebot.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
async def main() -> None:
async with (
ClientSession() as session,
asyncpg.create_pool(dsn=POSTGRES_URI, min_size=25, max_size=25, command_timeout=60) as pool,
asyncpg.create_pool(
dsn=POSTGRES_URI, min_size=25, max_size=25, command_timeout=60
) as pool,
):
async with Catherine(
config=config,
Expand Down
4 changes: 3 additions & 1 deletion bot/catherinecore.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ async def remove_from_blacklist(self, object_id: int):
pass

# Basically silence all prefixed errors
async def on_command_error(self, ctx: commands.Context, error: commands.CommandError) -> None:
async def on_command_error(
self, ctx: commands.Context, error: commands.CommandError
) -> None:
return

async def setup_hook(self) -> None:
Expand Down
20 changes: 13 additions & 7 deletions bot/cogs/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ class BlacklistPageSource(menus.AsyncIteratorPageSource):
def __init__(self, entries: dict[str, Union[_T, Any]]):
super().__init__(self.blacklist_iterator(entries), per_page=20)

async def blacklist_iterator(self, entries: dict[str, Union[_T, Any]]) -> AsyncIterator[str]:
async def blacklist_iterator(
self, entries: dict[str, Union[_T, Any]]
) -> AsyncIterator[str]:
for key, entry in entries.items():
yield f"{key}: {entry}"

Expand Down Expand Up @@ -97,7 +99,9 @@ async def delete_response(self, interaction: discord.Interaction):
style=discord.ButtonStyle.green,
emoji="<:greenTick:596576670815879169>",
)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
async def confirm(
self, interaction: discord.Interaction, button: discord.ui.Button
) -> None:
self.value = True
if self.delete_after:
await self.delete_response(interaction)
Expand All @@ -107,7 +111,9 @@ async def confirm(self, interaction: discord.Interaction, button: discord.ui.But
style=discord.ButtonStyle.red,
emoji="<:redTick:596576672149667840>",
)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
async def cancel(
self, interaction: discord.Interaction, button: discord.ui.Button
) -> None:
self.value = False
await self.delete_response(interaction)

Expand Down Expand Up @@ -166,9 +172,7 @@ def tick(self, opt: Optional[bool], label: Optional[str] = None) -> str:
return emoji

def format_results(self, statuses: List) -> str:
desc = (
"\U00002705 - Successful reload | \U0000274c - Failed reload | \U000023e9 - Skipped\n\n"
)
desc = "\U00002705 - Successful reload | \U0000274c - Failed reload | \U000023e9 - Skipped\n\n"
status = "\n".join(f"- {status}: `{module}`" for status, module in statuses)
desc += status
return desc
Expand Down Expand Up @@ -266,7 +270,9 @@ async def reload(self, ctx: commands.Context) -> None:
mods_text = "\n".join(
f"{index}. `{module}`" for index, (_, module) in enumerate(modules, start=1)
)
prompt_text = f"This will update the following modules, are you sure?\n{mods_text}"
prompt_text = (
f"This will update the following modules, are you sure?\n{mods_text}"
)

confirm = await self.prompt(ctx, prompt_text)
if not confirm:
Expand Down
71 changes: 53 additions & 18 deletions bot/cogs/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ class InclusiveInfo(msgspec.Struct, frozen=True):

### UI components (Page Sources, Pages)
class TermSource(menus.ListPageSource):
def __init__(self, entries: list[dict[str, Any]], *, bot: Catherine, per_page: int = 1):
def __init__(
self, entries: list[dict[str, Any]], *, bot: Catherine, per_page: int = 1
):
super().__init__(entries=entries, per_page=per_page)
self.cog: Dictionary = bot.get_cog("dictionary") # type: ignore

Expand All @@ -72,7 +74,9 @@ async def format_page(self, menu: "TermsPages", entries: dict[str, Any]) -> Embe

menu.embed.title = entry.term
menu.embed.set_thumbnail(url=self.cog.determine_image_url(entries))
menu.embed.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}")
menu.embed.set_footer(
text=f"Page {menu.current_page + 1}/{self.get_max_pages()}"
)

menu.embed.description = f"{entry.original}\n\n{entry.definition}"

Expand All @@ -84,7 +88,9 @@ async def format_page(self, menu: "TermsPages", entries: dict[str, Any]) -> Embe


class TermsPages(CatherinePages):
def __init__(self, entries: list[dict[str, Any]], *, interaction: discord.Interaction):
def __init__(
self, entries: list[dict[str, Any]], *, interaction: discord.Interaction
):
self.bot: Catherine = interaction.client # type: ignore
self.entries = entries
super().__init__(
Expand All @@ -111,8 +117,12 @@ def _fmt_prefix(value: str) -> str:
return value

return NounInfo(
masc="\n".join(map(_fmt_prefix, f"{entries['masc']}|{entries['mascPl']}".split("|"))),
fem="\n".join(map(_fmt_prefix, f"{entries['fem']}|{entries['femPl']}".split("|"))),
masc="\n".join(
map(_fmt_prefix, f"{entries['masc']}|{entries['mascPl']}".split("|"))
),
fem="\n".join(
map(_fmt_prefix, f"{entries['fem']}|{entries['femPl']}".split("|"))
),
neutral="\n".join(
map(_fmt_prefix, f"{entries['neutr']}|{entries['neutrPl']}".split("|"))
),
Expand All @@ -134,14 +144,20 @@ async def format_page(self, menu: "TermsPages", entries: dict[str, Any]):


class NounPages(CatherinePages):
def __init__(self, entries: list[dict[str, Any]], *, interaction: discord.Interaction):
def __init__(
self, entries: list[dict[str, Any]], *, interaction: discord.Interaction
):
self.bot: Catherine = interaction.client # type: ignore
super().__init__(source=NounSource(entries, per_page=1), interaction=interaction)
super().__init__(
source=NounSource(entries, per_page=1), interaction=interaction
)
self.embed = Embed()


class InclusiveSource(menus.ListPageSource):
def __init__(self, entries: list[dict[str, Any]], *, bot: Catherine, per_page: int = 1):
def __init__(
self, entries: list[dict[str, Any]], *, bot: Catherine, per_page: int = 1
):
super().__init__(entries=entries, per_page=per_page)
self.cog: Dictionary = bot.get_cog("dictionary") # type: ignore

Expand All @@ -150,7 +166,9 @@ def format_info(self, entries: dict[str, Any]) -> InclusiveInfo:
instead_of="\n".join(
map(lambda value: f"- ~~{value}~~", entries["insteadOf"].split("|"))
),
say="\n".join(map(lambda value: f"- **{value}**", entries["say"].split("|"))),
say="\n".join(
map(lambda value: f"- **{value}**", entries["say"].split("|"))
),
because=entries["because"],
clarification=entries["clarification"],
author=self.cog.determine_author(entries["author"]),
Expand All @@ -169,17 +187,22 @@ async def format_page(self, menu: "InclusivePages", entries: dict[str, Any]):
if entry.clarification:
menu.embed.description += f"### Clarification\n{entry.clarification}"

menu.embed.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}")
menu.embed.set_footer(
text=f"Page {menu.current_page + 1}/{self.get_max_pages()}"
)

menu.embed.add_field(name="Author", value=entry.author)
return menu.embed


class InclusivePages(CatherinePages):
def __init__(self, entries: list[dict[str, Any]], *, interaction: discord.Interaction):
def __init__(
self, entries: list[dict[str, Any]], *, interaction: discord.Interaction
):
self.bot: Catherine = interaction.client # type: ignore
super().__init__(
source=InclusiveSource(entries, bot=self.bot, per_page=1), interaction=interaction
source=InclusiveSource(entries, bot=self.bot, per_page=1),
interaction=interaction,
)
self.embed = Embed()

Expand Down Expand Up @@ -249,11 +272,15 @@ def format_inline_term_reference(self, content: str, entities: list[str]):
# Since we are only using english for now, this doesn't matter
pronouns_parts = entity[1:].partition("=")
pronouns_url = URL.build(
scheme="https", host="en.pronouns.page", path=f"/{pronouns_parts[0]}"
scheme="https",
host="en.pronouns.page",
path=f"/{pronouns_parts[0]}",
)
replacements.update({entity: f"[{pronouns_parts[-1]}]({pronouns_url})"})
else:
replacements.update({entity: f"[{entity}]({url.with_query({'filter': entity})})"})
replacements.update(
{entity: f"[{entity}]({url.with_query({'filter': entity})})"}
)

fmt_regex = re.compile(r"(%s)" % "|".join(map(re.escape, replacements.keys())))
return fmt_regex.sub(lambda mo: replacements[mo.group()], cleaned_content)
Expand All @@ -262,7 +289,9 @@ def extract_reference(self, content: str) -> list[str]:
return re.findall(r"{(.*?)}", content)

def format_references(self, content: str) -> str:
return self.format_inline_term_reference(content, self.extract_reference(content))
return self.format_inline_term_reference(
content, self.extract_reference(content)
)

### General utilities

Expand All @@ -274,7 +303,9 @@ def determine_author(self, author: Optional[str]) -> str:

@app_commands.command(name="terms")
@app_commands.describe(query="The term to look for")
async def terms(self, interaction: discord.Interaction, query: Optional[str] = None) -> None:
async def terms(
self, interaction: discord.Interaction, query: Optional[str] = None
) -> None:
"""Looks up LGBTQ+ terms up"""
await interaction.response.defer()
url = URL("https://en.pronouns.page/api/terms")
Expand All @@ -290,7 +321,9 @@ async def terms(self, interaction: discord.Interaction, query: Optional[str] = N

@app_commands.command(name="nouns")
@app_commands.describe(query="The noun to look for")
async def nouns(self, interaction: discord.Interaction, query: Optional[str] = None) -> None:
async def nouns(
self, interaction: discord.Interaction, query: Optional[str] = None
) -> None:
"""Looks up gender neutral nouns and language"""
url = URL("https://en.pronouns.page/api/nouns")
if query:
Expand All @@ -313,7 +346,9 @@ async def nouns(self, interaction: discord.Interaction, query: Optional[str] = N

@app_commands.command(name="inclusive")
@app_commands.describe(term="The inclusive term to look for")
async def inclusive(self, interaction: discord.Interaction, term: Optional[str] = None) -> None:
async def inclusive(
self, interaction: discord.Interaction, term: Optional[str] = None
) -> None:
"""Provides inclusive terms for users to learn about"""
await interaction.response.defer()
url = URL("https://en.pronouns.page/api/inclusive")
Expand Down
12 changes: 9 additions & 3 deletions bot/cogs/ext/prometheus.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ class GuildCollector:
def __init__(self, bot: Catherine):
self.bot = bot
self.count = Gauge(f"{METRIC_PREFIX}guilds", "Amount of guilds connected")
self.text = Gauge(f"{METRIC_PREFIX}text", "Amount of text channels that can be seen")
self.text = Gauge(
f"{METRIC_PREFIX}text", "Amount of text channels that can be seen"
)
self.voice = Gauge(f"{METRIC_PREFIX}voice", "Amount of voice channels")
self.users = Gauge(f"{METRIC_PREFIX}users", "Total users")

Expand Down Expand Up @@ -78,7 +80,9 @@ def __init__(self, bot: Catherine):

# For now, until we can improve the blacklist system,
# we will leave these to be blank
self.users = Gauge(f"{METRIC_PREFIX}blacklist_users", "Current amount of blacklisted users")
self.users = Gauge(
f"{METRIC_PREFIX}blacklist_users", "Current amount of blacklisted users"
)
self.commands = Counter(
f"{METRIC_PREFIX}blacklist_commands",
"Counter of commands that were attempted for blacklisted users",
Expand Down Expand Up @@ -110,7 +114,9 @@ class CommandsCollector:
def __init__(self, bot: Catherine):
self.bot = bot

self.total = Summary(f"{METRIC_PREFIX}commands_total", "Total commands included")
self.total = Summary(
f"{METRIC_PREFIX}commands_total", "Total commands included"
)
self.invocation = Counter(
f"{METRIC_PREFIX}commands_invocation", "Counter for invoked commands"
)
Expand Down
4 changes: 3 additions & 1 deletion bot/cogs/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ async def ship(

@app_commands.command(name="who-would-win")
@app_commands.describe(user="The user to place your bets against")
async def who_would_win(self, interaction: discord.Interaction, user: discord.Member) -> None:
async def who_would_win(
self, interaction: discord.Interaction, user: discord.Member
) -> None:
"""Who would win template with friends!"""
params = {
"image1": interaction.user.display_avatar.url,
Expand Down
8 changes: 6 additions & 2 deletions bot/cogs/hrt.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,9 @@ async def estradiol(
Choice(name="ng/dL", value="ng_dl"),
]
)
async def testosterone(self, interaction: discord.Interaction, amount: int, units: Choice[str]):
async def testosterone(
self, interaction: discord.Interaction, amount: int, units: Choice[str]
):
"""Converts one unit of testosterone to another unit"""
res = self.calc_testosterone(amount, units.value)

Expand Down Expand Up @@ -186,7 +188,9 @@ async def progesterone(
@app_commands.choices(
units=[Choice(name="mIU/L", value="miu_l"), Choice(name="ng/mL", value="ng_ml")]
)
async def prolactin(self, interaction: discord.Interaction, amount: int, units: Choice[str]):
async def prolactin(
self, interaction: discord.Interaction, amount: int, units: Choice[str]
):
"""Converts one unit of prolactin to another unit"""
res = self.calc_prolactin(amount, units.value)

Expand Down
Loading

0 comments on commit b883df1

Please sign in to comment.