Skip to content

Commit

Permalink
feat(breaking): add yaml parsing + helper classes
Browse files Browse the repository at this point in the history
- move whole project's directory
- remove old env file parsing
  • Loading branch information
nythepegasus committed Jan 10, 2025
1 parent 5cd4307 commit 53eaeee
Show file tree
Hide file tree
Showing 15 changed files with 151 additions and 64 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ dist/
build/
.venv
.env*
conf.yaml
tags
__pycache__
*.egg-info/
Expand Down
28 changes: 12 additions & 16 deletions src/SideBot/__init__.py → SideBot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,23 @@
import pathlib
import typing

import yaml
import asyncpg
import discord
from discord.ext import commands
from discord.ext.commands import AutoShardedBot, Bot, when_mentioned_or

from SideBot.db.tags import Tag

from .utils import ButtonLink, DiscordUser
from .utils import ButtonLink, DiscordUser, BotConfig


class SideBot(Bot):
"""Custom SideBot class to simplify start up."""

def __init__(self, config: dict[str, str]) -> None:
"""Initialize the bot with the given configuration."""
self.__tok = config.pop("DTOKEN")
self.config = config
self.config = BotConfig.from_dict(config)
self.logger = logging.getLogger(__name__)

intents = discord.Intents.all()
Expand All @@ -31,16 +31,16 @@ def __init__(self, config: dict[str, str]) -> None:
intents=intents,
)

self.owner_id = int(self.config["OWNER"])
self.conf_cogs = self.config["COGS"].split(",")
self.owner_id = self.config.owner
self.conf_cogs = self.config.cogs

async def setup_connection(self) -> asyncpg.Connection:
"""Set up the database connection."""
return await asyncpg.connect(self.config["DATABASE_URL"])
return await asyncpg.connect(self.config.db_url)

async def setup_hook(self) -> None:
"""Set up cogs and app commands."""
for cog in self.conf_cogs:
for cog in self.config.cogs:
await self.load_extension(f"SideBot.cogs.{cog}")
self.logger.debug(self.extensions)
self.logger.debug(self.tree.get_commands())
Expand All @@ -55,6 +55,7 @@ async def on_ready(self) -> None:
self.user.id,
)
self.connection: asyncpg.Connection = await self.setup_connection()
self.logger.info("Connected to postgresql!")

await Tag.write_schema(self.connection)

Expand Down Expand Up @@ -94,14 +95,9 @@ def run(
"""Run the bot with the given token."""
if token:
return super().run(token, *args, root_logger=True, **kwargs)
return super().run(self.__tok, *args, root_logger=True, **kwargs)
return super().run(self.config.token, *args, root_logger=True, **kwargs)

@classmethod
def from_env(cls, path: str = ".env") -> "SideBot":
"""Load the bot from a .env file with the proper configuration."""
with pathlib.Path(path).open(encoding="utf-8") as env:
conf = {
k: v for line in env if (k := line.strip().split("=", 1)[0]) and (v := line.strip().split("=", 1)[1])
}

return cls(conf)
def from_yaml_file(cls, path: str = "conf.yaml") -> "SideBot":
with open(path, 'r') as f:
return cls(yaml.safe_load(f))
2 changes: 1 addition & 1 deletion src/SideBot/__main__.py → SideBot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

from . import SideBot

SideBot.from_env().run()
SideBot.from_yaml_file().run()
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
120 changes: 120 additions & 0 deletions SideBot/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""utilites for SideBot."""

import discord


class DBConfig:
"""DBConfig class for Postgresql with Bot"""
__slot__ = ('user', 'password', 'host', 'port', 'name')

def __init__(
self,
user: str,
password: str,
host: str,
port: int | None = None,
name: str | None = None
):
self.user = user
self.password = password
self.host = host
self.port = port or 5432
self.name = name or user

@property
def connect_str(self):
return f"postgresql://{self.user}:{self.password}@{self.host}:{self.port}/{self.name}"

@property
def as_dict(self):
return {
'user': self.user,
'pass': self.password,
'host': self.host,
'port': self.port,
'name': self.name,
}

@classmethod
def from_dict(cls, data: dict):
return cls(
data['user'],
data['pass'],
data['host'],
data['port'] if 'port' in data else None,
data['name'] if 'name' in data else data['user']
)

class BotConfig:
"""BotConfig class for SideBot"""
__slots__ = ('token', 'owner', 'db_url', 'cogs')

def __init__(
self,
token: str,
owner: int,
db_url: str,
cogs: list[str]
):
self.token = token
self.owner = owner
self.db_url = db_url
self.cogs = cogs

@classmethod
def from_dict(cls, data: dict):
if 'botDB' in data:
return cls(
data['discordToken'],
data['owner'],
DBConfig.from_dict(data['botDB']).connect_str,
data['cogs']
)
return cls(
data['discordToken'],
data['owner'],
data['botDBURL'],
data['cogs']
)


class DiscordUser:
"""DiscordUser class."""

def __init__(self, iden: int, name: str) -> None:
"""DiscordUser class."""
self.id = iden
self.name = name

def to_tuple(self) -> tuple[int, str]:
"""Convert to tuple."""
return self.id, self.name

@classmethod
def from_tuple(cls, user: tuple[int, str]) -> "DiscordUser":
"""Convert from tuple."""
return cls(*user)

@classmethod
def from_dpy_user(cls, user: discord.User | discord.Member) -> "DiscordUser":
"""Convert from discord.py User."""
return cls(user.id, user.name)


class ButtonLink:
"""ButtonLink class."""

def __init__(self, label: str, url: str) -> None:
"""ButtonLink class."""
self.label = label
self.url = url

@classmethod
def to_tuple(cls, button: "ButtonLink") -> tuple[str, str]:
"""Convert to tuple."""
return button.label, button.url

@classmethod
def from_tuple(cls, button: tuple[str, str]) -> "ButtonLink":
"""Convert from tuple."""
return cls(*button)
16 changes: 16 additions & 0 deletions conf.yaml.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
owner: 195864152856723456
cogs:
- admin
- developer
- tags
- utility
discordToken: 111111111111111111111111111111111111111111111111111111111111111111111111
botDBURL: postgresql://sidebot:[email protected]:5432/sidebot
# or
botDB:
user: sidebot
pass: password
host: 127.0.0.1
# Optional
port: 5432
name: sidebot
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ description = "SideBot is a multipurpose bot for the SideStore community."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"discord.py>=2.3.2",
"discord.py>=2.4.0",
"asyncpg>=0.29.0",
"openai>=1.37.0",
]
Expand Down
46 changes: 0 additions & 46 deletions src/SideBot/utils/__init__.py

This file was deleted.

0 comments on commit 53eaeee

Please sign in to comment.