Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernize and update the codebase with latest dependencies and ruff. #63

Merged
merged 1 commit into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions config.template.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ owner_ids = [123, 456, 789] # user or role ids, optional
[TOKENS]
bot = ''
idevision = '' # optional key
mystbin = '' # optional key
pythonista = '' # optional key
pythonista = '' # optional key

[DATABASE]
dsn = 'postgres://pythonistabot:pythonistabot@database:5432/pythonistabot' # assumed default
Expand All @@ -19,9 +18,9 @@ domains = ["pastebin.com", "hastebin.com"]
# 20 = INFO
# 10 = DEBUG
[LOGGING]
webhook_url = "" # optional
webhook_url = "" # optional
webhook_avatar_url = "" # optional
runner = 123456789 # optional: sets the webhook avatar url (will be overridden by the webhook_avatar_url attribute)
runner = 123456789 # optional: sets the webhook avatar url (will be overridden by the webhook_avatar_url attribute)
level = 20

[SUGGESTIONS] # optional
Expand Down
1 change: 1 addition & 0 deletions constants/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from .constants import *

GUILD_ID: int = 490948346773635102
5 changes: 2 additions & 3 deletions constants/_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,22 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, NoReturn, cast

import toml

if TYPE_CHECKING:
from typing_extensions import Self

from types_.config import Database, Logging, Tokens


_config = toml.load("config.toml")


