Compare commits

...

4 commits

11 changed files with 100 additions and 59 deletions

View file

@ -3,30 +3,43 @@
<words>
<w>anglais</w>
<w>appdirs</w>
<w>apres</w>
<w>asctime</w>
<w>commandstats</w>
<w>ctype</w>
<w>debian</w>
<w>découverte</w>
<w>fonction</w>
<w>francais</w>
<w>français</w>
<w>gnous</w>
<w>ipinfo</w>
<w>iplocalise</w>
<w>jishaku</w>
<w>langue</w>
<w>levelname</w>
<w>liste</w>
<w>localiseip</w>
<w>octobre</w>
<w>pacman</w>
<w>postgresql</w>
<w>pred</w>
<w>pylint</w>
<w>releaselevel</w>
<w>rprint</w>
<w>socketstats</w>
<w>soit</w>
<w>splt</w>
<w>suivante</w>
<w>systemd</w>
<w>tldr</w>
<w>tutux</w>
<w>tuxbot</w>
<w>tuxbot's</w>
<w>tuxvenv</w>
<w>venv</w>
<w>webhooks</w>
<w>écrite</w>
</words>
</dictionary>
</component>

View file

@ -2,6 +2,8 @@
good-names=
e, # (exception) as e
f, # (file) as f
k, # for k, v in
v, # for k, v in
[MASTER]
disable=

View file

@ -28,7 +28,7 @@ Arch Linux
$ sudo pacman -Syu python python-pip python-virtualenv git
Continue to `create the venv <#creating-the-virtual-environnement>`__.
Continue to `create the venv <#creating-the-virtual-environment>`__.
--------------
@ -40,7 +40,7 @@ Debian
$ sudo apt update
$ sudo apt -y install python3 python3-dev python3-pip python3-venv git
Continue to `create the venv <#creating-the-virtual-environnement>`__.
Continue to `create the venv <#creating-the-virtual-environment>`__.
--------------

View file

@ -17,13 +17,12 @@ python_requires = >=3.7
install_requires =
appdirs>=1.4.4
Babel>=2.8.0
black==1.4.4
black==20.8b1
discord.py==1.5.0
discord_flags==2.1.1
humanize==2.6.0
jishaku>=1.19.1.200
psutil>=5.7.2
pyyaml>=5.3.1
rich>=6.0.0
structured_config>=4.12

View file

@ -116,7 +116,7 @@ def debug_info() -> NoReturn:
table.add_row(f"[u]System arch:[/u] {os.uname().machine}")
table.add_row(f"[u]Kernel:[/u] {os.uname().release}")
table.add_row(f"[u]User:[/u] {os.getlogin()}")
table.add_row(f"[u]Uptime:[/u] {uptime[2]}")
table.add_row(f"[u]Uptime:[/u] {uptime[2][:-1]}")
table.add_row(
f"[u]Load Average:[/u] {' '.join(map(str, os.getloadavg()))}"
)

View file

