Skip to content

Commit

Permalink
Wrap up rewriting extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
hypergonial committed Jun 4, 2024
1 parent e5d4976 commit 3d7ec79
Show file tree
Hide file tree
Showing 10 changed files with 246 additions and 245 deletions.
7 changes: 5 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
[tool.ruff]
exclude = ["examples", "docs", "build"]
line-length = 120
target-version = "py312"

[tool.ruff.lint]
select = [
"E",
"F",
Expand All @@ -19,8 +23,7 @@ select = [
]
ignore = ["F405", "F403", "E501", "D203", "D205", "D213", "RUF001"]
fixable = ["I", "TCH", "D"]
line-length = 120
target-version = "py312"


[tool.mypy]
ignore_errors = true # I use pyright only because mypy dumb
Expand Down
44 changes: 2 additions & 42 deletions src/extensions/automod.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import datetime
import enum
import json
import logging
import re
import typing as t
Expand All @@ -11,7 +10,7 @@

import src.utils as utils
from src.etc import const
from src.etc.settings_static import default_automod_policies, notices
from src.etc.settings_static import notices
from src.models.client import SnedClient, SnedPlugin
from src.models.events import AutoModMessageFlagEvent
from src.utils import helpers
Expand Down Expand Up @@ -61,45 +60,6 @@ class AutoModState(enum.Enum):
PERMABAN = "permaban"


# TODO: Purge this cursed abomination
async def get_policies(guild: hikari.SnowflakeishOr[hikari.Guild]) -> dict[str, t.Any]:
"""Return auto-moderation policies for the specified guild.
Parameters
----------
guild : hikari.SnowflakeishOr[hikari.Guild]
The guild to get policies for.
Returns
-------
dict[str, t.Any]
The guild's auto-moderation policies.
"""
guild_id = hikari.Snowflake(guild)

records = await plugin.client.db_cache.get(table="mod_config", guild_id=guild_id)

policies = json.loads(records[0]["automod_policies"]) if records else default_automod_policies

for key in default_automod_policies:
if key not in policies:
policies[key] = default_automod_policies[key]

for nested_key in default_automod_policies[key]:
if nested_key not in policies[key]:
policies[key][nested_key] = default_automod_policies[key][nested_key]

invalid = []
for key in policies:
if key not in default_automod_policies:
invalid.append(key)

for key in invalid:
policies.pop(key)

return policies


def can_automod_punish(me: hikari.Member, offender: hikari.Member) -> bool:
"""Determine if automod can punish a member.
This checks all required permissions and if the member is a cool person or not.
Expand Down Expand Up @@ -628,7 +588,7 @@ async def scan_messages(event: hikari.GuildMessageCreateEvent | hikari.GuildMess
if not message.member or message.member.is_bot:
return

policies = await get_policies(message.guild_id)
policies = await plugin.client.mod.get_automod_policies(message.guild_id)

if isinstance(event, hikari.GuildMessageUpdateEvent):
all(
Expand Down
8 changes: 2 additions & 6 deletions src/extensions/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,11 +504,9 @@ async def calc(
@arc.slash_command("tictactoe", "Play tic tac toe with someone!")
async def tictactoe(
ctx: SnedContext,
user: arc.Option[hikari.User, arc.UserParams("The user to play tic tac toe with!")],
user: arc.Option[hikari.Member, arc.MemberParams("The user to play tic tac toe with!")],
size: arc.Option[int, arc.IntParams("The size of the board. Default is 3.", choices=[3, 4, 5])] = 3,
) -> None:
if not helpers.is_member(user):
return
assert ctx.member is not None

if user.id == ctx.author.id:
Expand Down Expand Up @@ -728,11 +726,9 @@ async def urban_lookup(ctx: SnedContext, word: arc.Option[str, arc.StrParams("Th
@arc.slash_command("avatar", "Displays a user's avatar for your viewing pleasure.")
async def avatar(
ctx: SnedContext,
user: arc.Option[hikari.User | None, arc.UserParams("The user to show the avatar for.")] = None,
user: arc.Option[hikari.Member | None, arc.MemberParams("The user to show the avatar for.")] = None,
show_global: arc.Option[bool, arc.BoolParams("To show the global avatar or not, if applicable.")] = False,
) -> None:
if user and not helpers.is_member(user):
return
member = user or ctx.member
assert member is not None

Expand Down
119 changes: 57 additions & 62 deletions src/extensions/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,21 +313,19 @@ async def edit(

assert ctx.interaction.app_permissions is not None

channel = ctx.app.cache.get_guild_channel(message.channel_id) or await ctx.app.rest.fetch_channel(
channel = ctx.client.cache.get_guild_channel(message.channel_id) or await ctx.client.rest.fetch_channel(
message.channel_id
)

if not helpers.includes_permissions(
ctx.interaction.app_permissions,
hikari.Permissions.SEND_MESSAGES | hikari.Permissions.VIEW_CHANNEL | hikari.Permissions.READ_MESSAGE_HISTORY,
):
raise lightbulb.BotMissingRequiredPermission(
perms=hikari.Permissions.SEND_MESSAGES
| hikari.Permissions.VIEW_CHANNEL
| hikari.Permissions.READ_MESSAGE_HISTORY
raise arc.BotMissingPermissionsError(
hikari.Permissions.SEND_MESSAGES | hikari.Permissions.VIEW_CHANNEL | hikari.Permissions.READ_MESSAGE_HISTORY
)

if message.author.id != ctx.app.user_id:
if message.author.id != ctx.client.user_id:
await ctx.respond(
embed=hikari.Embed(
title="❌ Not Authored",
Expand All @@ -349,7 +347,8 @@ async def edit(
max_length=2000,
)
)
await modal.send(ctx.interaction)
await ctx.respond_with_builder(modal.build_response(ctx.client.miru))
ctx.client.miru.start_modal(modal)
await modal.wait()
if not modal.last_context:
return
Expand All @@ -362,18 +361,16 @@ async def edit(
)


@plugin.command
@lightbulb.app_command_permissions(None, dm_enabled=False)
@lightbulb.add_checks(
bot_has_permissions(
@plugin.include
@arc.with_hook(
arc.bot_has_permissions(
hikari.Permissions.SEND_MESSAGES | hikari.Permissions.VIEW_CHANNEL | hikari.Permissions.READ_MESSAGE_HISTORY
)
)
@lightbulb.command("Raw Content", "Show raw content for this message.", pass_options=True)
@lightbulb.implements(lightbulb.MessageCommand)
async def raw(ctx: SnedMessageContext, target: hikari.Message) -> None:
if target.content:
await ctx.respond(f"```{target.content[:1990]}```", flags=hikari.MessageFlag.EPHEMERAL)
@arc.message_command("Raw Content")
async def raw(ctx: SnedContext, message: hikari.Message) -> None:
if message.content:
await ctx.respond(f"```{message.content[:1990]}```", flags=hikari.MessageFlag.EPHEMERAL)
else:
await ctx.respond(
embed=hikari.Embed(
Expand All @@ -385,14 +382,21 @@ async def raw(ctx: SnedMessageContext, target: hikari.Message) -> None:
)


@plugin.command
@lightbulb.app_command_permissions(None, dm_enabled=False)
@lightbulb.option("timezone", "The timezone to set as your default. Example: 'Europe/Kiev'", autocomplete=True)
@lightbulb.command(
"timezone", "Sets your preferred timezone for other time-related commands to use.", pass_options=True
)
@lightbulb.implements(lightbulb.SlashCommand)
async def set_timezone(ctx: SnedSlashContext, timezone: str) -> None:
async def tz_autocomplete(data: arc.AutocompleteData[SnedClient, str]) -> list[str]:
if data.focused_value:
return get_close_matches(data.focused_value.title(), pytz.common_timezones, 25)
return []


@plugin.include
@arc.slash_command("timezone", "Sets your preferred timezone for other time-related commands to use.")
async def set_timezone(
ctx: SnedContext,
timezone: arc.Option[
str,
arc.StrParams("The timezone to set as your default. Example: 'Europe/Kiev'", autocomplete_with=tz_autocomplete),
],
) -> None:
if timezone.title() not in pytz.common_timezones:
await ctx.respond(
embed=hikari.Embed(
Expand All @@ -404,16 +408,16 @@ async def set_timezone(ctx: SnedSlashContext, timezone: str) -> None:
)
return

await ctx.app.db.execute(
await ctx.client.db.execute(
"""
INSERT INTO preferences (user_id, timezone)
VALUES ($1, $2)
ON CONFLICT (user_id) DO
UPDATE SET timezone = $2""",
INSERT INTO preferences (user_id, timezone)
VALUES ($1, $2)
ON CONFLICT (user_id) DO
UPDATE SET timezone = $2""",
ctx.user.id,
timezone.title(),
)
await ctx.app.db_cache.refresh(table="preferences", user_id=ctx.user.id, timezone=timezone.title())
await ctx.client.db_cache.refresh(table="preferences", user_id=ctx.user.id, timezone=timezone.title())

