Skip to content

Commit

Permalink
massive cleanup effort
Browse files Browse the repository at this point in the history
  • Loading branch information
haliphax committed Nov 8, 2023
1 parent c21a7a3 commit b4500a9
Show file tree
Hide file tree
Showing 25 changed files with 488 additions and 252 deletions.
5 changes: 4 additions & 1 deletion aethersprite/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ def invoked_with(self):
def get_prefixes(bot: Bot, message: Message):
from .settings import settings

assert bot.user
user_id = bot.user.id
base = [f"<@!{user_id}> ", f"<@{user_id}> "]
default = [config.get("bot", {}).get("prefix", "!")]
Expand Down Expand Up @@ -149,17 +150,19 @@ async def on_command_error(ctx: Context, error: Exception):
return

bot: Bot = ctx.bot
cog: Alias | None = bot.get_cog("Alias")
cog: Alias | None = bot.get_cog("Alias") # type: ignore

if cog is None:
return

assert ctx.guild
guild = str(ctx.guild.id)
aliases = cog.aliases[guild] if guild in cog.aliases else None

if aliases is None:
return

assert ctx.prefix
name = ctx.message.content.replace(ctx.prefix, "").split(" ")[0].strip()

if name not in aliases:
Expand Down
12 changes: 9 additions & 3 deletions aethersprite/authz.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ async def react_if_not_help(ctx: Context):
if ctx.invoked_with not in help_aliases:
await ctx.message.add_reaction(POLICE_OFFICER)
log.warn(
f"{ctx.author} attempted to access unauthorized command " f"{ctx.command}"
f"{ctx.author} attempted to access unauthorized command "
f"{ctx.command}"
)

return
Expand All @@ -73,6 +74,7 @@ async def react_if_not_help(ctx: Context):
async def require_admin(ctx: Context):
"""Check for requiring admin/mod privileges to execute a command."""

assert isinstance(ctx.author, Member)
perms = ctx.channel.permissions_for(ctx.author)

if (
Expand All @@ -83,7 +85,7 @@ async def require_admin(ctx: Context):
):
return True

await react_if_not_help()
await react_if_not_help(ctx)

return False

Expand All @@ -97,6 +99,8 @@ async def require_roles(ctx: Context, roles: Sequence[Role]) -> bool:
:param roles: The roles to authorize
"""

assert isinstance(ctx.author, Member)

if is_in_any_role(ctx.author, roles):
return True

Expand All @@ -106,7 +110,7 @@ async def require_roles(ctx: Context, roles: Sequence[Role]) -> bool:


async def require_roles_from_setting(
ctx: Context, setting: Union[str, Sequence], open_by_default=True
ctx: Context, setting: str | Sequence, open_by_default=True
) -> bool:
"""
Check for requiring particular roles (loaded from the given setting) to
Expand Down Expand Up @@ -147,6 +151,8 @@ async def my_other_command(ctx):
:type setting: str or list or tuple
"""

assert isinstance(ctx.author, Member)

perms = ctx.channel.permissions_for(ctx.author)

if (
Expand Down
50 changes: 29 additions & 21 deletions aethersprite/common.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
"Common functions module"
"""Common functions module"""

# typing
from typing import Any

# 3rd party
from discord.ext.commands import Context

# stdlib
from collections import namedtuple
from datetime import datetime, timezone
Expand All @@ -11,23 +15,27 @@
from typing import Callable, Tuple

# constants
#: One minute in seconds
MINUTE = 60
#: One hour in seconds
"""One minute in seconds"""

HOUR = MINUTE * 60
#: One day in seconds
"""One hour in seconds"""

DAY = HOUR * 24
#: 15 minutes in seconds
"""One day in seconds"""

FIFTEEN_MINS = MINUTE * 15
#: Formatting string for datetime objects
DATETIME_FORMAT = '%a %Y-%m-%d %H:%M:%S %Z'
"""15 minutes in seconds"""

DATETIME_FORMAT = "%a %Y-%m-%d %H:%M:%S %Z"
"""Formatting string for datetime objects"""

# structs
#: Fake a context for use in certain functions that expect one
FakeContext = namedtuple('FakeContext', ('guild',))
FakeContext = namedtuple("FakeContext", ("guild",))
"""Fake a context for use in certain functions that expect one"""


def get_channel_for_id(guild, id: int) -> str:
def get_channel_for_id(guild, id: int) -> str | None:
"""
Return channel name for given guild and channel ID.
Expand All @@ -41,7 +49,7 @@ def get_channel_for_id(guild, id: int) -> str:
return chans[0] if len(chans) else None


