tuxbot-bot/bot.py

127 lines
4.1 KiB
Python
Raw Normal View History

2019-05-29 22:59:20 +00:00
import datetime
import logging
2019-05-29 22:59:20 +00:00
import sys
import traceback
from collections import deque
2019-05-29 22:59:20 +00:00
2018-12-03 00:26:23 +00:00
import aiohttp
2019-05-29 22:59:20 +00:00
import discord
import git
2019-05-29 22:59:20 +00:00
from discord.ext import commands
2019-05-29 22:59:20 +00:00
import config
from cogs.utils.config import Config
from cogs.utils.lang import gettext
from cogs.utils.version import Version
description = """
Je suis TuxBot, le bot qui vit de l'OpenSource ! ;)
"""
log = logging.getLogger(__name__)
2019-07-28 18:55:00 +00:00
2019-05-29 22:59:20 +00:00
l_extensions = (
'cogs.admin',
2019-09-10 16:37:38 +00:00
'cogs.bascics',
'jishaku',
2019-05-29 22:59:20 +00:00
)
2019-09-10 16:23:24 +00:00
async def _prefix_callable(bot, message: discord.message) -> list:
extras = []
if message.guild is not None:
extras = bot.prefixes.get(str(message.guild.id), [])
return commands.when_mentioned_or(*extras)(bot, message)
class TuxBot(commands.AutoShardedBot):
__slots__ = ('uptime', 'config', 'session')
2019-09-10 16:23:24 +00:00
def __init__(self, unload: list):
2019-09-10 16:37:38 +00:00
super().__init__(command_prefix=_prefix_callable, description=description, pm_help=None, help_command=None, help_attrs=dict(hidden=True))
2019-09-10 16:23:24 +00:00
self.uptime: datetime = datetime.datetime.utcnow()
2019-05-29 22:59:20 +00:00
self.config = config
self._prev_events = deque(maxlen=10)
2019-05-29 22:59:20 +00:00
self.session = aiohttp.ClientSession(loop=self.loop)
self.prefixes = Config('prefixes.json')
self.blacklist = Config('blacklist.json')
self.version = Version(10, 0, 0, pre_release='a20', build=git.Repo(search_parent_directories=True).head.object.hexsha)
2019-05-29 22:59:20 +00:00
for extension in l_extensions:
if extension not in unload:
try:
self.load_extension(extension)
except Exception as e:
2019-09-10 16:37:38 +00:00
print(gettext("Failed to load extension : ") + extension, file=sys.stderr)
log.error(gettext("Failed to load extension : ") + extension, exc_info=e)
2019-09-10 16:23:24 +00:00
async def is_owner(self, user: discord.User) -> bool:
return user.id in config.authorized_id
async def on_socket_response(self, msg):
self._prev_events.append(msg)
2019-05-29 22:59:20 +00:00
2019-09-10 16:23:24 +00:00
async def on_command_error(self, ctx: discord.ext.commands.Context, error):
2019-05-29 22:59:20 +00:00
if isinstance(error, commands.NoPrivateMessage):
2019-09-10 16:37:38 +00:00
await ctx.author.send(gettext('This command cannot be used in private messages.'))
2019-05-29 22:59:20 +00:00
elif isinstance(error, commands.DisabledCommand):
2019-09-10 16:37:38 +00:00
await ctx.author.send(gettext('Sorry. This command is disabled and cannot be used.'))
2019-05-29 22:59:20 +00:00
elif isinstance(error, commands.CommandInvokeError):
2019-09-10 16:37:38 +00:00
print(gettext('In ') + f'{ctx.command.qualified_name}:', file=sys.stderr)
2019-05-29 22:59:20 +00:00
traceback.print_tb(error.original.__traceback__)
2019-09-10 16:37:38 +00:00
print(f'{error.original.__class__.__name__}: {error.original}', file=sys.stderr)
elif isinstance(error, commands.ArgumentParsingError):
2019-09-10 16:23:24 +00:00
await ctx.send(error.__str__())
2019-05-29 22:59:20 +00:00
2019-09-10 16:23:24 +00:00
async def process_commands(self, message: discord.message):
ctx = await self.get_context(message)
if ctx.command is None:
return
await self.invoke(ctx)
2019-09-10 16:23:24 +00:00
async def on_message(self, message: discord.message):
2019-09-10 16:37:38 +00:00
if message.author.bot or message.author.id in self.blacklist or message.guild.id in self.blacklist:
return
await self.process_commands(message)
2019-05-29 22:59:20 +00:00
async def on_ready(self):
if not hasattr(self, 'uptime'):
self.uptime = datetime.datetime.utcnow()
print(gettext('Ready:') + f' {self.user} (ID: {self.user.id})')
print(self.version)
2019-05-29 22:59:20 +00:00
2019-09-10 16:23:24 +00:00
presence: dict = dict(status=discord.Status.dnd)
if self.config.activity is not None:
presence.update(activity=discord.Game(name=self.config.activity))
await self.change_presence(**presence)
2019-05-29 22:59:20 +00:00
@staticmethod
async def on_resumed():
print('resumed...')
@property
2019-09-10 16:23:24 +00:00
def logs_webhook(self) -> discord.Webhook:
logs_webhook = self.config.logs_webhook
2019-09-10 16:37:38 +00:00
webhook = discord.Webhook.partial(id=logs_webhook.get('id'), token=logs_webhook.get('token'), adapter=discord.AsyncWebhookAdapter(self.session))
return webhook
2019-05-29 22:59:20 +00:00
async def close(self):
await super().close()
await self.session.close()
2019-05-29 22:59:20 +00:00
def run(self):
super().run(config.token, reconnect=True)