Skip to content

Commit

Permalink
Merge pull request #161 from alexraskin/Fix-typing-annotations
Browse files Browse the repository at this point in the history
✨ feat: add type hints and future annotations to improve code readabi…
  • Loading branch information
alexraskin authored Feb 19, 2024
2 parents a795930 + 80ab0b6 commit 9f352a6
Show file tree
Hide file tree
Showing 14 changed files with 207 additions and 140 deletions.
17 changes: 9 additions & 8 deletions bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
import platform
import time
from functools import lru_cache
from typing import Union

import motor.motor_asyncio
import psutil # type: ignore
import psutil # type: ignore
import sentry_sdk
from aiohttp import ClientSession, ClientTimeout
from cogs import EXTENSIONS
Expand Down Expand Up @@ -38,7 +39,7 @@ class LhBot(AutoShardedBot):
def __init__(self, *args, **options) -> None:
super().__init__(*args, **options)
self.session: ClientSession = None
self.db_client = None
self.db_client: motor.motor_asyncio.AsyncIOMotorClient = None
self.start_time = None
self.version = config.bot_version
self.config = config
Expand Down Expand Up @@ -81,7 +82,7 @@ async def setup_hook(self) -> None:
@property
def get_uptime(self) -> str:
return str(
datetime.timedelta(seconds=int(round(time.time() - self.start_time)))
datetime.timedelta(seconds=int(round(time.time() - self.start_time))) # type: ignore
)

@property
Expand All @@ -99,7 +100,7 @@ def cpu_usage(self) -> float:
return psutil.cpu_percent(interval=1)

@property
def git_revision(self) -> str:
def git_revision(self) -> Union[str, None]:
latest_revision = os.getenv("RAILWAY_GIT_COMMIT_SHA")
if latest_revision is None:
return None
Expand Down Expand Up @@ -128,12 +129,12 @@ async def clean_dir() -> None:


@client.event
async def on_ready() -> bool:
async def on_ready() -> None:
main_id = config.main_guild
client.main_guild = client.get_guild(main_id) or client.guilds[0]
logging.info(f"{client.user.name} started successfully")
client.main_guild = client.get_guild(main_id) or client.guilds[0] # type: ignore
logging.info(f"{client.user.name} started successfully") # type: ignore
clean_dir.start()


client.run(token=config.bot_token, reconnect=True, log_handler=None)
logging.info(f"{client.user.name} stopped successfully")
logging.info(f"{client.user.name} stopped successfully") # type: ignore
9 changes: 7 additions & 2 deletions bot/cogs/fun.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import random
from typing import Union, TYPE_CHECKING

Expand All @@ -8,6 +10,7 @@
if TYPE_CHECKING:
from ..bot import LhBot


class Fun(commands.Cog, name="Fun"):
def __init__(self, client: LhBot):
self.client: LhBot = client
Expand All @@ -26,7 +29,9 @@ async def load_chuck_http_codes(self) -> None:
@commands.guild_only()
@app_commands.guild_only()
@app_commands.describe(category="Category of Chuck Norris fact")
async def chucknorris(self, ctx: commands.Context, category: str = None) -> Union[Embed, None]:
async def chucknorris(
self, ctx: commands.Context, category: str = None
) -> Union[Embed, None]:
"""
Get a random Chuck Norris fact
"""
Expand Down Expand Up @@ -189,5 +194,5 @@ async def year(self, ctx: commands.Context):
await ctx.send(embed=embed)


async def setup(client):
async def setup(client: LhBot):
await client.add_cog(Fun(client))
15 changes: 10 additions & 5 deletions bot/cogs/general.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import random
import os

Expand All @@ -13,12 +15,13 @@
if TYPE_CHECKING:
from ..bot import LhBot


class General(commands.Cog, name="General"):
def __init__(self, client: LhBot):
self.client: LhBot = client
self.streamer_name = "lhcloudy27"
self.cloudflare_url = os.environ.get("CLOUDFLARE_URL")
self.cloudflare_token = os.environ.get('CLOUDFLARE_TOKEN')
self.cloudflare_token = os.environ.get("CLOUDFLARE_TOKEN")
self.twitch_url = "https://www.twitch.tv/lhcloudy27"
self.body = {
"client_id": self.client.config.twitch_client_id,
Expand All @@ -27,7 +30,9 @@ def __init__(self, client: LhBot):
}
self.status_task.start()

