55import pathlib
66import typing
77
8+ import yaml
89import asyncpg
910import discord
1011from discord .ext import commands
1112from discord .ext .commands import AutoShardedBot , Bot , when_mentioned_or
1213
1314from SideBot .db .tags import Tag
1415
15- from .utils import ButtonLink , DiscordUser
16+ from .utils import ButtonLink , DiscordUser , BotConfig
1617
1718
1819class SideBot (Bot ):
1920 """Custom SideBot class to simplify start up."""
2021
2122 def __init__ (self , config : dict [str , str ]) -> None :
2223 """Initialize the bot with the given configuration."""
23- self .__tok = config .pop ("DTOKEN" )
24- self .config = config
24+ self .config = BotConfig .from_dict (config )
2525 self .logger = logging .getLogger (__name__ )
2626
2727 intents = discord .Intents .all ()
@@ -31,16 +31,16 @@ def __init__(self, config: dict[str, str]) -> None:
3131 intents = intents ,
3232 )
3333
34- self .owner_id = int ( self .config [ "OWNER" ])
35- self .conf_cogs = self .config [ "COGS" ]. split ( "," )
34+ self .owner_id = self .config . owner
35+ self .conf_cogs = self .config . cogs
3636
3737 async def setup_connection (self ) -> asyncpg .Connection :
3838 """Set up the database connection."""
39- return await asyncpg .connect (self .config [ "DATABASE_URL" ] )
39+ return await asyncpg .connect (self .config . db_url )
4040
4141 async def setup_hook (self ) -> None :
4242 """Set up cogs and app commands."""
43- for cog in self .conf_cogs :
43+ for cog in self .config . cogs :
4444 await self .load_extension (f"SideBot.cogs.{ cog } " )
4545 self .logger .debug (self .extensions )
4646 self .logger .debug (self .tree .get_commands ())
@@ -55,6 +55,7 @@ async def on_ready(self) -> None:
5555 self .user .id ,
5656 )
5757 self .connection : asyncpg .Connection = await self .setup_connection ()
58+ self .logger .info ("Connected to postgresql!" )
5859
5960 await Tag .write_schema (self .connection )
6061
@@ -94,14 +95,9 @@ def run(
9495 """Run the bot with the given token."""
9596 if token :
9697 return super ().run (token , * args , root_logger = True , ** kwargs )
97- return super ().run (self .__tok , * args , root_logger = True , ** kwargs )
98+ return super ().run (self .config . token , * args , root_logger = True , ** kwargs )
9899
99100 @classmethod
100- def from_env (cls , path : str = ".env" ) -> "SideBot" :
101- """Load the bot from a .env file with the proper configuration."""
102- with pathlib .Path (path ).open (encoding = "utf-8" ) as env :
103- conf = {
104- k : v for line in env if (k := line .strip ().split ("=" , 1 )[0 ]) and (v := line .strip ().split ("=" , 1 )[1 ])
105- }
106-
107- return cls (conf )
101+ def from_yaml_file (cls , path : str = "conf.yaml" ) -> "SideBot" :
102+ with open (path , 'r' ) as f :
103+ return cls (yaml .safe_load (f ))
0 commit comments