@ -5,6 +5,8 @@ from discord.ext import commands
from tuxbot.core import checks
from tuxbot.core.bot import Tux
from tuxbot.core.config import set_for
from tuxbot.core.config import Config
from tuxbot.core.i18n import (
Translator,
find_locale,
@ -26,8 +28,8 @@ class Admin(commands.Cog, name="Admin"):
self.bot = bot
async def _save_lang(self, ctx: ContextPlus, lang: str):
await self.bot.config.update(
"core", f"guild.{ctx.guild.id}.locale", lang
set_for(
self.bot.config.Servers, ctx.guild.id, Config.Server, locale=lang
)
@group_extra(name="lang", aliases=["locale", "langue"], deletable=True)

View file

@ -15,7 +15,7 @@ from rich.traceback import install
from tuxbot import version_info
from . import Config, ConfigFile
from .config import Config, ConfigFile, search_for
from .data_manager import logs_data_path, data_path
from . import __version__, ExitCodes
@ -189,9 +189,11 @@ class Tux(commands.AutoShardedBot):
return
if (
self.config.Servers.all[message.guild.id].blacklisted
or self.config.Channels.all[message.channel.id].blacklisted
or self.config.Users.all[message.author.id].blacklisted
search_for(self.config.Servers, message.guild.id, "blacklisted")
or search_for(
self.config.Channels, message.channel.id, "blacklisted"
)
or search_for(self.config.Users, message.author.id, "blacklisted")
):
return
@ -200,9 +202,8 @@ class Tux(commands.AutoShardedBot):
if ctx is None or ctx.valid is False:
self.dispatch("message_without_command", message)
else:
if (
ctx.command
in self.config.Servers.all[message.guild.id].disabled_command
if ctx.command in search_for(
self.config.Servers, message.guild.id, "disabled_command", []
):
raise exceptions.DisabledCommandByServerOwner

View file

@ -1,5 +1,5 @@
import logging
from typing import List, Dict
from typing import List, Dict, Any
from structured_config import (
Structure,
IntField,
@ -9,39 +9,35 @@ from structured_config import (
)
__all__ = ["Config", "ConfigFile"]
__all__ = ["Config", "ConfigFile", "search_for", "set_for"]
log = logging.getLogger("tuxbot.core.config")
class Server(Structure):
prefixes: List[str] = []
disabled_command: List[str] = []
locale: str = StrField("")
blacklisted: bool = BoolField(False)
class Channel(Structure):
disabled_command: List[str] = []
locale: str = StrField("")
blacklisted: bool = BoolField(False)
class User(Structure):
aliases: List[dict] = []
locale: str = StrField("")
blacklisted: bool = BoolField(False)
class Config(Structure):
class Servers(Structure):
all: Dict[int, Server] = {}
class Server(Structure):
prefixes: List[str] = []
disabled_command: List[str] = []
locale: str = StrField("")
blacklisted: bool = BoolField(False)
class Channels(Structure):
all: Dict[int, Channel] = {}
class Channel(Structure):
disabled_command: List[str] = []
locale: str = StrField("")
blacklisted: bool = BoolField(False)
class Users(Structure):
all: Dict[int, User] = {}
class User(Structure):
aliases: List[dict] = []
locale: str = StrField("")
blacklisted: bool = BoolField(False)
class Cog(Structure):
pass
Servers: Dict[int, Server] = {}
Channels: Dict[int, Channel] = {}
Users: Dict[int, User] = {}
Cogs: Dict[str, Cog] = {}
class Core(Structure):
owners_id: List[int] = []
@ -51,9 +47,6 @@ class Config(Structure):
locale: str = StrField("")
disabled_command: List[str] = []
class Cogs(Structure):
pass
# =============================================================================
# Configuration of Tuxbot Application (not the bot)
@ -67,3 +60,24 @@ class AppConfig(Structure):
last_run: int = IntField(0)
instances: Dict[str, Instance] = {}
# =============================================================================
# Useful functions to interact with configs
# =============================================================================
def search_for(config, key, value, default=False) -> Any:
if key in config:
return getattr(config[key], value)
return default
# la fonction suivante a été écrite le lundi 19 octobre 2020 à 13h49 soit 1h
# apres la découverte de mon chat, rip roxy, 201?-2020 :'(
def set_for(config, key, ctype, **values) -> Any:
if key not in config:
config[key] = ctype()
for k, v in values.items():
setattr(config[key], k, v)

View file

@ -6,6 +6,7 @@ from typing import Callable, Union, Dict, List
from babel.messages.pofile import read_po
from tuxbot.core import Config
from tuxbot.core.config import search_for
from tuxbot.core.utils.functions.extra import ContextPlus
log = logging.getLogger("tuxbot.core.i18n")
@ -59,12 +60,19 @@ class Translator(Callable[[str], str]):
self, untranslated: str, ctx: ContextPlus, config: Config
) -> str:
try:
locale = config.get_value(
"core",
f"guild.{ctx.guild.id}.locale",
config.get_value("core", "locale"),
user_locale = search_for(
config.Users, ctx.author.id, "locale", None
)
return self.translations[locale][untranslated]
if user_locale:
return self.translations[user_locale][untranslated]
guild_locale = search_for(
config.Servers, ctx.guild.id, "locale", None
)
if guild_locale:
return self.translations[guild_locale][untranslated]
return self.translations[config.Core.locale][untranslated]
except KeyError:
return untranslated

View file

@ -1,5 +1,4 @@
import asyncio
import yaml
import discord
from discord import Embed
@ -9,20 +8,23 @@ from rich.console import Console
console = Console()
console.clear()
TOKEN_REPLACEMENT = "whoops, leaked token"
class ContextPlus(commands.Context):
async def send(self, content=None, *args, **kwargs):
if content is not None:
content = content.replace(
self.bot.config("core").get("token"), "<token>"
self.bot.config.Core.token, TOKEN_REPLACEMENT
)
if kwargs.get("embed"):
e = str(kwargs.get("embed").to_dict())
e = e.replace(self.bot.config("core").get("token"), "<token>")
e = yaml.load(e, Loader=yaml.FullLoader)
kwargs["embed"] = Embed.from_dict(e)
embed = kwargs.get("embed").to_dict()
for key, value in embed.items():
if isinstance(value, (str, bytes)):
embed[key] = value.replace(
self.bot.config.Core.token, TOKEN_REPLACEMENT
)
kwargs["embed"] = Embed.from_dict(embed)
if (
hasattr(self.command, "deletable") and self.command.deletable

View file

@ -2,10 +2,10 @@ from typing import List
import discord
from tuxbot.core.bot import Tux
from tuxbot.core.config import search_for
def get_prefixes(tux: Tux, guild: discord.Guild) -> List[str]:
def get_prefixes(tux, guild: discord.Guild) -> List[str]:
"""Get custom prefixes for one guild.
Parameters
----------
@ -19,4 +19,4 @@ def get_prefixes(tux: Tux, guild: discord.Guild) -> List[str]:
List[str]
List of all prefixes.
"""
return tux.config.Servers.all[guild.id].prefixes or []
return search_for(tux.config.Servers, guild.id, "prefixes", [])