refactor(all): start from new

feat(doc): add readme file
This commit is contained in:
Romain J 2020-06-03 01:07:43 +02:00
parent 28d1d71c5a
commit 078dc075f2
22 changed files with 120 additions and 311 deletions

181
app.py
View file

@ -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()

View file

@ -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)

View file

@ -1,5 +0,0 @@
{
"channels": [],
"guilds": [],
"users": []
}

View file

@ -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
]

View file

@ -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 = ''

View file

@ -1,3 +0,0 @@
{
"owners": [269156684155453451]
}

View file

@ -1,11 +0,0 @@
discord.py
discord-flags
asyncpg
tortoise-orm
requests
ipinfo
ipwhois
humanize
psutil
aiohttp
colorama

2
tuxbot/__main__.py Normal file
View file

@ -0,0 +1,2 @@
def main():
...

View file

@ -0,0 +1,5 @@
from .images import Images
def setup(bot):
bot.add_cog(Images(bot))

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -0,0 +1,5 @@
from .network import Network
def setup(bot):
bot.add_cog(Network(bot))

View file

@ -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)

8
tuxbot/core/__init__.py Normal file
View file

@ -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()

41
tuxbot/core/bot.py Normal file
View file

@ -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
)

41
tuxbot/core/config.py Normal file
View file

@ -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)

2
tuxbot/setup.py Normal file
View file

@ -0,0 +1,2 @@
def setup():
...