[base] J'ai fait bc de chose et je ne sais pas quoi mettre en résumé

This commit is contained in:
Louis Chauvet 2019-08-16 19:11:21 +02:00
parent 4c300d45c3
commit 03f7050aaa
Signed by: fomys
GPG Key ID: 1ECA046A9615ABA0
8 changed files with 94 additions and 57 deletions

View File

@ -12,11 +12,15 @@ aiohttp = "*"
aiofiles = "*" aiofiles = "*"
lupa = "*" lupa = "*"
aiofile = "*" aiofile = "*"
pyyaml = "*" toml = "*"
"discord.py" = {version = "*", extras = ["voice",]} "discord.py" = {version = "*", extras = ["voice",]}
[dev-packages] [dev-packages]
[requires] [requires]
python_version = "3.7" python_version = "3.7"

View File

@ -1,6 +1,6 @@
import os import os
import yaml import toml
from config.Base import Config from config.Base import Config
@ -8,7 +8,7 @@ from config.Base import Config
class FSConfig(Config): class FSConfig(Config):
path: str path: str
def __init__(self, path="config.json", *args, **kwargs): def __init__(self, path="config.toml", *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.path = path self.path = path
os.makedirs(os.path.dirname(path), exist_ok=True) os.makedirs(os.path.dirname(path), exist_ok=True)
@ -17,13 +17,11 @@ class FSConfig(Config):
def _load(self): def _load(self):
with open(self.path, "r") as file: with open(self.path, "r") as file:
content = file.read() content = file.read()
self.config = yaml.load(content, Loader=yaml.BaseLoader) self.config = toml.loads(content)
if self.config is None: if self.config is None:
self.parent.config[self.name] = {}
self.config = {} self.config = {}
def _save(self): def _save(self):
content = yaml.dump(self.config) content = toml.dumps(self.config)
print(self.config)
with open(self.path, "w") as file: with open(self.path, "w") as file:
file.write(content) file.write(content)

View File

@ -18,6 +18,7 @@ from packaging.version import Version
from config.FileSystem import FSConfig from config.FileSystem import FSConfig
from errors import IncompatibleModule from errors import IncompatibleModule
from modules.base import base_supported_type
__version__ = "0.1.0" __version__ = "0.1.0"
@ -74,7 +75,6 @@ class Module:
return False return False
with open(os.path.join("modules", self.name, "version.json")) as file: with open(os.path.join("modules", self.name, "version.json")) as file:
versions = json.load(file) versions = json.load(file)
print(versions)
if "version" not in versions.keys(): if "version" not in versions.keys():
return False return False
if "dependencies" not in versions.keys(): if "dependencies" not in versions.keys():
@ -83,6 +83,8 @@ class Module:
return False return False
if "type" not in versions.keys(): if "type" not in versions.keys():
return False return False
if versions["type"] not in base_supported_type:
return False
return True return True
@property @property
@ -226,7 +228,7 @@ class LBI(discord.Client):
def __init__(self, config=None, *args, **kwargs): def __init__(self, config=None, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
if config is None: if config is None:
config = FSConfig(path="data/config.yml") config = FSConfig(path="data/config.toml")
self.reloading = False self.reloading = False
self.id = ClientById(self) self.id = ClientById(self)
self.ready = False self.ready = False

View File

@ -30,13 +30,12 @@ class BaseClass:
Initialize module class, always call it to set self.client when you override it. Initialize module class, always call it to set self.client when you override it.
:param client: client instance :param client: client instance
:type client: NikolaTesla""" :type client: LBI"""
self.client = client self.client = client
self.storage = FSStorage(path.join(self.client.base_path, self.name)) self.storage = FSStorage(path.join(self.client.base_path, self.name))
self.objects = FSObjects(self.storage) self.objects = FSObjects(self.storage)
self.config = Config(parent=self.client.config, name="mod-"+self.name) self.config = Config(parent=self.client.config, name="mod-"+self.name)
self.config["authorized_roles"] = self.config["authorized_roles"] or self.authorized_roles self.config.init({"authorized_roles": self.authorized_roles, "authorized_users": self.authorized_users})
self.config["authorized_users"] = self.config["authorized_users"] or self.authorized_users
async def send_help(self, channel): async def send_help(self, channel):
embed = discord.Embed( embed = discord.Embed(
@ -61,9 +60,9 @@ class BaseClass:
:type user: discord.User :type user: discord.User
""" """
if role_list is None: if role_list is None:
role_list = self.authorized_roles role_list = self.config["authorized_roles"]
if user_list is None: if user_list is None:
user_list = self.authorized_users user_list = self.config["authorized_users"]
if len(role_list) == 0 and len(user_list) == 0: if len(role_list) == 0 and len(user_list) == 0:
# Everyone can use this command # Everyone can use this command
return True return True

View File

@ -1,2 +1,3 @@
from .BasePython import BaseClassPython from .BasePython import BaseClassPython
from .BaseLua import BaseClassLua from .BaseLua import BaseClassLua
base_supported_type = ["python", "lua"]

View File

@ -1,11 +1,14 @@
import asyncio import asyncio
import time
import datetime
import random import random
import traceback import traceback
import collections import collections
import discord import discord
from discord import Message
from config.Base import Config
from modules.base import BaseClassPython from modules.base import BaseClassPython
@ -26,9 +29,7 @@ class MainClass(BaseClassPython):
def __init__(self, client): def __init__(self, client):
super().__init__(client) super().__init__(client)
self.config["dev_chan"] = self.config["dev_chan"] or [] self.config.init({"dev_chan":[], "memes":[""], "icon":""})
self.config["meme"] = [""]
self.config["icon"] = ""
self.errorsDeque = None self.errorsDeque = None
async def on_ready(self): async def on_ready(self):
@ -38,10 +39,10 @@ class MainClass(BaseClassPython):
self.errorsDeque = collections.deque() self.errorsDeque = collections.deque()
for i in range(len(self.errorsDeque)): for i in range(len(self.errorsDeque)):
try: try:
messagelst = self.errorsDeque.popleft() msg_id = self.errorsDeque.popleft()
channel = self.client.get_channel(messagelst[0]) channel = self.client.get_channel(msg_id["channel_id"])
delete_message = await channel.fetch_message(messagelst[1]) to_delete = await channel.fetch_message(msg_id["msg_id"])
await delete_message.delete() await to_delete.delete()
except: except:
raise raise
self.objects.save_object('errorsDeque', self.errorsDeque) self.objects.save_object('errorsDeque', self.errorsDeque)
@ -50,39 +51,59 @@ class MainClass(BaseClassPython):
raise Exception("KERNEL PANIC!!!") raise Exception("KERNEL PANIC!!!")
async def on_error(self, event, *args, **kwargs): async def on_error(self, event, *args, **kwargs):
embed = discord.Embed(title="Aïe :/", description="```PYTHON\n{0}```".format(traceback.format_exc()), """Send error message"""
color=self.color).set_image(url=random.choice(self.memes)) # Search first channel instance found in arg, then search in kwargs
channel = None
for arg in args:
if type(arg) == Message:
channel = arg.channel
break
if type(arg) == discord.TextChannel:
channel = arg
break
if channel is None:
for _,v in kwargs.items():
if type(v) == discord.Message:
channel = v.channel
break
if type(v) == discord.TextChannel:
channel = v
break# Create embed
embed = discord.Embed(
title="[Erreur] Aïe :/",
description="```python\n{0}```".format(traceback.format_exc()),
color=self.color)
embed.set_image(url=random.choice(self.config["memes"]))
message_list = None message_list = None
try:
message = await args[0].channel.send( # Send message to dev channels
embed=embed.set_footer(text="Ce message va s'autodétruire dans une minute.", icon_url=self.icon))
message_list = [message.channel.id, message.id]
self.errorsDeque.append(message_list)
except:
try:
message = args[1].channel.send(
embed=embed.set_footer(text="Ce message va s'autodétruire dans une minute.", icon_url=self.icon))
message_list = [message.channel.id, message.id]
self.errorsDeque.append(message_list)
except:
pass
for chanid in self.config["dev_chan"]: for chanid in self.config["dev_chan"]:
try: try:
await self.client.get_channel(chanid).send( await self.client.get_channel(chanid).send(
embed=embed.set_footer(text="Ce message ne s'autodétruira pas.", icon_url=self.icon)) embed=embed.set_footer(text="Ce message ne s'autodétruira pas.", icon_url=self.icon))
except: except:
pass pass
self.objects.save_object('errorsDeque', self.errorsDeque) # Send message to current channel if exists
await asyncio.sleep(60) if channel is not None:
try: message = await channel.send(embed=embed.set_footer(text="Ce message va s'autodétruire dans une minute",
channel = self.client.get_channel(message_list[0]) icon_url=self.config["icon"]))
delete_message = await channel.fetch_message(message_list[1]) msg_id = {"chan_id": message.channel.id, "msg_id": message.id}
await delete_message.delete() self.errorsDeque.append(msg_id)
except: # Save message in errorsDeque now to keep them if a reboot happend during next 60 seconds
raise self.objects.save_object('errorsDeque', self.errorsDeque)
finally:
# Wait 60 seconds and delete message
await asyncio.sleep(60)
try: try:
self.errorsDeque.remove(message_list) channel = self.client.get_channel(msg_id["chan_id"])
except ValueError: delete_message = await channel.fetch_message(msg_id["msg_id"])
pass await delete_message.delete()
self.objects.save_object('errorsDeque', self.errorsDeque) except:
raise
finally:
try:
self.errorsDeque.remove(msg_id)
except ValueError:
pass
# Save now to avoid deleting unkown message
self.objects.save_object('errorsDeque', self.errorsDeque)

View File

@ -36,7 +36,7 @@ class MainClass(BaseClassPython):
all_items = os.listdir("modules") all_items = os.listdir("modules")
modules = [] modules = []
for item in all_items: for item in all_items:
if item not in ["__init__.py", "base", "__pycache__", "dummy"]: if item not in ["__init__.py", "base", "__pycache__"]:
if os.path.isfile(os.path.join("modules", item)): if os.path.isfile(os.path.join("modules", item)):
modules.append(item[:-3]) modules.append(item[:-3])
else: else:
@ -58,7 +58,9 @@ class MainClass(BaseClassPython):
return return
for arg in args: for arg in args:
e = self.client.load_module(arg) e = self.client.load_module(arg)
if e: if e == 2:
await message.channel.send("Module {module} is incompatible.")
elif e:
await message.channel.send("An error occurred during the loading of the module {module}: {error}." await message.channel.send("An error occurred during the loading of the module {module}: {error}."
.format(module=arg, error=e)) .format(module=arg, error=e))
await self.com_list(message, args, kwargs) await self.com_list(message, args, kwargs)
@ -106,10 +108,16 @@ class MainClass(BaseClassPython):
async def com_list(self, message, args, kwargs): async def com_list(self, message, args, kwargs):
list_files = self.get_all_modules() list_files = self.get_all_modules()
activated = set(self.client.config["modules"]) activated = set(self.client.config["modules"])
activated_string = "\n+ " + "\n+ ".join(activated) if len(activated):
deactivated_string = "- " + "\n- ".join(list_files.difference(activated)) activated_string = "\n+ " + "\n+ ".join(activated)
else:
activated_string = ""
if len(activated) != len(list_files):
deactivated_string = "\n- " + "\n- ".join(list_files.difference(activated))
else:
deactivated_string = ""
embed = discord.Embed(title="[Modules] - Liste des modules", embed = discord.Embed(title="[Modules] - Liste des modules",
description="```diff\n{activated}\n{deactivated}```".format( description="```diff{activated}{deactivated}```".format(
activated=activated_string, activated=activated_string,
deactivated=deactivated_string) deactivated=deactivated_string)
) )

View File

@ -31,6 +31,10 @@ class Api:
async def download(self, module, version): async def download(self, module, version):
await self._download("modules/"+module+"/"+version, filename="temp.zip") await self._download("modules/"+module+"/"+version, filename="temp.zip")
shutil.rmtree(os.path.join("modules, module")) # TODO: Supprimer le dossier ici
try:
shutil.rmtree(os.path.join("modules", module))
except:
print('Error while deleting directory')
with zipfile.ZipFile('temp.zip', "r") as z: with zipfile.ZipFile('temp.zip', "r") as z:
z.extractall(os.path.join("modules", module)) z.extractall(os.path.join("modules", module))