Skip to content

Commit

Permalink
Typing maintenance and modernization
Browse files Browse the repository at this point in the history
  • Loading branch information
EthanC committed Feb 26, 2024
1 parent e080c8b commit a6e9f68
Show file tree
Hide file tree
Showing 15 changed files with 228 additions and 241 deletions.
42 changes: 20 additions & 22 deletions components/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import sys
from datetime import datetime
from sys import exit
from typing import Any, Dict, List, Optional, Union
from typing import Any

import hikari
import tanjun
Expand Down Expand Up @@ -48,10 +48,10 @@
@tanjun.as_slash_command("unban", "Unban a user from the current server.")
async def CommandUnban(
ctx: SlashContext,
user: Union[InteractionMember, UserImpl],
user: InteractionMember | UserImpl,
reason: str,
client: Client = tanjun.inject(type=Client),
config: Dict[str, Any] = tanjun.inject(type=Dict[str, Any]),
config: dict[str, Any] = tanjun.inject(type=dict[str, Any]),
) -> None:
"""Handler for the /unban slash command."""

Expand Down Expand Up @@ -100,9 +100,7 @@ async def CommandUnban(
@tanjun.with_own_permission_check(Permissions.SEND_MESSAGES)
@tanjun.with_user_slash_option("user", "Enter a user to fetch the profile of.")
@tanjun.as_slash_command("profile", "Fetch detailed information about a Discord user.")
async def CommandProfile(
ctx: SlashContext, user: Union[InteractionMember, UserImpl]
) -> None:
async def CommandProfile(ctx: SlashContext, user: InteractionMember | UserImpl) -> None:
"""Handler for the /profile slash command."""

if hasattr(user, "user"):
Expand All @@ -113,9 +111,9 @@ async def CommandProfile(
f"Failed to fetch user {Responses.ExpandUser(user.id, False)}"
)

fields: List[Dict[str, Any]] = []
altAvatar: Optional[str] = None
accent: Optional[str] = None
fields: list[dict[str, Any]] = []
altAvatar: str | None = None
accent: str | None = None

if hasattr(user, "nickname"):
if (nickname := user.nickname) is not None:
Expand Down Expand Up @@ -188,11 +186,11 @@ async def CommandProfile(
)
@tanjun.as_slash_command("reboot", "Restart the active N31L instance.")
async def CommandReboot(
ctx: SlashContext, delay: Optional[int], state: State = tanjun.inject(type=State)
ctx: SlashContext, delay: int | None, state: State = tanjun.inject(type=State)
) -> None:
"""Handler for the /reboot slash command."""

started: Dict[str, Any] = {
started: dict[str, Any] = {
"name": "Instance Started",
"value": Timestamps.Relative(state.botStart),
}
Expand Down Expand Up @@ -240,9 +238,9 @@ async def CommandServer(ctx: SlashContext) -> None:
"""Handler for the /server slash command."""

server: Guild = await ctx.fetch_guild()
creators: Dict[int, int] = {136986169563938816: 132693143173857281}
creators: dict[int, int] = {136986169563938816: 132693143173857281}

fields: List[Dict[str, Any]] = []
fields: list[dict[str, Any]] = []

if hasattr(server, "created_at"):
if (created := server.created_at) is not None:
Expand Down Expand Up @@ -285,7 +283,7 @@ async def CommandStatus(
) -> None:
"""Handler for the /status slash command."""

stats: List[Dict[str, Any]] = []
stats: list[dict[str, Any]] = []

# Make a request to Discord to determine the REST latency
latStart: float = datetime.now().timestamp()
Expand Down Expand Up @@ -354,8 +352,8 @@ async def CommandStatus(
async def CommandSendDirectMessage(
ctx: SlashContext,
user: User,
content: Optional[str],
attachment: Optional[Attachment],
content: str | None,
attachment: Attachment | None,
) -> None:
"""Handler for the /send direct_message slash command."""

Expand Down Expand Up @@ -418,8 +416,8 @@ async def CommandSendDirectMessage(
async def CommandSendMessage(
ctx: SlashContext,
channel: InteractionChannel,
content: Optional[str],
attachment: Optional[Attachment],
content: str | None,
attachment: Attachment | None,
) -> None:
"""Handler for the /send message slash command."""

Expand Down Expand Up @@ -485,7 +483,7 @@ async def CommandSetActivity(
ctx: SlashContext,
type: int,
name: str,
url: Optional[str] = None,
url: str | None = None,
bot: GatewayBot = tanjun.inject(type=GatewayBot),
) -> None:
"""Handler for the /set activity slash command."""
Expand Down Expand Up @@ -516,10 +514,10 @@ async def CommandSetActivity(
"image", "Upload an image file or leave empty to use default avatar.", default=None
)
@tanjun.as_slash_command("avatar", "Set the avatar for N31L.")
async def CommandSetAvatar(ctx: SlashContext, image: Optional[Attachment]) -> None:
async def CommandSetAvatar(ctx: SlashContext, image: Attachment | None) -> None:
"""Handler for the /set avatar slash command."""

url: Optional[str] = None if image is None else image.url
url: str | None = None if image is None else image.url

try:
if image is not None:
Expand Down Expand Up @@ -571,7 +569,7 @@ async def CommandSetStatus(
) -> None:
"""Handler for the /set status slash command."""

color: Optional[str] = None
color: str | None = None

if type == Status.DO_NOT_DISTURB:
color = "ED4245"
Expand Down
7 changes: 3 additions & 4 deletions components/animals.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import asyncio
import random
from typing import List, Optional

import tanjun
from hikari import Permissions
Expand Down Expand Up @@ -28,7 +27,7 @@
)

component: Component = Component(name="Animals")
animalTypes: List[str] = [
animalTypes: list[str] = [
"Axolotl",
"Bingus",
"Bird",
Expand Down Expand Up @@ -59,13 +58,13 @@
default=None,
)
@tanjun.as_slash_command("animal", "Fetch a random picture of an animal.")
async def CommandAnimal(ctx: SlashContext, type: Optional[str]) -> None:
async def CommandAnimal(ctx: SlashContext, type: str | None) -> None:
"""Handler for the /animal command."""

if type is None:
type = random.choice(animalTypes)

result: Optional[Embed] = None
result: Embed | None = None
source: int = 1
retries: int = 0

Expand Down
7 changes: 3 additions & 4 deletions components/food.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import asyncio
import random
from typing import List, Optional

import tanjun
from hikari import Permissions
Expand All @@ -12,7 +11,7 @@
from services import Burger, Dessert, HotDog, Pasta, Pizza, Salad, Sandwich, Sushi, Taco

component: Component = Component(name="Food")
foodTypes: List[str] = [
foodTypes: list[str] = [
"Burger",
"Dessert",
"Hot Dog",
Expand All @@ -34,13 +33,13 @@
default=None,
)
@tanjun.as_slash_command("food", "Fetch a random picture of food.")
async def CommandFood(ctx: SlashContext, type: Optional[str]) -> None:
async def CommandFood(ctx: SlashContext, type: str | None) -> None:
"""Handler for the /food command."""

if type is None:
type = random.choice(foodTypes)

result: Optional[Embed] = None
result: Embed | None = None
source: int = 1
retries: int = 0

Expand Down
28 changes: 14 additions & 14 deletions components/logs.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from os import environ
from typing import Any, Dict, List, Optional
from typing import Any

import tanjun
from hikari.events.message_events import (
Expand All @@ -19,7 +19,7 @@
@component.with_listener(DMMessageCreateEvent)
async def EventDirectMessage(
ctx: DMMessageCreateEvent,
config: Dict[str, Any] = tanjun.inject(type=Dict[str, Any]),
config: dict[str, Any] = tanjun.inject(type=dict[str, Any]),
) -> None:
"""Handler for notifying of direct messages."""

Expand All @@ -28,13 +28,13 @@ async def EventDirectMessage(
elif int(ctx.author.id) == config["users"]["owner"]:
return

content: Optional[str] = None
content: str | None = None

if hasattr(ctx.message, "content"):
if ctx.message.content is not None:
content = f">>> {Utility.Trim(ctx.message.content, 4000)}"

payload: Dict[str, Any] = {
payload: dict[str, Any] = {
"username": "N31L",
"avatar_url": "https://i.imgur.com/cGtkGuI.png",
"embeds": [
Expand Down Expand Up @@ -76,7 +76,7 @@ async def EventDirectMessage(
@component.with_listener(GuildMessageCreateEvent)
async def EventKeyword(
ctx: GuildMessageCreateEvent,
config: Dict[str, Any] = tanjun.inject(type=Dict[str, Any]),
config: dict[str, Any] = tanjun.inject(type=dict[str, Any]),
) -> None:
"""Handler for notifying of keyword mentions."""

Expand All @@ -91,8 +91,8 @@ async def EventKeyword(
elif ctx.message.content is None:
return

words: List[str] = [word.lower() for word in ctx.message.content.split()]
found: List[str] = []
words: list[str] = [word.lower() for word in ctx.message.content.split()]
found: list[str] = []

for keyword in config["logging"]["keywords"]:
if keyword not in words:
Expand All @@ -103,7 +103,7 @@ async def EventKeyword(
if len(found) == 0:
return

payload: Dict[str, Any] = {
payload: dict[str, Any] = {
"username": "N31L",
"avatar_url": "https://i.imgur.com/cGtkGuI.png",
"embeds": [
Expand Down Expand Up @@ -160,7 +160,7 @@ async def EventKeyword(
@component.with_listener(GuildMessageCreateEvent)
async def EventMention(
ctx: GuildMessageCreateEvent,
config: Dict[str, Any] = tanjun.inject(type=Dict[str, Any]),
config: dict[str, Any] = tanjun.inject(type=dict[str, Any]),
) -> None:
"""Handler for notifying of mentions."""

Expand All @@ -173,7 +173,7 @@ async def EventMention(
elif ctx.message.content is None:
return

found: List[str] = []
found: list[str] = []

for id in config["logging"]["mentions"]:
if id not in ctx.message.user_mentions_ids:
Expand All @@ -184,7 +184,7 @@ async def EventMention(
if len(found) == 0:
return

payload: Dict[str, Any] = {
payload: dict[str, Any] = {
"username": "N31L",
"avatar_url": "https://i.imgur.com/cGtkGuI.png",
"embeds": [
Expand Down Expand Up @@ -242,7 +242,7 @@ async def EventMention(
async def EventMirror(
ctx: GuildMessageCreateEvent,
client: Client = tanjun.inject(type=Client),
config: Dict[str, Any] = tanjun.inject(type=Dict[str, Any]),
config: dict[str, Any] = tanjun.inject(type=dict[str, Any]),
) -> None:
"""Handler for automatically mirroring Zeppelin log archives."""

Expand All @@ -258,7 +258,7 @@ async def EventMirror(
return

content: str = ctx.message.content.lower()
urls: List[str] = []
urls: list[str] = []
extractor: URLExtract = URLExtract()

urls = extractor.find_urls(content, True)
Expand All @@ -270,7 +270,7 @@ async def EventMirror(
if not url.startswith("https://api.zeppelin.gg/archives/"):
continue

data: Optional[str] = await Utility.GET(url)
data: str | None = await Utility.GET(url)

if data is None:
return
Expand Down
22 changes: 11 additions & 11 deletions components/messages.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import datetime
from os import environ
from typing import Any, Dict, List, Optional
from typing import Any

import tanjun
from hikari import (
Expand Down Expand Up @@ -32,7 +32,7 @@
@component.with_schedule
@tanjun.as_interval(300)
async def TaskArchiveThreads(
config: Dict[str, Any] = tanjun.inject(type=Dict[str, Any]),
config: dict[str, Any] = tanjun.inject(type=dict[str, Any]),
bot: GatewayBot = tanjun.inject(type=GatewayBot),
) -> None:
"""Automatically archive threads in the configured channels."""
Expand All @@ -43,7 +43,7 @@ async def TaskArchiveThreads(
logger.info("Beginning recurring task to archive threads...")

lifetime: int = config["archiveThreads"]["lifetime"]
threads: List[GuildThreadChannel] = await bot.rest.fetch_active_threads(
threads: list[GuildThreadChannel] = await bot.rest.fetch_active_threads(
int(environ.get("DISCORD_SERVER_ID"))
)

Expand Down Expand Up @@ -80,7 +80,7 @@ async def TaskArchiveThreads(
@component.with_listener(GuildMessageCreateEvent)
async def EventShadowban(
ctx: GuildMessageCreateEvent,
config: Dict[str, Any] = tanjun.inject(type=Dict[str, Any]),
config: dict[str, Any] = tanjun.inject(type=dict[str, Any]),
) -> None:
"""Silently delete user messages in the configured channels."""

Expand Down Expand Up @@ -111,7 +111,7 @@ async def EventShadowban(
async def CommandReport(
ctx: MenuContext,
message: Message,
config: Dict[str, Any] = tanjun.inject(type=Dict[str, Any]),
config: dict[str, Any] = tanjun.inject(type=dict[str, Any]),
) -> None:
"""Handler for the Report to Moderators message command."""

Expand All @@ -128,8 +128,8 @@ async def CommandReport(

return

imageUrl: Optional[str] = None
fields: List[Dict[str, Any]] = [
imageUrl: str | None = None
fields: list[dict[str, Any]] = [
{"name": "Channel", "value": f"<#{message.channel_id}>"},
{"name": "Sent", "value": Timestamps.Relative(message.created_at)},
{"name": "Reported", "value": Timestamps.Relative(ctx.created_at)},
Expand Down Expand Up @@ -214,12 +214,12 @@ async def CommandPurge(
ctx: SlashContext,
channel: InteractionChannel,
amount: int,
member: Optional[Member],
member: Member | None,
) -> None:
"""Handler for the /purge command."""

messages: List[int] = []
users: List[int] = []
messages: list[int] = []
users: list[int] = []
last: datetime = datetime.now()

try:
Expand Down Expand Up @@ -305,7 +305,7 @@ async def CommandParseUsers(
) -> None:
"""Handler for the /parse users command."""

results: List[int] = []
results: list[int] = []

# Minimum and maximum length of Discord snowflakes
# https://discord.com/developers/docs/reference#snowflakes
Expand Down
Loading

0 comments on commit a6e9f68

Please sign in to comment.