feat(config): add Config object

This commit is contained in:
Romain J 2020-06-04 19:16:51 +02:00
parent ec68280519
commit b5b7f0c7ef
5 changed files with 122 additions and 69 deletions

View file

@ -5,6 +5,7 @@
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/tuxbot/__main__.py" beforeDir="false" afterPath="$PROJECT_DIR$/tuxbot/__main__.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/tuxbot/core/bot.py" beforeDir="false" afterPath="$PROJECT_DIR$/tuxbot/core/bot.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/tuxbot/core/config.py" beforeDir="false" afterPath="$PROJECT_DIR$/tuxbot/core/config.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/tuxbot/core/data_manager.py" beforeDir="false" afterPath="$PROJECT_DIR$/tuxbot/core/data_manager.py" afterDir="false" />
</list>
<list id="a3abf5c0-7587-46e4-8f09-88e34a1ab8a4" name="5ed41911b012e33f68a07e7a i18n" comment="" />
@ -95,6 +96,7 @@
</task>
<task id="5ed41911b012e33f68a07e7a" summary="i18n">
<changelist id="a3abf5c0-7587-46e4-8f09-88e34a1ab8a4" name="5ed41911b012e33f68a07e7a i18n" comment="" />
<created>1591290805787</created>
<option name="issue" value="true" />
<url>https://trello.com/c/vK0cBbF2/38-i18n</url>
<option name="number" value="38" />
@ -106,6 +108,7 @@
</task>
<task active="true" id="5ed57ed9960f35191182a924" summary="core">
<changelist id="c97c8a30-7573-4dcd-a0d4-5bf94b8ddbbd" name="5ed57ed9960f35191182a924 core" comment="" />
<created>1591290805787</created>
<option name="issue" value="true" />
<url>https://trello.com/c/SafaMBht/40-core</url>
<option name="number" value="40" />
@ -115,7 +118,7 @@
<workItem from="1591054878071" duration="1039000" />
<workItem from="1591088657371" duration="4107000" />
<workItem from="1591128560850" duration="40267000" />
<workItem from="1591281151234" duration="150000" />
<workItem from="1591281151234" duration="9745000" />
</task>
<option name="localTasksCounter" value="2" />
<option name="createBranch" value="false" />

View file