async def check_if_live(self) -> Union[Tuple[bool, str, str, str], Tuple[bool, None, None, None]]:
async def check_if_live(
self,
) -> Union[Tuple[bool, str, str, str], Tuple[bool, None, None, None]]:
async with self.client.session.post(
"https://id.twitch.tv/oauth2/token", data=self.body
) as response:
Expand Down Expand Up @@ -123,7 +128,6 @@ async def on_command_error(self, ctx, error) -> None:
capture_exception(error)
return


@commands.Cog.listener()
async def on_message(self, message: discord.Message):
if message.author.bot:
Expand All @@ -142,7 +146,8 @@ async def on_message(self, message: discord.Message):
"messages": [
{
"role": "system",
"content": gpt.context + f"when you answer someone, answer them by {name}",
"content": gpt.context
+ f"when you answer someone, answer them by {name}",
},
{
"role": "user",
Expand Down Expand Up @@ -196,5 +201,5 @@ async def on_command_completion(self, ctx: commands.Context) -> None:
)


async def setup(client):
async def setup(client: LhBot):
await client.add_cog(General(client))
31 changes: 19 additions & 12 deletions bot/cogs/help.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
from __future__ import annotations

import itertools

from typing import TYPE_CHECKING

from discord import Embed
from discord.ext import commands
from discord.ext.commands import DefaultHelpCommand, HelpCommand

if TYPE_CHECKING:
from ..bot import LhBot


class myHelpCommand(HelpCommand):
def __init__(self, **options) -> None:
Expand All @@ -16,7 +23,7 @@ async def send_pages(self, header=False, footer=False):
embed = Embed(color=0x2ECC71, timestamp=self.context.message.created_at)
if header:
embed.set_author(name=self.context.bot.description)
for category, entries in self.paginator:
for category, entries in self.paginator: # type: ignore
embed.add_field(name=category, value=entries, inline=False)
if footer:
embed.set_footer(text="Use !help <command/category> for more information.")
Expand Down Expand Up @@ -44,7 +51,7 @@ def get_category(command):
entries += " | ".join([cmd.name for cmd in cmds[0:8]])
cmds = cmds[8:]
entries += "\n" if cmds else ""
self.paginator.append((category, entries))
self.paginator.append((category, entries)) # type: ignore
await self.send_pages(header=True, footer=True)

async def send_cog_help(self, cog):
Expand All @@ -60,7 +67,7 @@ async def send_cog_help(self, cog):
+ f"**{command.name}** → {command.short_doc or command.description}"
for command in filtered
)
self.paginator.append((category, entries))
self.paginator.append((category, entries)) # type: ignore
await self.send_pages(footer=True)

async def send_group_help(self, group):
Expand All @@ -75,13 +82,13 @@ async def send_group_help(self, group):
self.spacer + f"**{command.name}** → {command.short_doc}"
for command in filtered
)
self.paginator.append((category, entries))
self.paginator.append((category, entries)) # type: ignore
await self.send_pages(footer=True)

async def send_command_help(self, command):
signature = self.get_command_signature(command)
helptext = command.help or command.description or "No help Text"
self.paginator.append((signature, helptext))
self.paginator.append((signature, helptext)) # type: ignores
await self.send_pages()

async def prepare_help_command(self, ctx, command=None):
Expand All @@ -90,20 +97,20 @@ async def prepare_help_command(self, ctx, command=None):


class Help(commands.Cog):
def __init__(self, client):
self.client = client
def __init__(self, client: LhBot):
self.client: LhBot = client
self.client.help_command = myHelpCommand(
command_attrs={
"aliases": ["halp"],
"help": "Shows help about the bot, a command, or a category",
}
)