def get_id_for_channel(guild, channel: str) -> int:
def get_id_for_channel(guild, channel: str) -> int | None:
"""
Return channel ID for given guild and channel name.
Expand All @@ -56,7 +64,7 @@ def get_id_for_channel(guild, channel: str) -> int:
return ids[0] if len(ids) else None


def get_mixed_channels(value: str) -> Tuple[Tuple[str, str]]:
def get_mixed_channels(value: str) -> list[Any]:
"""
Return a series of group pairs matched from the provided value. The first
element in each pair will be the channel ID if the match was a mention;
Expand All @@ -67,10 +75,10 @@ def get_mixed_channels(value: str) -> Tuple[Tuple[str, str]]:
:returns: A series of group pairs (channel ID, channel text)
"""

return re.findall(r'<#(\d+)> ?|([-_a-zA-Z0-9]+)[, ]*', value.strip())
return re.findall(r"<#(\d+)> ?|([-_a-zA-Z0-9]+)[, ]*", value.strip())


def get_id_for_role(guild, role: str) -> int:
def get_id_for_role(guild, role: str) -> int | None:
"""
Return role ID for given guild and role name.
Expand All @@ -85,7 +93,7 @@ def get_id_for_role(guild, role: str) -> int:
return ids[0] if len(ids) else None


def get_role_for_id(guild, id: int) -> str:
def get_role_for_id(guild, id: int) -> str | None:
"""
Return role name for given guild and role ID.
Expand All @@ -99,7 +107,7 @@ def get_role_for_id(guild, id: int) -> str:
return roles[0] if len(roles) else None


def get_mixed_roles(value: str) -> Tuple[Tuple[str, str]]:
def get_mixed_roles(value: str) -> list[Any]:
"""
Return a series of group pairs matched from the provided value. The first
element in each pair will be the role ID if the match was a mention;
Expand All @@ -110,7 +118,7 @@ def get_mixed_roles(value: str) -> Tuple[Tuple[str, str]]:
:returns: A series of group pairs (role ID, role text)
"""

return re.findall(r'<@&(\d+)> ?|([^,]+)[, ]*', value.strip())
return re.findall(r"<@&(\d+)> ?|([^,]+)[, ]*", value.strip())


def get_timespan_chunks(string: str):
Expand All @@ -122,11 +130,11 @@ def get_timespan_chunks(string: str):
:rtype: tuple
"""

s = re.search(r'.*?(-?\d+)d.*', string)
s = re.search(r".*?(-?\d+)d.*", string)
days = int(s.groups()[0]) if s else 0
s = re.search(r'.*?(-?\d+)h.*', string)
s = re.search(r".*?(-?\d+)h.*", string)
hours = int(s.groups()[0]) if s else 0
s = re.search(r'.*?(-?\d+)m.*', string)
s = re.search(r".*?(-?\d+)m.*", string)
minutes = int(s.groups()[0]) if s else 0

return (days, hours, minutes)
Expand Down Expand Up @@ -164,4 +172,4 @@ def seconds_to_str(ts):
if seconds > 0:
until.append(f'{seconds} second{"s" if seconds > 1 else ""}')

return ', '.join(until)
return ", ".join(until)
1 change: 1 addition & 0 deletions aethersprite/extensions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Aethersprite extensions"""
2 changes: 1 addition & 1 deletion aethersprite/extensions/base/_all.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Load all command extensions"""
"""Load all extensions"""

# 3rd party
from discord.ext.commands import Bot
Expand Down
37 changes: 23 additions & 14 deletions aethersprite/extensions/base/alias.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
"Alias cog"
"""Alias cog"""

# 3rd party
from discord.ext.commands import Bot, command, Cog
from discord.ext.commands import Bot, Cog, command, Context
from sqlitedict import SqliteDict

# local
from aethersprite import data_folder, log
from aethersprite.authz import channel_only, require_admin

#: Aliases database
aliases = SqliteDict(
f"{data_folder}alias.sqlite3", tablename="aliases", autocommit=True
)
"""Aliases database"""

bot: Bot


class Alias(Cog):
"Alias commands; add and remove command aliases"
"""Alias commands; add and remove command aliases"""