await ctx.respond(
embed=hikari.Embed(
Expand All @@ -425,40 +429,31 @@ async def set_timezone(ctx: SnedSlashContext, timezone: str) -> None:
)


@set_timezone.autocomplete("timezone")
async def tz_opts(
option: hikari.AutocompleteInteractionOption, interaction: hikari.AutocompleteInteraction
) -> list[str]:
if option.value:
assert isinstance(option.value, str)
return get_close_matches(option.value.title(), pytz.common_timezones, 25)
return []


@plugin.command
@lightbulb.app_command_permissions(None, dm_enabled=False)
@lightbulb.option(
"style",
"Timestamp style.",
choices=[
"t - Short time",
"T - Long time",
"d - Short date",
"D - Long Date",
"f - Short Datetime",
"F - Long Datetime",
"R - Relative",
@plugin.include
@arc.slash_command("timestamp", "Create a Discord timestamp from human-readable time formats and dates.")
async def timestamp_gen(
ctx: SnedContext,
time: arc.Option[
str, arc.StrParams("The time to create the timestamp from. Examples: 'in 20 minutes', '2022-04-03', '21:43'")
],
required=False,
)
@lightbulb.option("time", "The time to create the timestamp from. Examples: 'in 20 minutes', '2022-04-03', '21:43'")
@lightbulb.command(
"timestamp", "Create a Discord timestamp from human-readable time formats and dates.", pass_options=True
)
@lightbulb.implements(lightbulb.SlashCommand)
async def timestamp_gen(ctx: SnedSlashContext, time: str, style: str | None = None) -> None:
style: arc.Option[
str | None,
arc.StrParams(
"Timestamp style.",
choices=[
"t - Short time",
"T - Long time",
"d - Short date",
"D - Long Date",
"f - Short Datetime",
"F - Long Datetime",
"R - Relative",
],
),
] = None,
) -> None:
try:
converted_time = await ctx.app.scheduler.convert_time(
converted_time = await ctx.client.scheduler.convert_time(
time, conversion_mode=ConversionMode.ABSOLUTE, user=ctx.user
)
except ValueError as error:
Expand Down
Loading

0 comments on commit 3d7ec79

Please sign in to comment.