@ -6,8 +6,8 @@ import logging
import platform
import signal
import sys
from typing import NoReturn
from argparse import Namespace
from typing import NoReturn
import discord
import pip
@ -109,6 +109,11 @@ def parse_cli_flags(args: list) -> Namespace:
action="store_true",
help="List all instance names"
)
parser.add_argument(
"--token", "-T",
type=str,
help="Run Tuxbot with passed token"
)
parser.add_argument(
"instance_name", nargs="?",
help="Name of the bot instance created during `tuxbot-setup`."
@ -128,7 +133,7 @@ async def shutdown_handler(tux: Tux, signal_type, exit_code=None) -> NoReturn:
----------
tux:Tux
Object for the bot.
signal_type:int
signal_type:int, None
Exiting signal code.
exit_code:None|int
Code to show when exiting.
@ -174,7 +179,7 @@ async def run_bot(tux: Tux, cli_flags: Namespace) -> None:
data_path = data_manager.data_path(tux.instance_name)
tuxbot.logging.init_logging(
level=cli_flags.logging_level,
10,
location=data_path / "logs"
)
@ -184,14 +189,14 @@ async def run_bot(tux: Tux, cli_flags: Namespace) -> None:
if cli_flags.token:
token = cli_flags.token
else:
token = await tux.config.token()
token = tux.config('core').get('token')
if not token:
log.critical("Token must be set if you want to login.")
sys.exit(1)
try:
await tux.start(token, bot=True, cli_flags=cli_flags)
await tux.start(token, bot=True)
except discord.LoginFailure:
log.critical("This token appears to be valid.")
sys.exit(1)

View file

@ -1,11 +1,30 @@
import logging
from pathlib import Path
from typing import List
import discord
from colorama import Fore, Style, init
from discord.ext import commands
from . import Config
from . import data_manager
from .utils.functions.cli import bordered
__all__ = ["Tux"]
from . import __version__
log = logging.getLogger("tuxbot")
init()
NAME = r"""
_____ _ _ _ _
|_ _| ___ _| |__ ___ | |_ | |__ ___ | |_
| || | | \ \/ / '_ \ / _ \| __|____| '_ \ / _ \| __|
| || |_| |> <| |_) | (_) | ||_____| |_) | (_) | |_
|_| \__,_/_/\_\_.__/ \___/ \__| |_.__/ \___/ \__|
"""
l_extensions: List[str] = [
"jishaku"
]
class Tux(commands.AutoShardedBot):
@ -17,34 +36,17 @@ class Tux(commands.AutoShardedBot):
self.instance_name = self.cli_flags.instance_name
self.last_exception = None
self.config = Config(
data_manager.data_path(self.instance_name)
)
self.config.register_global(
token=None,
prefix=[],
owner=None,
whitelist=[],
blacklist=[],
locale="en-US",
embeds=True,
color=0x6E83D1,
disabled_commands=[]
)
self.config.register_guild(
prefix=[],
whitelist=[],
blacklist=[],
locale="en-US",
admin_role=[],
mod_role=[],
embeds=None,
ignored=False,
disabled_commands=[]
)
self.config.register_channel(
ignored=False
)
self.config = Config(self.instance_name)
async def _prefixes(bot, message) -> List[str]:
prefixes = self.config.get_prefixes(message.guild)
if self.config('core').get('mentionable'):
return commands.when_mentioned_or(*prefixes)(bot, message)
return prefixes
if "command_prefix" not in kwargs:
kwargs["command_prefix"] = _prefixes
if "owner_ids" in kwargs:
kwargs["owner_ids"] = set(kwargs["owner_ids"])
@ -58,8 +60,34 @@ class Tux(commands.AutoShardedBot):
self.uptime = None
self.main_dir = bot_dir
print(str(self.cli_flags), self.instance_name, self.config, self.owner_ids, self.main_dir)
exit()
super().__init__(*args, help_command=None, **kwargs)
async def on_ready(self):
INFO = {
'title': "INFO",
'rows': [
str(self.user),
f"Prefixes: {', '.join(self.config('core').get('prefixes'))}",
f"Language: {self.config('core').get('locale')}",
f"Tuxbot Version: {__version__}",
f"Discord.py Version: {discord.__version__}",
f"Shards: {self.shard_count}",
f"Servers: {len(self.guilds)}",
f"Users: {len(self.users)}"
]
}
COGS = {
'title': "COGS",
'rows': []
}
for extension in l_extensions:
COGS['rows'].append(
f"[{'X' if extension in self.extensions else ' '}] {extension}"
)
print(Fore.LIGHTBLUE_EX + NAME)
print(Style.RESET_ALL)
print(bordered(INFO, COGS))
print(f"\n{'=' * 118}\n\n")

View file

@ -1,41 +1,55 @@
from pathlib import Path
from typing import Any, NoReturn
import json
import logging
__all__ = ["Config"]
from typing import List, Dict
import discord
from tuxbot.core.data_manager import data_path
log = logging.getLogger("tuxbot.config")
class Config:
GLOBAL = "GLOBAL"
GUILD = "GUILD"
CHANNEL = "TEXT_CHANNEL"
ROLE = "ROLE"
MEMBER = "MEMBER"
USER = "USER"
def __init__(
self,
cog_instance: str = None
):
self._cog_instance = cog_instance
def __init__(self, config_dir: Path):
self._defaults = {}
def __getitem__(self, item) -> Dict:
path = data_path(self._cog_instance)
def __getattr__(self, item: str) -> dict:
return getattr(self._defaults, item)
if item != 'core':
path = path / 'cogs' / item
else:
path /= 'core'
def _register_default(self, key: str, **kwargs: Any):
...
settings_file = path / 'settings.json'
def register_core(self, **kwargs) -> NoReturn:
self._register_default(self.GUILD, **kwargs)
if not settings_file.exists():
raise FileNotFoundError(f"Unable to find settings file "
f"'{settings_file}'")
else:
with settings_file.open('r') as f:
return json.load(f)
def register_global(self, **kwargs) -> NoReturn:
self._register_default(self.GLOBAL, **kwargs)
def __call__(self, item):
return self.__getitem__(item)
def register_guild(self, **kwargs) -> NoReturn:
self._register_default(self.GUILD, **kwargs)
def owner_ids(self) -> List[int]:
return self.__getitem__('core').get('owner_ids')
def register_channel(self, **kwargs) -> NoReturn:
self._register_default(self.CHANNEL, **kwargs)
def token(self) -> str:
return self.__getitem__('core').get('token')
def register_role(self, **kwargs) -> NoReturn:
self._register_default(self.ROLE, **kwargs)
def get_prefixes(self, guild: discord.Guild) -> List[str]:
core = self.__getitem__('core')
prefixes = core\
.get('guild', {}) \
.get(guild.id, {}) \
.get('prefixes', [])
def register_member(self, **kwargs) -> NoReturn:
self._register_default(self.MEMBER, **kwargs)
def register_user(self, **kwargs) -> NoReturn:
self._register_default(self.USER, **kwargs)
return prefixes

View file

@ -1,7 +1,10 @@
import logging
from pathlib import Path
import appdirs
log = logging.getLogger("tuxbot.data_manager")
app_dir = appdirs.AppDirs("Tuxbot-bot")
config_dir = Path(app_dir.user_config_dir)
config_file = config_dir / "config.json"