@staticmethod
def get_aliases(ctx, cmd):
"Get aliases for the given command and context."
def get_aliases(ctx: Context, cmd: str):
"""Get aliases for the given command and context."""

assert ctx.guild
mylist = list()
guild = str(ctx.guild.id)

Expand All @@ -40,9 +43,10 @@ def __init__(self, bot):
self.aliases = aliases

@command(name="alias.add")
async def add(self, ctx, alias: str, command: str):
"Add an alias of <alias> for <command>"
async def add(self, ctx: Context, alias: str, command: str):
"""Add an alias of <alias> for <command>"""

assert ctx.guild
guild = str(ctx.guild.id)

if ctx.guild.id not in aliases:
Expand All @@ -55,7 +59,7 @@ async def add(self, ctx, alias: str, command: str):

return

cmd = ctx.bot.get_command(command)
cmd = bot.get_command(command)

if cmd is None:
await ctx.send(f":scream: No such command!")
Expand All @@ -68,9 +72,10 @@ async def add(self, ctx, alias: str, command: str):
await ctx.send(f":sunglasses: Done.")

@command(name="alias.remove")
async def remove(self, ctx, alias: str):
"Remove <alias>"
async def remove(self, ctx: Context, alias: str):
"""Remove <alias>"""

assert ctx.guild
guild = str(ctx.guild.id)
als = aliases[guild] if guild in aliases else None

Expand All @@ -90,9 +95,10 @@ async def remove(self, ctx, alias: str):
await ctx.send(":wastebasket: Removed.")

@command(name="alias.list")
async def list(self, ctx):
"List all command aliases"
async def list(self, ctx: Context):
"""List all command aliases"""

assert ctx.guild
guild = str(ctx.guild.id)

if guild not in aliases:
Expand All @@ -108,7 +114,10 @@ async def list(self, ctx):
await ctx.send(f":detective: **{output}**")


async def setup(bot: Bot):
async def setup(bot_: Bot):
global bot

bot = bot_
cog = Alias(bot)

for c in cog.get_commands():
Expand Down
6 changes: 4 additions & 2 deletions aethersprite/extensions/base/badnames.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"Badnames extension; automatically kick users whose names match a blacklist."
"""
Badnames extension; automatically kick users whose names match a blacklist.
"""

# local
from aethersprite import log
Expand All @@ -10,7 +12,7 @@


async def on_member_join(member: Member):
"Check member names against blacklist on join."
"""Check member names against blacklist on join."""

badnames_setting: str = settings["badnames"].get(member)

Expand Down
10 changes: 6 additions & 4 deletions aethersprite/extensions/base/github.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
"GitHub URL command"
"""GitHub URL command"""

# 3rd party
from discord.ext.commands import Bot, command
from discord.ext.commands import Bot, command, Context

# local
from aethersprite import log


@command(brief="GitHub URL for bot source code, feature requests", pass_context=True)
async def github(ctx):
@command(
brief="GitHub URL for bot source code, feature requests", pass_context=True
)
async def github(ctx: Context):
"""
This bot is running on Aethersprite, an open source bot software built with discord.py. My source code is available for free. Contributions in the form of code, bug reports, and feature requests are all welcome.
Expand Down
7 changes: 3 additions & 4 deletions aethersprite/extensions/base/gmt.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
"GMT time check and offset command"
"""GMT time check and offset command"""

# stdlib
from datetime import datetime, timedelta
import typing

# 3rd party
from discord.ext.commands import Bot, command, Context
Expand All @@ -25,7 +24,7 @@ async def _time(ctx: Context, tz: str, offset: str | None):


@command(brief="Get current time or offset in GMT")
async def gmt(ctx: Context, *, offset: typing.Optional[str]):
async def gmt(ctx: Context, *, offset: str | None = None):
"""
Get current time in GMT or offset by days, hours, and minutes.
Expand All @@ -40,7 +39,7 @@ async def gmt(ctx: Context, *, offset: typing.Optional[str]):


@command(brief="Get current time or offset in UTC")
async def utc(ctx: Context, *, offset: typing.Optional[str]):
async def utc(ctx: Context, *, offset: str | None = None):
"""
Get current time in UTC or offset by days, hours, and minutes.
Expand Down
Loading

0 comments on commit b4500a9

Please sign in to comment.