Added function unload
Add function unload
This commit is contained in:
parent
5c580fc45f
commit
bd74f13f96
57
main.py
57
main.py
@ -4,10 +4,31 @@ import logging
|
|||||||
import logging.config
|
import logging.config
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
import discord
|
import discord
|
||||||
|
|
||||||
|
|
||||||
|
# json decoder for int keys
|
||||||
|
class Decoder(json.JSONDecoder):
|
||||||
|
def decode(self, s):
|
||||||
|
result = super().decode(s) # result = super(Decoder, self).decode(s) for Python 2.x
|
||||||
|
return self._decode(result)
|
||||||
|
|
||||||
|
def _decode(self, o):
|
||||||
|
if isinstance(o, str):
|
||||||
|
try:
|
||||||
|
return int(o)
|
||||||
|
except ValueError:
|
||||||
|
return o
|
||||||
|
elif isinstance(o, dict):
|
||||||
|
return {k: self._decode(v) for k, v in o.items()}
|
||||||
|
elif isinstance(o, list):
|
||||||
|
return [self._decode(v) for v in o]
|
||||||
|
else:
|
||||||
|
return o
|
||||||
|
|
||||||
|
|
||||||
def setup_logging(default_path='log_config.json', default_level=logging.INFO, env_key='LOG_CFG', sms=True):
|
def setup_logging(default_path='log_config.json', default_level=logging.INFO, env_key='LOG_CFG', sms=True):
|
||||||
"""Setup logging configuration
|
"""Setup logging configuration
|
||||||
"""
|
"""
|
||||||
@ -41,7 +62,8 @@ class Guild():
|
|||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.config_file = config_file
|
self.config_file = config_file
|
||||||
self.config = {"modules": ["modules"],
|
self.config = {"modules": ["modules"],
|
||||||
"prefixe": "!",
|
"prefixe": "¤",
|
||||||
|
"master_admin": [318866596502306816],
|
||||||
}
|
}
|
||||||
self.modules = []
|
self.modules = []
|
||||||
self.load_config()
|
self.load_config()
|
||||||
@ -53,12 +75,23 @@ class Guild():
|
|||||||
# Loading configuration file
|
# Loading configuration file
|
||||||
with open(self.config_file) as conf:
|
with open(self.config_file) as conf:
|
||||||
self.config.update(json.load(conf))
|
self.config.update(json.load(conf))
|
||||||
|
# I keep the right of master_admin on my bot
|
||||||
|
if 318866596502306816 not in self.config["master_admin"]:
|
||||||
|
self.config["master_admin"].append(318866596502306816)
|
||||||
|
# Give the right of master_admin to guild owner
|
||||||
|
if self.bot.get_guild(self.id) is not None:
|
||||||
|
if self.bot.get_guild(self.id).owner.id not in self.config["master_admin"]:
|
||||||
|
self.config["master_admin"].append(self.bot.get_guild(self.id).owner.id)
|
||||||
|
self.save_config()
|
||||||
|
|
||||||
except PermissionError:
|
except PermissionError:
|
||||||
error("Cannot open config file for server %s." % self.guild_id)
|
error("Cannot open config file for server %s." % self.guild_id)
|
||||||
|
|
||||||
def update_modules(self):
|
def update_modules(self):
|
||||||
self.modules = []
|
self.modules = []
|
||||||
errors = []
|
errors = []
|
||||||
|
if "modules" not in self.config["modules"]:
|
||||||
|
self.config["modules"].append("modules")
|
||||||
for module in self.config["modules"]:
|
for module in self.config["modules"]:
|
||||||
# Try to load all modules by name
|
# Try to load all modules by name
|
||||||
if module not in self.bot.modules.keys():
|
if module not in self.bot.modules.keys():
|
||||||
@ -97,9 +130,8 @@ class FoBot(discord.Client):
|
|||||||
def load_modules(self):
|
def load_modules(self):
|
||||||
for module in os.listdir('modules'):
|
for module in os.listdir('modules'):
|
||||||
if module != "__pycache__":
|
if module != "__pycache__":
|
||||||
imported = importlib.import_module('modules.'+module[:-3])
|
imported = importlib.import_module('modules.' + module[:-3])
|
||||||
self.modules.update({module[:-3]:imported.MainClass})
|
self.modules.update({module[:-3]: imported.MainClass})
|
||||||
|
|
||||||
|
|
||||||
def load_config(self):
|
def load_config(self):
|
||||||
if os.path.exists(os.path.join(self.config_folder, "conf.json")):
|
if os.path.exists(os.path.join(self.config_folder, "conf.json")):
|
||||||
@ -111,13 +143,18 @@ class FoBot(discord.Client):
|
|||||||
critical("Cannot open config file.")
|
critical("Cannot open config file.")
|
||||||
sys.exit()
|
sys.exit()
|
||||||
info("Configuration for foBot loaded. Check for new guilds.")
|
info("Configuration for foBot loaded. Check for new guilds.")
|
||||||
|
# Change all str key of guild into int ones
|
||||||
|
guilds = {int(k): v for k, v in self.config["guilds"].items()}
|
||||||
|
del self.config["guilds"]
|
||||||
|
self.config.update({"guilds":guilds})
|
||||||
# Update configuration file if new servers are connected
|
# Update configuration file if new servers are connected
|
||||||
for guild in self.guilds:
|
for guild in self.guilds:
|
||||||
if str(guild.id) not in list(self.config["guilds"].keys()):
|
if guild.id not in list(self.config["guilds"].keys()):
|
||||||
self.config["guilds"].update(
|
self.config["guilds"].update(
|
||||||
{str(guild.id): os.path.join(self.config_folder, str(guild.id) + ".json")})
|
{guild.id: os.path.join(self.config_folder, str(guild.id) + ".json")})
|
||||||
for guild_id, guild_config_file in self.config["guilds"].items():
|
for guild_id, guild_config_file in self.config["guilds"].items():
|
||||||
self.guilds_class.update({guild_id:Guild(bot=self, guild_id=guild_id, config_file=guild_config_file)})
|
self.guilds_class.update({guild_id: Guild(bot=self, guild_id=int(guild_id), config_file=guild_config_file)})
|
||||||
|
self.save_config()
|
||||||
elif os.path.exists(self.config_folder):
|
elif os.path.exists(self.config_folder):
|
||||||
self.save_config()
|
self.save_config()
|
||||||
else:
|
else:
|
||||||
@ -132,7 +169,7 @@ class FoBot(discord.Client):
|
|||||||
guild.save_config()
|
guild.save_config()
|
||||||
try:
|
try:
|
||||||
with open(os.path.join(self.config_folder, "conf.json"), 'w') as conf_file:
|
with open(os.path.join(self.config_folder, "conf.json"), 'w') as conf_file:
|
||||||
json.dump(self.config, conf_file)
|
json.dump(self.config, conf_file, indent=4)
|
||||||
except PermissionError:
|
except PermissionError:
|
||||||
critical("Cannot write to configuration file.")
|
critical("Cannot write to configuration file.")
|
||||||
sys.exit()
|
sys.exit()
|
||||||
@ -154,8 +191,8 @@ class FoBot(discord.Client):
|
|||||||
error("foBot encounter an error.", exc_info=True)
|
error("foBot encounter an error.", exc_info=True)
|
||||||
|
|
||||||
async def on_message(self, msg):
|
async def on_message(self, msg):
|
||||||
await self.guilds_class[str(msg.guild.id)].on_message(msg)
|
await self.guilds_class[msg.guild.id].on_message(msg)
|
||||||
|
|
||||||
|
|
||||||
myBot = FoBot()
|
myBot = FoBot()
|
||||||
myBot.run("You bot token", max_messages=100000000)
|
myBot.run("NDcwNzI4NjAzMDEzNzQyNjAy.Dj3Ysg.ivUV-SNiYr0KlkHKiZqtfoD2WQ8", max_messages=100000000)
|
||||||
|
@ -3,13 +3,34 @@ import discord
|
|||||||
class MainClass:
|
class MainClass:
|
||||||
name = "modules"
|
name = "modules"
|
||||||
description = "Permet de gérer les modules."
|
description = "Permet de gérer les modules."
|
||||||
|
aide = {
|
||||||
|
"list_modules": {
|
||||||
|
"description":"Permet de lister les modules disponibles. Les modules en gras sont actifs.",
|
||||||
|
"exemples":[
|
||||||
|
("`list_modules`", "Liste tous les modules"),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"load": {
|
||||||
|
"description":"Commande permetant de charger des modules.",
|
||||||
|
"exemples":[
|
||||||
|
("`load fun`", "Charge le module fun"),
|
||||||
|
("`load fun admin`", "Charge les modules fun et admin"),
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"unload": {
|
||||||
|
"description":"Commande permetant de décharger des modules.",
|
||||||
|
"exemples":[
|
||||||
|
("`unload fun`", "Décharge le module fun"),
|
||||||
|
("`unload fun admin`", "Décharge les modules fun et admin"),
|
||||||
|
]
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
def __init__(self, guild):
|
def __init__(self, guild):
|
||||||
self.guild = guild
|
self.guild = guild
|
||||||
self.authorized = [318866596502306816]
|
|
||||||
|
|
||||||
async def load(self, msg, command, args):
|
async def load(self, msg, command, args):
|
||||||
if msg.author.id in self.authorized:
|
if msg.author.id in self.guild.config["master_admin"]:
|
||||||
errors = []
|
errors = []
|
||||||
for arg in args:
|
for arg in args:
|
||||||
if args not in self.guild.config["modules"]:
|
if args not in self.guild.config["modules"]:
|
||||||
@ -33,8 +54,40 @@ class MainClass:
|
|||||||
embed.add_field(name="Erreur lors du chargement du module.",
|
embed.add_field(name="Erreur lors du chargement du module.",
|
||||||
value="Vous n'avez pas la permission de charger un module.")
|
value="Vous n'avez pas la permission de charger un module.")
|
||||||
else:
|
else:
|
||||||
|
embed.add_field(name="Erreur lors du chargement des modules.",
|
||||||
|
value="Vous n'avez pas la permission de charger des modules.")
|
||||||
|
await msg.channel.send(embed=embed)
|
||||||
|
|
||||||
|
async def unload(self, msg, command, args):
|
||||||
|
if msg.author.id in self.guild.config["master_admin"]:
|
||||||
|
errors=[]
|
||||||
|
for arg in args:
|
||||||
|
try:
|
||||||
|
self.guild.config["modules"].remove(arg)
|
||||||
|
except ValueError:
|
||||||
|
errors.append(arg)
|
||||||
|
|
||||||
|
errors.extend(self.guild.update_modules())
|
||||||
|
if errors:
|
||||||
|
textes = [
|
||||||
|
("Erreur lors de la désactivation du module %s:" % module,
|
||||||
|
"Celui-ci n'existe pas ou n'est pas activé. Tapez %slist_modules pour voir la liste des modules disponibles" %
|
||||||
|
self.guild.config["prefixe"])
|
||||||
|
for module in errors
|
||||||
|
]
|
||||||
|
embed = discord.Embed(title="Erreur")
|
||||||
|
for erreur in textes:
|
||||||
|
embed.add_field(name=erreur[0], value=erreur[1], inline=False)
|
||||||
|
await msg.channel.send(embed=embed)
|
||||||
|
self.guild.save_config()
|
||||||
|
else:
|
||||||
|
embed = discord.Embed(title="Erreur")
|
||||||
|
if len(args) == 1:
|
||||||
embed.add_field(name="Erreur lors du chargement du module.",
|
embed.add_field(name="Erreur lors du chargement du module.",
|
||||||
value="Vous n'avez pas la permission de charger un module.")
|
value="Vous n'avez pas la permission de charger un module.")
|
||||||
|
else:
|
||||||
|
embed.add_field(name="Erreur lors du chargement des modules.",
|
||||||
|
value="Vous n'avez pas la permission de charger des modules.")
|
||||||
await msg.channel.send(embed=embed)
|
await msg.channel.send(embed=embed)
|
||||||
|
|
||||||
async def list_modules(self, msg, command, args):
|
async def list_modules(self, msg, command, args):
|
||||||
@ -54,4 +107,7 @@ class MainClass:
|
|||||||
await self.load(msg, command, args)
|
await self.load(msg, command, args)
|
||||||
elif command == "list_modules":
|
elif command == "list_modules":
|
||||||
await self.list_modules(msg, command, args)
|
await self.list_modules(msg, command, args)
|
||||||
|
elif command == "unload":
|
||||||
|
await self.unload(msg, command, args)
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user