class ConstantsMeta(type):
def __new__(mcs, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> Self:
def __new__(mcs, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> type:
if name == "CONSTANTS":
return super().__new__(mcs, name, bases, attrs)

Expand Down
1 change: 1 addition & 0 deletions constants/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from ._meta import CONSTANTS

__all__ = (
Expand Down
1 change: 1 addition & 0 deletions core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

__version__ = "0.0.1a"

from . import utils as utils
Expand Down
3 changes: 2 additions & 1 deletion core/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

import datetime
Expand Down Expand Up @@ -106,7 +107,7 @@ async def on_error(self, event_name: str, /, *args: Any, **kwargs: Any) -> None:
traceback_text = "".join(traceback.format_exception(exc_type, exception, traceback_))

embed.description = f"```py\n{traceback_text}\n```"
embed.timestamp = datetime.datetime.now(datetime.timezone.utc)
embed.timestamp = datetime.datetime.now(datetime.UTC)

args_str = ["```py"]
for index, arg in enumerate(args):
Expand Down
1 change: 1 addition & 0 deletions core/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any
Expand Down
1 change: 1 addition & 0 deletions core/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from collections import deque
from typing import NamedTuple

Expand Down
1 change: 1 addition & 0 deletions core/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

from typing import TYPE_CHECKING
Expand Down
1 change: 1 addition & 0 deletions core/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from discord.ext import commands

__all__ = ("InvalidEval",)
Expand Down
1 change: 1 addition & 0 deletions core/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from .formatters import *
from .logging import LogHandler as LogHandler
1 change: 1 addition & 0 deletions core/utils/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import random

from discord import Colour
Expand Down
2 changes: 1 addition & 1 deletion core/utils/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import core

if TYPE_CHECKING:
from typing_extensions import Self
from typing import Self

from core import Bot

Expand Down
6 changes: 4 additions & 2 deletions core/utils/paginator.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

import asyncio
Expand All @@ -31,8 +32,9 @@
from discord.utils import MISSING

if TYPE_CHECKING:
from typing import Self

from discord.abc import MessageableChannel
from typing_extensions import Self

from core import Bot, Context

Expand Down Expand Up @@ -208,7 +210,7 @@ def message_check(m: discord.Message) -> bool:

try:
msg = await self.bot.wait_for("message", check=message_check, timeout=30.0)
except asyncio.TimeoutError:
except TimeoutError:
to_delete.append(await self.channel.send("Took too long."))
await asyncio.sleep(5)
else:
Expand Down
14 changes: 9 additions & 5 deletions launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import asyncio

import aiohttp
Expand All @@ -32,18 +33,21 @@


async def main() -> None:
async with core.Bot() as bot, aiohttp.ClientSession() as session, asyncpg.create_pool(
dsn=core.CONFIG["DATABASE"]["dsn"]
) as pool, LogHandler(bot=bot) as handler:
async with (
core.Bot() as bot,
aiohttp.ClientSession() as session,
asyncpg.create_pool(dsn=core.CONFIG["DATABASE"]["dsn"]) as pool,
LogHandler(bot=bot) as handler,
):
bot.logging_queue = asyncio.Queue()
bot.strip_after_prefix = True
bot.case_insensitive = True
bot.session = session
bot.pool = pool
bot.log_handler = handler

_mystbin_token = core.CONFIG["TOKENS"].get("mystbin")
bot.mb_client = mystbin.Client(token=_mystbin_token, session=session)
_mystbin_token = core.CONFIG["TOKENS"]
bot.mb_client = mystbin.Client(session=session)

await bot.load_extension("jishaku")
for extension in EXTENSIONS:
Expand Down
2 changes: 2 additions & 0 deletions modules/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import pathlib
from pkgutil import ModuleInfo, iter_modules

assert __package__ # this exists here

_ext: list[ModuleInfo] = []
_ext.extend(
[
Expand Down
1 change: 1 addition & 0 deletions modules/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import logging

from discord.ext import commands
Expand Down
1 change: 1 addition & 0 deletions modules/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

import asyncio
Expand Down
4 changes: 3 additions & 1 deletion modules/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

import ast
import logging
import textwrap
import traceback

import mystbin
from discord.ext import commands

import core
Expand Down Expand Up @@ -104,7 +106,7 @@ async def eval(
await ctx.message.add_reaction("\U00002705")

if len(output) > 1000:
codeblock = await self.bot.mb_client.create_paste(content=output, filename="eval.py")
codeblock = await self.bot.mb_client.create_paste(files=[mystbin.File(content=output, filename="eval.py")])

elif output:
codeblock = formatters.to_codeblock(output, escape_md=False)
Expand Down
9 changes: 4 additions & 5 deletions modules/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

import asyncio
import re
from enum import Enum

Expand Down Expand Up @@ -165,9 +165,8 @@ async def format_highlight_block(self, url: str, line_adjustment: int = 10) -> d

github_dict = {
"path": file_path,
"min": (
_min_boundary if _min_boundary > 0 else highlighted_line - 1
) + 1, # Do not display negative numbers if <0
"min": (_min_boundary if _min_boundary > 0 else highlighted_line - 1)
+ 1, # Do not display negative numbers if <0
"max": _max_boundary + 1,
"msg": msg,
}
Expand Down Expand Up @@ -256,7 +255,7 @@ def check(reaction: discord.Reaction, user: discord.User) -> bool:
msg: str = f"Showing lines `{_min}-{_max}` in: `{path}`\n{code_fmt}"
await message.channel.send(msg, suppress_embeds=True)

except asyncio.TimeoutError:
except TimeoutError:
return


Expand Down
1 change: 1 addition & 0 deletions modules/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

from typing import TYPE_CHECKING
Expand Down
1 change: 1 addition & 0 deletions modules/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

from typing import TypeVar
Expand Down
3 changes: 2 additions & 1 deletion modules/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

import datetime
Expand Down Expand Up @@ -61,7 +62,7 @@ async def logging_loop(self) -> None:
attributes = {"INFO": "\U00002139\U0000fe0f", "WARNING": "\U000026a0\U0000fe0f"}

emoji = attributes.get(to_log.levelname, "\N{CROSS MARK}")
dt = datetime.datetime.utcfromtimestamp(to_log.created)
dt = datetime.datetime.fromtimestamp(to_log.created, tz=datetime.UTC)

message = textwrap.shorten(f"{emoji} {format_dt(dt)}\n{to_log.message}", width=1990)

Expand Down
1 change: 1 addition & 0 deletions modules/manuals.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

import discord
Expand Down
9 changes: 4 additions & 5 deletions modules/moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import annotations

import asyncio
Expand Down Expand Up @@ -234,11 +235,9 @@ async def pull_badbin_content(self, site: str, slug: str, *, fail_hard: bool = T

return (await f.read()).decode()

async def post_mystbin_content(self, contents: list[tuple[str, str]]) -> tuple[str, str | None]:
response = await self.bot.mb_client.create_paste(
files=[mystbin.File(filename=a, content=b, attachment_url=None) for a, b in contents]
)
return response.id, response.notice or None
async def post_mystbin_content(self, contents: list[tuple[str, str]]) -> str:
response = await self.bot.mb_client.create_paste(files=[mystbin.File(filename=a, content=b) for a, b in contents])
return response.id

@commands.Cog.listener("on_message")
async def find_badbins(self, message: discord.Message) -> None:
Expand Down
1 change: 1 addition & 0 deletions modules/stars.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import core


Expand Down
7 changes: 2 additions & 5 deletions modules/suggestions.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

import logging
from datetime import datetime
from typing import Union

import discord
from discord import ui
Expand All @@ -43,7 +42,7 @@ class TypeSelect(ui.Select["TypeView"]):
def __init__(
self,
*,
original_author: Union[discord.Member, discord.User],
original_author: discord.Member | discord.User,
suggestion: str,
webhook: discord.Webhook,
) -> None:
Expand Down Expand Up @@ -88,9 +87,7 @@ async def callback(self, interaction: discord.Interaction) -> None:
class TypeView(ui.View):
message: discord.Message | discord.WebhookMessage

def __init__(
self, *, original_author: Union[discord.Member, discord.User], suggestion: str, webhook: discord.Webhook
) -> None:
def __init__(self, *, original_author: discord.Member | discord.User, suggestion: str, webhook: discord.Webhook) -> None:
super().__init__(timeout=180)
self.original_author = original_author
self.add_item(TypeSelect(original_author=original_author, suggestion=suggestion, webhook=webhook))
Expand Down
1 change: 1 addition & 0 deletions modules/tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import core


Expand Down
Loading
Loading