From 078dc075f267c8c6cbc50529cf1bfd1eb3562907 Mon Sep 17 00:00:00 2001 From: Romain J Date: Wed, 3 Jun 2020 01:07:43 +0200 Subject: [PATCH] refactor(all): start from new feat(doc): add readme file --- app.py | 181 ------------------ cogs/Useless.py | 33 ---- configs/bot/blacklist.json | 5 - configs/bot/protected.py | 9 - configs/bot/settings.py.example | 48 ----- configs/bot/whitelist.json | 3 - requirements.txt | 11 -- version.py => tuxbot/__init__.py | 4 +- tuxbot/__main__.py | 2 + tuxbot/cogs/images/__init__.py | 5 + .../Images.py => tuxbot/cogs/images/images.py | 5 - tuxbot/cogs/logs/__init__.py | 14 ++ cogs/Logs.py => tuxbot/cogs/logs/logs.py | 9 - tuxbot/cogs/network/__init__.py | 5 + .../cogs/network/network.py | 5 - tuxbot/core/__init__.py | 8 + tuxbot/core/bot.py | 41 ++++ tuxbot/core/config.py | 41 ++++ {models => tuxbot/core/models}/__init__.py | 0 {utils => tuxbot/core/utils}/functions/cli.py | 0 .../core/utils}/functions/extra.py | 0 tuxbot/setup.py | 2 + 22 files changed, 120 insertions(+), 311 deletions(-) delete mode 100644 app.py delete mode 100644 cogs/Useless.py delete mode 100644 configs/bot/blacklist.json delete mode 100644 configs/bot/protected.py delete mode 100644 configs/bot/settings.py.example delete mode 100644 configs/bot/whitelist.json delete mode 100644 requirements.txt rename version.py => tuxbot/__init__.py (90%) create mode 100644 tuxbot/__main__.py create mode 100644 tuxbot/cogs/images/__init__.py rename cogs/Images.py => tuxbot/cogs/images/images.py (99%) create mode 100644 tuxbot/cogs/logs/__init__.py rename cogs/Logs.py => tuxbot/cogs/logs/logs.py (98%) create mode 100644 tuxbot/cogs/network/__init__.py rename cogs/Network.py => tuxbot/cogs/network/network.py (98%) create mode 100644 tuxbot/core/__init__.py create mode 100644 tuxbot/core/bot.py create mode 100644 tuxbot/core/config.py rename {models => tuxbot/core/models}/__init__.py (100%) rename {utils => tuxbot/core/utils}/functions/cli.py (100%) rename {utils => tuxbot/core/utils}/functions/extra.py (100%) create mode 100644 tuxbot/setup.py diff --git a/app.py b/app.py deleted file mode 100644 index 1dbf4f0..0000000 --- a/app.py +++ /dev/null @@ -1,181 +0,0 @@ -import contextlib -import datetime -import logging -from collections import Counter -from typing import List - -import aiohttp -import discord -from colorama import Fore, Style, init -from discord.ext import commands - -from configs.bot import settings -from utils.functions.cli import bordered -from utils.functions.extra import ContextPlus, get_prefix, \ - get_owners, get_blacklist -from version import __version__ - -log = logging.getLogger(__name__) -init() - -NAME = r""" - _____ _ _ _ _ - |_ _| ___ _| |__ ___ | |_ | |__ ___ | |_ - | || | | \ \/ / '_ \ / _ \| __|____| '_ \ / _ \| __| - | || |_| |> <| |_) | (_) | ||_____| |_) | (_) | |_ - |_| \__,_/_/\_\_.__/ \___/ \__| |_.__/ \___/ \__| -""" - -l_extensions: List[str] = [ - "jishaku", - "cogs.Logs", - "cogs.Images", - "cogs.Network", - "cogs.Useless", -] - - -class TuxBot(commands.AutoShardedBot): - logs_channels: dict - session: aiohttp.ClientSession - command_stats: Counter = Counter() - socket_stats: Counter = Counter() - - def __init__(self): - self.uptime = datetime.datetime.utcnow() - self._config = settings - self.locale = self._config.default_locale - - super().__init__( - command_prefix=get_prefix, - case_insensitive=True - ) - - self.logs_channels = { - "dm": self._config.logs["dm"], - "mentions": self._config.logs["mentions"], - "guilds": self._config.logs["guilds"], - "errors": self._config.logs["errors"], - "gateway": self._config.logs["gateway"], - } - - for extension in l_extensions: - try: - self.load_extension(extension) - except Exception as e: - log.warning(f"{type(e).__name__}: {e}") - - async def is_owner(self, user: discord.User): - return user.id in get_owners() - - async def on_ready(self): - INFO = { - 'title': "INFO", - 'rows': [ - str(self.user), - f"Prefixes: {', '.join(self._config.prefixes)}", - f"Language: {self.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") - - async def on_resumed(self): - print(f"resumed... {self.uptime}") - - async def get_context(self, message: discord.Message, *, cls=None): - return await super().get_context(message, cls=ContextPlus) - - async def on_message(self, message: discord.Message): - if message.author.bot: - return - - if message.author.id in get_blacklist()['users'] \ - or message.channel.id in get_blacklist()['channels'] \ - or (message.channel.guild - and message.channel.guild.id in get_blacklist()['guilds']): - return - - try: - await self.process_commands(message) - except Exception as e: - print(f"{type(e).__name__}: {e}") - - async def bot_logout(self): - await super().logout() - await self.session.close() - - async def bot_start(self): - self.session = aiohttp.ClientSession(loop=self.loop) - await self.login(self._config.token, bot=True) - await self.connect() - - def run(self): - loop = self.loop - - # loop.run_until_complete( - # Tortoise.init( - # db_url=self._config.postgresql, - # modules={ - # "models": [ - # "models.__init__" - # ] - # } - # ) - # ) - # loop.run_until_complete(Tortoise.generate_schemas()) - - try: - loop.run_until_complete(self.bot_start()) - except KeyboardInterrupt: - loop.run_until_complete(self.bot_logout()) - - -@contextlib.contextmanager -def setup_logging(): - logging.getLogger('discord').setLevel(logging.INFO) - logging.getLogger('discord.http').setLevel(logging.WARNING) - - logger = logging.getLogger() - logger.setLevel(logging.INFO) - - try: - handler = logging.FileHandler(filename='tuxbot.log', - encoding='utf-8', mode='w') - fmt = logging.Formatter('[{levelname:<7}] [{asctime}]' - ' {name}: {message}', - '%Y-%m-%d %H:%M:%S', style='{') - - handler.setFormatter(fmt) - logger.addHandler(handler) - - yield - finally: - handlers = logger.handlers[:] - for handler in handlers: - handler.close() - logger.removeHandler(handler) - - -if __name__ == "__main__": - tutux = TuxBot() - with setup_logging(): - tutux.run() diff --git a/cogs/Useless.py b/cogs/Useless.py deleted file mode 100644 index 4788727..0000000 --- a/cogs/Useless.py +++ /dev/null @@ -1,33 +0,0 @@ -import logging - -from discord.ext import commands - -from app import TuxBot -from utils.functions.extra import ContextPlus, command_extra - -log = logging.getLogger(__name__) - - -class Useless(commands.Cog, name="Useless"): - def __init__(self, bot): - self.bot = bot - - @command_extra(name="space") - @commands.cooldown(1, 5, commands.BucketType.user) - async def _space(self, ctx: ContextPlus): - await ctx.send(""" - > ˚              *                        .              .            ✦              ‍ ‍ ‍ ‍                  ,       - > - > .             .   ゚      .             . - > - >       ,       .                                  :sunny:                                                        .           .             .                                                                                        ✦        ,               :rocket:        ,    ‍ ‍ ‍ ‍               .            .                                             ˚            ,                                       .                      .             .               *            ✦                                               .                  .           .        .     :new_moon:              .           .               - > - >  ˚                     ゚     .               .      :earth_americas: ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ,                * .                    .           ✦             ˚                                      .              . .           ✦             ˚                                      .              .            ✦              ‍ ‍ ‍ ‍                  ,       - > - > .             .   ゚      .             . - """) - - -def setup(bot: TuxBot): - cog = Useless(bot) - bot.add_cog(cog) diff --git a/configs/bot/blacklist.json b/configs/bot/blacklist.json deleted file mode 100644 index cbbe594..0000000 --- a/configs/bot/blacklist.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "channels": [], - "guilds": [], - "users": [] -} \ No newline at end of file diff --git a/configs/bot/protected.py b/configs/bot/protected.py deleted file mode 100644 index 274a5ed..0000000 --- a/configs/bot/protected.py +++ /dev/null @@ -1,9 +0,0 @@ -from .settings import token, postgresql, logs, ipinfo - -protected = [ - token, str(list(token)), - postgresql, str(list(postgresql)), - *[channel.get('webhook').get('token') for channel in logs.values()], - ipinfo -] - diff --git a/configs/bot/settings.py.example b/configs/bot/settings.py.example deleted file mode 100644 index 84df70b..0000000 --- a/configs/bot/settings.py.example +++ /dev/null @@ -1,48 +0,0 @@ -token = "" -prefixes = ["drw."] -default_locale = "en-US" - -main_guild = int - -logs = { - "gateway": { - 'channel': int, - 'webhook': { - 'id': int, - 'token': '' - } - }, - "dm": { - 'channel': int, - 'webhook': { - 'id': int, - 'token': '' - } - }, - "mentions": { - 'channel': int, - 'webhook': { - 'id': int, - 'token': '' - } - }, - "guilds": { - 'channel': int, - 'webhook': { - 'id': int, - 'token': '' - } - }, - "errors": { - 'channel': int, - 'webhook': { - 'id': int, - 'token': '' - } - }, -} - -postgresql = 'postgres://tuxbot:tuxbot@localhost:5432/tuxbot-rewrite' - -# https://ipinfo.io/ -ipfinfo = '' \ No newline at end of file diff --git a/configs/bot/whitelist.json b/configs/bot/whitelist.json deleted file mode 100644 index 83434f3..0000000 --- a/configs/bot/whitelist.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "owners": [269156684155453451] -} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index c47fc47..0000000 --- a/requirements.txt +++ /dev/null @@ -1,11 +0,0 @@ -discord.py -discord-flags -asyncpg -tortoise-orm -requests -ipinfo -ipwhois -humanize -psutil -aiohttp -colorama \ No newline at end of file diff --git a/version.py b/tuxbot/__init__.py similarity index 90% rename from version.py rename to tuxbot/__init__.py index 104307b..2f9deab 100644 --- a/version.py +++ b/tuxbot/__init__.py @@ -1,7 +1,7 @@ import subprocess from collections import namedtuple -build = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'])\ +build = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']) \ .decode() VersionInfo = namedtuple('VersionInfo', 'major minor micro releaselevel build') @@ -10,5 +10,5 @@ version_info = VersionInfo( releaselevel='alpha', build=build ) -__version__ = "v{}.{}.{}"\ +__version__ = "v{}.{}.{}" \ .format(version_info.major, version_info.minor, version_info.micro) \ No newline at end of file diff --git a/tuxbot/__main__.py b/tuxbot/__main__.py new file mode 100644 index 0000000..f26f22d --- /dev/null +++ b/tuxbot/__main__.py @@ -0,0 +1,2 @@ +def main(): + ... diff --git a/tuxbot/cogs/images/__init__.py b/tuxbot/cogs/images/__init__.py new file mode 100644 index 0000000..516710a --- /dev/null +++ b/tuxbot/cogs/images/__init__.py @@ -0,0 +1,5 @@ +from .images import Images + + +def setup(bot): + bot.add_cog(Images(bot)) diff --git a/cogs/Images.py b/tuxbot/cogs/images/images.py similarity index 99% rename from cogs/Images.py rename to tuxbot/cogs/images/images.py index bcb1957..d1bf8d4 100644 --- a/cogs/Images.py +++ b/tuxbot/cogs/images/images.py @@ -173,8 +173,3 @@ class Images(commands.Cog, name="Images"): @commands.cooldown(1, 5, commands.BucketType.user) async def _sot(self, ctx: ContextPlus, **passed_flags): await self._send_meme(ctx, 'scroll_of_truth', **passed_flags) - - -def setup(bot: TuxBot): - cog = Images(bot) - bot.add_cog(cog) diff --git a/tuxbot/cogs/logs/__init__.py b/tuxbot/cogs/logs/__init__.py new file mode 100644 index 0000000..733b020 --- /dev/null +++ b/tuxbot/cogs/logs/__init__.py @@ -0,0 +1,14 @@ +import logging + +from discord.ext import commands + +from .logs import Logs, GatewayHandler, on_error + + +def setup(bot): + cog = Logs(bot) + bot.add_cog(cog) + + handler = GatewayHandler(cog) + logging.getLogger().addHandler(handler) + commands.AutoShardedBot.on_error = on_error diff --git a/cogs/Logs.py b/tuxbot/cogs/logs/logs.py similarity index 98% rename from cogs/Logs.py rename to tuxbot/cogs/logs/logs.py index ae49164..7981168 100644 --- a/cogs/Logs.py +++ b/tuxbot/cogs/logs/logs.py @@ -321,12 +321,3 @@ async def on_error(self, event, *args): except (discord.HTTPException, discord.NotFound, discord.Forbidden, discord.InvalidArgument): pass - - -def setup(bot: TuxBot): - cog = Logs(bot) - bot.add_cog(cog) - - handler = GatewayHandler(cog) - logging.getLogger().addHandler(handler) - commands.AutoShardedBot.on_error = on_error diff --git a/tuxbot/cogs/network/__init__.py b/tuxbot/cogs/network/__init__.py new file mode 100644 index 0000000..b6623f9 --- /dev/null +++ b/tuxbot/cogs/network/__init__.py @@ -0,0 +1,5 @@ +from .network import Network + + +def setup(bot): + bot.add_cog(Network(bot)) diff --git a/cogs/Network.py b/tuxbot/cogs/network/network.py similarity index 98% rename from cogs/Network.py rename to tuxbot/cogs/network/network.py index 2611c8e..f5c6b86 100644 --- a/cogs/Network.py +++ b/tuxbot/cogs/network/network.py @@ -103,8 +103,3 @@ class Network(commands.Cog, name="Useless"): await loading.delete() await ctx.send(embed=e) - - -def setup(bot: TuxBot): - cog = Network(bot) - bot.add_cog(cog) diff --git a/tuxbot/core/__init__.py b/tuxbot/core/__init__.py new file mode 100644 index 0000000..d38178b --- /dev/null +++ b/tuxbot/core/__init__.py @@ -0,0 +1,8 @@ +from colorama import init + +from .. import __version__, version_info, VersionInfo +from .config import Config + +__all__ = ["Config", "__version__", "version_info", "VersionInfo"] + +init() diff --git a/tuxbot/core/bot.py b/tuxbot/core/bot.py new file mode 100644 index 0000000..0eab5f2 --- /dev/null +++ b/tuxbot/core/bot.py @@ -0,0 +1,41 @@ +from pathlib import Path + +from discord.ext import commands +from . import Config + + +__all__ = ["Tux"] + + +class Tux(commands.AutoShardedBot): + def __init__(self, *args, bot_dir: Path, **kwargs): + self._config = Config.register_core( + identifier=None, + mentionnable=False + ) + self._config.register_global( + token=None, + prefix=[], + owner=None, + whitelist=[], + blacklist=[], + locale="en-US", + embeds=True, + color=0x6E83D1, + description="Tuxbot !", + 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 + ) \ No newline at end of file diff --git a/tuxbot/core/config.py b/tuxbot/core/config.py new file mode 100644 index 0000000..56bb294 --- /dev/null +++ b/tuxbot/core/config.py @@ -0,0 +1,41 @@ +from pathlib import Path +from typing import Any, NoReturn + + +class Config: + GLOBAL = "GLOBAL" + GUILD = "GUILD" + CHANNEL = "TEXT_CHANNEL" + ROLE = "ROLE" + MEMBER = "MEMBER" + USER = "USER" + + def __init__(self, config_dir: Path): + self._defaults = {} + + def __getattr__(self, item: str) -> dict: + return getattr(self._defaults, item) + + def _register_default(self, key: str, **kwargs: Any): + ... + + def register_core(self, **kwargs) -> NoReturn: + self._register_default(self.GUILD, **kwargs) + + def register_global(self, **kwargs) -> NoReturn: + self._register_default(self.GLOBAL, **kwargs) + + def register_guild(self, **kwargs) -> NoReturn: + self._register_default(self.GUILD, **kwargs) + + def register_channel(self, **kwargs) -> NoReturn: + self._register_default(self.CHANNEL, **kwargs) + + def register_role(self, **kwargs) -> NoReturn: + self._register_default(self.ROLE, **kwargs) + + def register_member(self, **kwargs) -> NoReturn: + self._register_default(self.MEMBER, **kwargs) + + def register_user(self, **kwargs) -> NoReturn: + self._register_default(self.USER, **kwargs) diff --git a/models/__init__.py b/tuxbot/core/models/__init__.py similarity index 100% rename from models/__init__.py rename to tuxbot/core/models/__init__.py diff --git a/utils/functions/cli.py b/tuxbot/core/utils/functions/cli.py similarity index 100% rename from utils/functions/cli.py rename to tuxbot/core/utils/functions/cli.py diff --git a/utils/functions/extra.py b/tuxbot/core/utils/functions/extra.py similarity index 100% rename from utils/functions/extra.py rename to tuxbot/core/utils/functions/extra.py diff --git a/tuxbot/setup.py b/tuxbot/setup.py new file mode 100644 index 0000000..c5f09f9 --- /dev/null +++ b/tuxbot/setup.py @@ -0,0 +1,2 @@ +def setup(): + ...