Skip to content

Commit

Permalink
use X | Y type annotation
Browse files Browse the repository at this point in the history
  • Loading branch information
rtk-rnjn committed Jul 25, 2023
1 parent 4600ab7 commit e05fc5b
Show file tree
Hide file tree
Showing 106 changed files with 890 additions and 956 deletions.
6 changes: 3 additions & 3 deletions api/cricket_api/api.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import random
from typing import Any, Optional
from typing import Any

import aiohttp # type: ignore
import uvicorn # type: ignore
Expand All @@ -19,11 +19,11 @@ async def root():


@app.get("/cricket_api")
async def cricket_api(url: Optional[str] = None) -> Optional[dict[str, Any]]:
async def cricket_api(url: str | None = None) -> dict[str, Any] | None:
return await _cricket_api(url)


async def _cricket_api(url: Optional[str] = None) -> Optional[dict[str, Any]]:
async def _cricket_api(url: str | None = None) -> dict[str, Any] | None:
if not url:
raise HTTPException(status_code=400, detail="URL not provided")

Expand Down
8 changes: 4 additions & 4 deletions api/cricket_api/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from concurrent.futures import ThreadPoolExecutor
from functools import partial, wraps
from html import unescape
from typing import Any, Optional
from typing import Any
from collections.abc import Callable

from bs4 import BeautifulSoup
Expand All @@ -19,7 +19,7 @@


class ToAsync:
def __init__(self, *, executor: Optional[ThreadPoolExecutor] = None) -> None:
def __init__(self, *, executor: ThreadPoolExecutor | None = None) -> None:
self.executor = executor

def __call__(self, blocking) -> Callable:
Expand All @@ -45,15 +45,15 @@ def parse_text(st: str) -> str:


@ToAsync()
def find_one(soup: BeautifulSoup, name: str, **kwargs: Any) -> Optional[str]:
def find_one(soup: BeautifulSoup, name: str, **kwargs: Any) -> str | None:
if finder := soup.find(name, kwargs):
return __parse_text(finder.text)

return None


@ToAsync()
def find_all(soup: BeautifulSoup, name: str, **kwargs: Any) -> Optional[list[str]]:
def find_all(soup: BeautifulSoup, name: str, **kwargs: Any) -> list[str] | None:
if finder := soup.find_all(name, kwargs):
return [__parse_text(i.text) for i in finder]

Expand Down
3 changes: 1 addition & 2 deletions cogs/actions/actions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

from random import choice, random
from typing import Optional

import discord
from core import Cog, Context, Parrot
Expand All @@ -26,7 +25,7 @@ def __init__(self, bot: Parrot) -> None:
def display_emoji(self) -> discord.PartialEmoji:
return discord.PartialEmoji(name="Lights_Camera_Action__Emoticon__", id=892434144364220497)

def _try_from_cache(self, ctx: Context) -> Optional[str]:
def _try_from_cache(self, ctx: Context) -> str | None:
return choice(self.cached_images.get(ctx.command.qualified_name, [None]))

async def send_message(self, ctx: Context, *, url: str = None) -> None:
Expand Down
6 changes: 3 additions & 3 deletions cogs/autoresponder/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import difflib
import inspect
import re
from typing import Annotated, Optional, Union
from typing import Annotated, Optional

import async_timeout
from jinja2.sandbox import SandboxedEnvironment
Expand Down Expand Up @@ -70,7 +70,7 @@ async def autoresponder(self, ctx: Context) -> None:

@autoresponder.command(name="tutorial")
@commands.has_permissions(manage_guild=True)
async def autoresponder_tutorial(self, ctx: Context, *, entity: Optional[str] = None) -> None:
async def autoresponder_tutorial(self, ctx: Context, *, entity: str | None = None) -> None:
"""Tutorial for autoresponder commands."""
# get the entity from TOPICS, use difflib to get the closest match
if entity:
Expand Down Expand Up @@ -143,7 +143,7 @@ def format_var(v: str) -> str:

