Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/ooliver1/botbase
Browse files Browse the repository at this point in the history
  • Loading branch information
ooliver1 committed Oct 25, 2022
2 parents b511ef0 + 3b9eb47 commit b045dfb
Show file tree
Hide file tree
Showing 6 changed files with 183 additions and 30 deletions.
84 changes: 84 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,89 @@
# Changelog

## [1.22.2](https://github.com/ooliver1/botbase/compare/v1.22.1...v1.22.2) (2022-10-22)


### Bug Fixes

* **botbase:** use str.join because windows ([48554dd](https://github.com/ooliver1/botbase/commit/48554ddd31eefaf19799af546a70a9557b264693))

## [1.22.1](https://github.com/ooliver1/botbase/compare/v1.22.0...v1.22.1) (2022-10-03)


### Bug Fixes

* only sync if ready ([39a752a](https://github.com/ooliver1/botbase/commit/39a752a04d2c1d9991c228e9bb6fdcd8e7b82845))

## [1.22.0](https://github.com/ooliver1/botbase/compare/v1.21.7...v1.22.0) (2022-10-03)


### Features

* add console handlers ([2aff21b](https://github.com/ooliver1/botbase/commit/2aff21b4ef20c4114ee02ba61d15a712c8bcd62f))

## [1.21.7](https://github.com/ooliver1/botbase/compare/v1.21.6...v1.21.7) (2022-10-03)


### Bug Fixes

* istg ([d34b34b](https://github.com/ooliver1/botbase/commit/d34b34bfef0427050d134d2f0f1d151ef930d15a))

## [1.21.6](https://github.com/ooliver1/botbase/compare/v1.21.5...v1.21.6) (2022-10-03)


### Bug Fixes

* oh ([9810669](https://github.com/ooliver1/botbase/commit/9810669d7a85fc015059c47539965146bd455563))

## [1.21.5](https://github.com/ooliver1/botbase/compare/v1.21.4...v1.21.5) (2022-10-03)


### Bug Fixes

* **botbase:** actually fix close and startup ([ab8a243](https://github.com/ooliver1/botbase/commit/ab8a243c58333ae53ac6f0516191177c8bf10149))

## [1.21.4](https://github.com/ooliver1/botbase/compare/v1.21.3...v1.21.4) (2022-09-11)


### Bug Fixes

* **botbase:** support db port ([41bedd1](https://github.com/ooliver1/botbase/commit/41bedd1d2a65ed113065139a6ed6126e7841ca16))

## [1.21.3](https://github.com/ooliver1/botbase/compare/v1.21.2...v1.21.3) (2022-09-10)


### Bug Fixes

* what ([fdf2390](https://github.com/ooliver1/botbase/commit/fdf2390c94b0cb158eec2fb3e6b71c4c9cb75cbb))

## [1.21.2](https://github.com/ooliver1/botbase/compare/v1.21.1...v1.21.2) (2022-09-10)


### Bug Fixes

* **botbase:** cogs are very painful ([1bb9ab9](https://github.com/ooliver1/botbase/commit/1bb9ab918d0d941a15ae85d892ab673e38110b46))

## [1.21.1](https://github.com/ooliver1/botbase/compare/v1.21.0...v1.21.1) (2022-09-10)


### Bug Fixes

* dont import removed emptyembed sentinel ([959fcae](https://github.com/ooliver1/botbase/commit/959fcae2cb99c2cc180726a79f42d09737d9abde))

## [1.21.0](https://github.com/ooliver1/botbase/compare/v1.20.8...v1.21.0) (2022-09-10)


### Features

* **botbase:** add helpers for cogs ([78b2b91](https://github.com/ooliver1/botbase/commit/78b2b91bd3181f4d3ba8a57df262c2806482afcc))

## [1.20.8](https://github.com/ooliver1/botbase/compare/v1.20.7...v1.20.8) (2022-08-02)


### Bug Fixes

* use desc not description pt.2 ([1401519](https://github.com/ooliver1/botbase/commit/1401519b3c38567383b639b0399c4489844ba1aa))

## [1.20.7](https://github.com/ooliver1/botbase/compare/v1.20.6...v1.20.7) (2022-08-02)


Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ This is a bot base project for Discord python bots made with [nextcord](https://
| `emojiset` | `Emojis[str, str]` | `Emojis[]` |
| `logchannel` | `int` | `None` |
| `guild_ids` | `list[int]` | `None` |
| `name` | `str` | `None` |
2 changes: 1 addition & 1 deletion botbase/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from .wraps import *
from .models import *

__version__ = "1.20.7" # x-release-please-version
__version__ = "1.22.2" # x-release-please-version


getLogger(__name__).addHandler(NullHandler())
115 changes: 92 additions & 23 deletions botbase/botbase.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
from __future__ import annotations

from asyncio import TimeoutError as AsyncTimeoutError
from asyncio import sleep, wait_for
from contextlib import suppress
from importlib import import_module
from logging import CRITICAL, INFO, Formatter, getLogger
from logging import CRITICAL, INFO, Formatter, getLogger, StreamHandler
from logging.handlers import RotatingFileHandler
from pathlib import Path
from random import choice
from sys import modules
from textwrap import dedent
from types import ModuleType
from typing import TYPE_CHECKING

from aiohttp import ClientSession
from asyncpg import create_pool
from nextcord import Embed, Interaction, Member, Thread, User, abc
from nextcord.ext.commands import AutoShardedBot, when_mentioned, when_mentioned_or
from nextcord.ext.commands import (
AutoShardedBot,
ExtensionNotFound,
when_mentioned,
when_mentioned_or,
)

from .blacklist import Blacklist
from .emojis import Emojis
Expand All @@ -26,7 +35,7 @@
)

if TYPE_CHECKING:
from typing import Any, Callable, Optional, Union
from typing import Any, Callable, Mapping, Optional, Union

from asyncpg import Pool
from nextcord import Guild, Message, PartialMessageable
Expand Down Expand Up @@ -72,21 +81,23 @@
"""


def get_handler():
def get_handlers():
formatter = Formatter(
"%(levelname)-7s %(asctime)s %(filename)12s:%(funcName)-28s: %(message)s",
datefmt="%H:%M:%S %d/%m/%Y",
)
h = RotatingFileHandler(
"./logs/bot/io.log",
maxBytes=1000000,
backupCount=5,
encoding="utf-8",
)
h.setFormatter(
Formatter(
"%(levelname)-7s %(asctime)s %(filename)12s:%(funcName)-28s: %(message)s",
datefmt="%H:%M:%S %d/%m/%Y",
)
)
i = StreamHandler()

i.setFormatter(formatter)
h.setFormatter(formatter)
h.namer = lambda name: name.replace(".log", "") + ".log"
return h
return h, i


class BotBase(AutoShardedBot):
Expand Down Expand Up @@ -141,9 +152,10 @@ def __init__(self, *args, config_module: str = "config", **kwargs) -> None:
log = getLogger()
log.handlers = []
log.setLevel(INFO)
h = get_handler()
h, i = get_handlers()

log.addHandler(h)
log.addHandler(i)
getLogger("asyncio").setLevel(CRITICAL)

self.loop.set_exception_handler(self.asyncio_handler)
Expand All @@ -158,9 +170,8 @@ def __init__(self, *args, config_module: str = "config", **kwargs) -> None:
self.db_enabled = True
self.db_args = (db_url,)
self.db_kwargs = {}
elif (
(db_name := getattr(config, "db_name", None))
and (db_user := getattr(config, "db_user", "ooliver"))
elif (db_name := getattr(config, "db_name", None)) and (
db_user := getattr(config, "db_user", "ooliver")
):
self.db_enabled = True
self.db_args = ()
Expand All @@ -169,6 +180,8 @@ def __init__(self, *args, config_module: str = "config", **kwargs) -> None:
"user": db_user,
"host": getattr(config, "db_host", None),
}
if port := getattr(config, "db_port", None):
self.db_kwargs["port"] = port
else:
self.db_enabled = False
self.db_args = ()
Expand All @@ -191,6 +204,7 @@ def __init__(self, *args, config_module: str = "config", **kwargs) -> None:
self.logchannel: int | None = getattr(config, "logchannel", None)
self.guild_ids: list[int] | None = getattr(config, "guild_ids", None)
self.database_init: str = initialise + getattr(config, "database_init", "")
self.name: Optional[str] = getattr(config, "name", None)

self._single_events: dict[str, Callable] = {
"on_message": self.get_wrapped_message,
Expand Down Expand Up @@ -231,11 +245,18 @@ def asyncio_handler(self, _, context: dict) -> None:
)
)

async def startup(self) -> None:
async def start(self, *args, **kwargs) -> None:
if self.db_enabled:
db = await create_pool(*self.db_args, **self.db_kwargs)
assert db is not None
self.db = db
for tries in range(5):
try:
db = await create_pool(*self.db_args, **self.db_kwargs)
assert db is not None
self.db = db
except AssertionError:
await sleep(2.5 * tries + 1)
else:
break

await self.db.execute(self.database_init)

if self.aiohttp_enabled:
Expand All @@ -244,9 +265,9 @@ async def startup(self) -> None:
if self.blacklist_enabled and self.db_enabled:
self.blacklist = Blacklist(self.db)

def run(self, *args, **kwargs) -> None:
self.loop.create_task(self.startup())
await super().start(*args, **kwargs)

def run(self, *args, **kwargs) -> None:
cog_dir = f"{self.mod}/cogs" if self.mod else "./cogs"
cogs = Path(cog_dir)

Expand All @@ -255,17 +276,21 @@ def run(self, *args, **kwargs) -> None:
if "extras" in ext.parts or any(part.startswith("_") for part in ext.parts):
continue
if ext.suffix == ".py":
a = str(ext).replace("/", ".")[:-3]
a = ".".join(ext.parts).removesuffix(".py")
log.info("Loading ext %s", a)
self.load_extension(a)
log.info("Loaded ext %s", a)

super().run(*args, **kwargs)

async def close(self, *args, **kwargs) -> None:
if self.aiohttp_enabled:
if self.aiohttp_enabled and hasattr(self, "session"):
await self.session.close()

if self.db_enabled and hasattr(self, "db"):
with suppress(AsyncTimeoutError):
await wait_for(self.db.close(), timeout=5)

await super().close(*args, **kwargs)

@staticmethod
Expand Down Expand Up @@ -531,3 +556,47 @@ async def on_guild_remove(self, guild: Guild):
await self.get_channel(self.logchannel).send(embed=embed) # type: ignore
except AttributeError:
pass

def load_extension(
self, name: str, *, extras: Optional[dict[str, Any]] = None
) -> None:
ext = f"{self.name}.cogs.{name}" if self.name else name

try:
super().load_extension(ext, extras=extras)
except (ExtensionNotFound, ModuleNotFoundError):
super().load_extension(name, extras=extras)

if self.is_ready():
self.loop.create_task(self.sync_all_application_commands())

def reload_extension(self, name: str) -> None:
ext = f"{self.name}.cogs.{name}" if self.name else name

try:
super().reload_extension(ext)
except (ExtensionNotFound, ModuleNotFoundError):
super().reload_extension(name)

if self.is_ready():
self.loop.create_task(self.sync_all_application_commands())

def unload_extension(self, name: str) -> None:
ext = f"{self.name}.cogs.{name}" if self.name else name

try:
super().unload_extension(ext)
except (ExtensionNotFound, ModuleNotFoundError):
super().unload_extension(name)

self.loop.create_task(self.sync_all_application_commands())

@property
def extensions(self) -> Mapping[str, ModuleType]:
if not self.name:
return super().extensions

return {
k.removeprefix(f"{self.name}.cogs."): v
for k, v in super().extensions.items()
} | super().extensions
5 changes: 2 additions & 3 deletions botbase/wraps/wrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
)
from nextcord.abc import Messageable
from nextcord.utils import utcnow
from nextcord.embeds import _EmptyEmbed

if TYPE_CHECKING:
from typing import Any
Expand Down Expand Up @@ -61,8 +60,8 @@ async def send_author_embed(self, text: str, **kwargs):

async def send_embed(
self,
title: str | _EmptyEmbed = Embed.Empty,
desc: str | _EmptyEmbed = Embed.Empty,
title: str | None = None,
desc: str | None = None,
*,
author: str | None = None,
image: str | None = None,
Expand Down
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "ooliver-botbase"
version = "1.20.7"
version = "1.22.2"
description = "A personal nextcord bot base package for bots."
authors = ["ooliver1 <[email protected]>"]
license = "MIT"
Expand All @@ -19,8 +19,8 @@ botbase = "botbase.cli:main"

[tool.poetry.dependencies]
python = "^3.8"
asyncpg = ">=0.25.0<0.26.0"
nextcord = ">=2.0.0-beta.2<3.0.0"
asyncpg = ">=0.25,<0.27"
nextcord = "^2.0.0"
nextcord-ext-menus = "^1.5.2"
jishaku = "2.4.0"
psutil = "^5.9.0"
Expand Down

0 comments on commit b045dfb

Please sign in to comment.