async def cog_check(self, ctx):
return self.client.user_is_admin(ctx.author)
async def cog_check(self, ctx): # type: ignore
return self.client.user_is_admin(ctx.author) # type: ignore

def cog_unload(self):
self.client.get_command("help").hidden = False
def cog_unload(self): # type: ignore
self.client.get_command("help").hidden = False # type: ignore
self.client.help_command = DefaultHelpCommand()

@commands.command(aliases=["halpall"], hidden=True)
Expand All @@ -116,5 +123,5 @@ async def helpall(self, ctx, *, text=None):
self.client.help_command = myHelpCommand()


async def setup(client):
async def setup(client: LhBot):
await client.add_cog(Help(client))
19 changes: 13 additions & 6 deletions bot/cogs/info.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
from __future__ import annotations

from typing import TYPE_CHECKING

import os
import discord
import pkg_resources
from discord import Colour, Embed, Member, app_commands
from discord.ext import commands
from utils.bot_utils import date

if TYPE_CHECKING:
from ..bot import LhBot


class Info(commands.Cog, name="Info"):
def __init__(self, client: commands.Bot) -> None:
self.client = client
class Info(commands.Cog):
def __init__(self, client: LhBot) -> None:
self.client: LhBot = client

@commands.command(
name="uptime", aliases=["up"], description="Shows the uptime of the bot"
)
@commands.guild_only()
async def uptime(self, ctx: commands.Context):
async def uptime(self, ctx: commands.Context) -> None:
embed = discord.Embed(
title="Bot Uptime",
description=f"Uptime: {self.client.get_uptime}",
Expand All @@ -26,7 +33,7 @@ async def uptime(self, ctx: commands.Context):

@commands.command(name="ping")
@commands.guild_only()
async def ping(self, ctx: commands.Context):
async def ping(self, ctx: commands.Context) -> None:
embed = discord.Embed(
title="🏓 Pong!",
description=f"The bot latency is {self.client.get_bot_latency}ms.",
Expand Down Expand Up @@ -124,5 +131,5 @@ async def user(self, ctx: commands.Context, *, user: Member = None):
await ctx.send(embed=embed)


async def setup(client):
async def setup(client: LhBot):
await client.add_cog(Info(client))
21 changes: 14 additions & 7 deletions bot/cogs/lhcloudy.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
from __future__ import annotations

import datetime
import sys

from typing import Optional, TYPE_CHECKING

from discord import Colour, Embed
from discord.ext import commands

if TYPE_CHECKING:
from ..bot import LhBot


class LhCloudy(commands.Cog, name="LhCloudy"):
def __init__(self, client: commands.Bot):
self.client = client
class LhCloudy(commands.Cog):
def __init__(self, client: LhBot):
self.client: LhBot = client

@commands.hybrid_group(invoke_without_command=True)
async def twitch(self, ctx):
Expand All @@ -17,14 +24,14 @@ async def twitch(self, ctx):
)

@twitch.command(name="lhfurry", with_app_command=True)
async def lhfurry(self, ctx: commands.Context):
async def lhfurry(self, ctx: commands.Context) -> None:
"""
LhCloudy's furry side
"""
await ctx.send("https://i.gyazo.com/3ae8376713000ab829a2853d0f31e6f2.png")

@twitch.command(name="code", aliases=["workshop"], with_app_command=True)
async def code(self, ctx: commands.Context):
async def code(self, ctx: commands.Context) -> None:
"""
LhCloudy's workshop code
"""
Expand Down Expand Up @@ -106,7 +113,7 @@ async def from_(self, ctx: commands.Context):
await ctx.send("kotka of south eastern finland of the continent of europe")

@twitch.command(name="links", aliases=["urls"], with_app_command=True)
async def links(self, ctx: commands.Context):
async def links(self, ctx: commands.Context) -> None:
"""
Get a list of LhCloudy's links
"""
Expand All @@ -123,5 +130,5 @@ async def links(self, ctx: commands.Context):
await ctx.send(embed=embed)


async def setup(client):
async def setup(client: LhBot):
await client.add_cog(LhCloudy(client))
Loading

0 comments on commit 9f352a6

Please sign in to comment.