@autoresponder.command(name="ignore")
@commands.has_permissions(manage_guild=True)
async def autoresponder_ignore(self, ctx: Context, name: str, entity: Union[discord.Role, discord.TextChannel]) -> None:
async def autoresponder_ignore(self, ctx: Context, name: str, entity: discord.Role | discord.TextChannel) -> None:
"""Ignore a role or channel from an autoresponder."""
if name not in self.cache[ctx.guild.id]:
await ctx.reply("An autoresponder with that name does not exist.")
Expand Down
34 changes: 17 additions & 17 deletions cogs/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio
import hashlib
import json
from typing import Annotated, Any, Literal, Optional, Union
from typing import Annotated, Any, Literal

from motor.motor_asyncio import AsyncIOMotorCollection as Collection
from tabulate import tabulate
Expand Down Expand Up @@ -131,7 +131,7 @@ async def setup_hub(
ctx: Context,
):
"""To setup Hub like channel."""
overwrites: dict[Union[discord.Role, discord.Member], discord.PermissionOverwrite] = {
overwrites: dict[discord.Role | discord.Member, discord.PermissionOverwrite] = {
ctx.guild.default_role: discord.PermissionOverwrite(connect=True, read_messages=True),
ctx.guild.me: discord.PermissionOverwrite(
connect=True,
Expand Down Expand Up @@ -166,19 +166,19 @@ async def starboard(
if ctx.invoked_subcommand:
return
try:
starboard_data: dict[str, Union[str, int, list[int], bool, None]] = self.bot.guild_configurations_cache[
starboard_data: dict[str, str | int | list[int] | bool | None] = self.bot.guild_configurations_cache[
ctx.guild.id
]["starboard_config"]
except KeyError:
return await self.bot.invoke_help_command(ctx)

channel: Optional[discord.TextChannel] = ctx.guild.get_channel(starboard_data.get("channel", 0))
limit: Optional[int] = starboard_data.get("limit")
is_locked: Optional[bool] = starboard_data.get("is_locked")
channel: discord.TextChannel | None = ctx.guild.get_channel(starboard_data.get("channel", 0))
limit: int | None = starboard_data.get("limit")
is_locked: bool | None = starboard_data.get("is_locked")

ignore_channel = ", ".join([f"{ctx.guild.get_channel(c)} ({c})" for c in starboard_data.get("ignore_channel", [])])
max_duration: Optional[str] = starboard_data.get("max_duration")
can_self_star: Optional[bool] = starboard_data.get("can_self_star")
max_duration: str | None = starboard_data.get("max_duration")
can_self_star: bool | None = starboard_data.get("can_self_star")

return await ctx.reply(
f"Configuration of this server [starboard]\n\n"
Expand All @@ -192,7 +192,7 @@ async def starboard(

@starboard.command(name="channel")
@commands.has_permissions(administrator=True)
async def starboard_channel(self, ctx: Context, *, channel: Optional[discord.TextChannel] = None):
async def starboard_channel(self, ctx: Context, *, channel: discord.TextChannel | None = None):
"""To setup the channel."""
await self.bot.guild_configurations.update_one(
{"_id": ctx.guild.id},
Expand Down Expand Up @@ -274,7 +274,7 @@ async def botprefix(self, ctx: Context, *, arg: str):
@config.command()
@commands.has_permissions(administrator=True)
@Context.with_type
async def suggestchannel(self, ctx: Context, *, channel: Optional[discord.TextChannel] = None):
async def suggestchannel(self, ctx: Context, *, channel: discord.TextChannel | None = None):
"""To configure the suggestion channel. If no channel is provided it will remove the channel."""
if channel:
await self.bot.guild_configurations.update_one(
Expand Down Expand Up @@ -332,12 +332,12 @@ async def gsetup(
ctx: Context,
setting: str = None,
*,
role: Optional[discord.Role] = None,
role: discord.Role | None = None,
):
"""This command will connect your server with other servers which then connected to #global-chat must try this once."""
collection: Collection = self.bot.guild_configurations
if not setting:
overwrites: dict[Union[discord.Role, discord.Member], discord.PermissionOverwrite] = {
overwrites: dict[discord.Role | discord.Member, discord.PermissionOverwrite] = {
ctx.guild.default_role: discord.PermissionOverwrite(
read_messages=True,
send_messages=True,
Expand Down Expand Up @@ -611,7 +611,7 @@ async def tel_config_memberping(self, ctx: Context, *, member: discord.Member =
@telephone.command(name="block")
@commands.has_permissions(administrator=True)
@Context.with_type
async def tel_config_block(self, ctx: Context, *, server: Union[discord.Guild, int]):
async def tel_config_block(self, ctx: Context, *, server: discord.Guild | int):
"""There are people who are really anonying, you can block them."""
if server is ctx.guild:
return await ctx.reply(f"{ctx.author.mention} can't block your own server")
Expand Down Expand Up @@ -793,7 +793,7 @@ async def enable(
ctx: Context,
command: Annotated[str, commands.clean_content],
*,
target: Optional[Union[discord.TextChannel, discord.VoiceChannel, discord.Thread, discord.Role]] = None,
target: discord.TextChannel | discord.VoiceChannel | discord.Thread | discord.Role | None = None,
):
"""To enable the command."""
cmd = self.bot.get_command(command)
Expand All @@ -815,7 +815,7 @@ async def disable(
ctx: Context,
command: Annotated[str, commands.clean_content],
*,
target: Optional[Union[discord.TextChannel, discord.VoiceChannel, discord.Thread, discord.Role]] = None,
target: discord.TextChannel | discord.VoiceChannel | discord.Thread | discord.Role | None = None,
):
"""To disable the command."""
cmd = self.bot.get_command(command)
Expand Down Expand Up @@ -992,7 +992,7 @@ async def serverstats_create(
r"What should be the format of the channel? Example: `Total Channels {}`, `{} Roles in total`. Only the `{}` will be replaced with the counter value.",
]

async def wait_for_response() -> Optional[str]:
async def wait_for_response() -> str | None:
def check(m: discord.Message) -> bool:
return m.author == ctx.author and m.channel == ctx.channel

Expand Down Expand Up @@ -1096,7 +1096,7 @@ async def serverstats_delete(
if counter.lower() not in AVAILABLE:
return await ctx.error(f"{ctx.author.mention} invalid counter! Available counter: `{'`, `'.join(AVAILABLE)}`")

async def wait_for_response() -> Optional[str]:
async def wait_for_response() -> str | None:
def check(m: discord.Message) -> bool:
return m.author == ctx.author and m.channel == ctx.channel

Expand Down
17 changes: 8 additions & 9 deletions cogs/config/flags.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
from __future__ import annotations

from typing import Optional

from discord.ext import commands
from utilities.converters import convert_bool


class AutoWarn(commands.FlagConverter, case_insensitive=True, delimiter=" ", prefix="--"):
enable: Optional[convert_bool] = True
count: Optional[int] = None
punish: Optional[str] = None
duration: Optional[str] = None
delete: Optional[convert_bool] = True
enable: convert_bool | None = True
count: int | None = None
punish: str | None = None
duration: str | None = None
delete: convert_bool | None = True


class WarnConfig(commands.FlagConverter, case_insensitive=True, delimiter=" ", prefix="--"):
count: Optional[int] = None
action: Optional[str] = None
duration: Optional[str] = None
count: int | None = None
action: str | None = None
duration: str | None = None
8 changes: 4 additions & 4 deletions cogs/config/method.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import Any, Literal, Optional, Union
from typing import Any, Literal

import discord
from core import Context
Expand All @@ -22,7 +22,7 @@ def get_text(
*,
ctx: Context,
cmd_cog: str,
target: Optional[Union[discord.Role, discord.abc.GuildChannel]],
target: discord.Role | discord.abc.GuildChannel | None,
tp: Literal["enable", "disable"],
) -> str:
is_are = "commands are" if cmd_cog == "all" else "is"
Expand All @@ -38,7 +38,7 @@ def get_text(
async def _enable(
ctx: Context,
cmd_cog: str,
target: Union[discord.abc.GuildChannel, discord.Role, None],
target: discord.abc.GuildChannel | discord.Role | None,
) -> None:
assert ctx.guild
if not target:
Expand All @@ -58,7 +58,7 @@ async def _enable(
async def _disable(
ctx: Context,
cmd_cog: str,
target: Union[discord.abc.GuildChannel, discord.Role],
target: discord.abc.GuildChannel | discord.Role,
) -> None:
assert ctx.guild
if not target:
Expand Down
6 changes: 3 additions & 3 deletions cogs/defcon/defcon.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Union
from typing import TYPE_CHECKING

import discord
from core import Cog, Context, Parrot
Expand Down Expand Up @@ -442,7 +442,7 @@ async def defcon_trustables(self, ctx: Context) -> None:

@defcon_trustables.command(name="add")
@commands.has_permissions(manage_guild=True)
async def defcon_trustables_add(self, ctx: Context, *roles_or_members: Union[discord.Role, discord.Member]) -> None:
async def defcon_trustables_add(self, ctx: Context, *roles_or_members: discord.Role | discord.Member) -> None:
"""To add trustable roles or members."""
guild_config = self.bot.guild_configurations_cache[ctx.guild.id]

Expand Down Expand Up @@ -481,7 +481,7 @@ async def defcon_trustables_add(self, ctx: Context, *roles_or_members: Union[dis

@defcon_trustables.command(name="remove")
@commands.has_permissions(manage_guild=True)
async def defcon_trustables_remove(self, ctx: Context, *roles_or_members: Union[discord.Role, discord.Member]) -> None:
async def defcon_trustables_remove(self, ctx: Context, *roles_or_members: discord.Role | discord.Member) -> None:
"""To remove trustable roles or members."""
guild_config = self.bot.guild_configurations_cache[ctx.guild.id]

Expand Down
7 changes: 3 additions & 4 deletions cogs/defcon/events.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

from typing import Optional, Union

import discord
from core import Cog, Parrot
Expand All @@ -13,7 +12,7 @@ def __init__(self, bot: Parrot) -> None:
self.bot = bot
self.settings = bot.guild_configurations_cache

async def defcon_broadcast(self, message: Union[str, discord.Embed], *, guild: discord.Guild, level: int) -> None:
async def defcon_broadcast(self, message: str | discord.Embed, *, guild: discord.Guild, level: int) -> None:
if self.has_defcon_in(guild) is False:
await self.bot.guild_configurations.update_one(
{"_id": guild.id},
Expand Down Expand Up @@ -95,8 +94,8 @@ async def defcon_on_invite_create(self, invite: discord.Invite, level: int) -> N

def has_defcon_in(
self,
guild: Optional[Union[discord.Guild, discord.Object, discord.PartialInviteGuild]],
) -> Union[bool, int]:
guild: discord.Guild | discord.Object | discord.PartialInviteGuild | None,
) -> bool | int:
if guild is None:
return False

Expand Down
4 changes: 2 additions & 2 deletions cogs/fun/_effects.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from collections.abc import Callable
from io import BytesIO
from pathlib import Path
from typing import Any, Optional
from typing import Any

from PIL import Image, ImageDraw, ImageOps

Expand Down Expand Up @@ -118,7 +118,7 @@ def flip_effect(image: Image.Image) -> Image.Image:
return image

@staticmethod
def easterify_effect(image: Image.Image, overlay_image: Optional[Image.Image] = None) -> Image.Image:
def easterify_effect(image: Image.Image, overlay_image: Image.Image | None = None) -> Image.Image:
"""Applies the easter effect to the given image.
This is done by getting the closest "easter" colour to each pixel and changing the colour
to the half-way RGB value.
Expand Down
12 changes: 6 additions & 6 deletions cogs/fun/_flags.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
from __future__ import annotations

from enum import Enum
from typing import Literal, Optional
from typing import Literal

from discord.ext import commands


class TriviaFlag(commands.FlagConverter, case_insensitive=True, prefix="--", delimiter=" "): # type: ignore
token: Optional[str] = None
number: Optional[int] = commands.flag(name="number", default=10, aliases=["amount"])
category: Optional[str] = None
difficulty: Optional[Literal["easy", "medium", "hard"]] = None
_type: Optional[Literal["multiple", "boolean"]] = commands.flag(default="multiple", name="type")
token: str | None = None
number: int | None = commands.flag(name="number", default=10, aliases=["amount"])
category: str | None = None
difficulty: Literal["easy", "medium", "hard"] | None = None
_type: Literal["multiple", "boolean"] | None = commands.flag(default="multiple", name="type")


class Category(Enum):
Expand Down
Loading

0 comments on commit e05fc5b

Please sign in to comment.