Ton bot mais en respectant la PEP8

This commit is contained in:
Fomys 2019-03-02 14:38:37 +01:00
parent 1117c77d9b
commit c4d3a98726
8 changed files with 405 additions and 266 deletions

54
main.py
View File

@ -1,12 +1,16 @@
#!/usr/bin/python3 #!/usr/bin/python3
import discord
import os
import importlib import importlib
import os
import traceback import traceback
import discord
client = discord.Client() client = discord.Client()
prefix = ";" prefix = ";"
modules = {} # format : {'modulename':[module, initializedclass]} modules = {} # format : {'modulename':[module, initializedclass]}
owners = [281166473102098433, 318866596502306816, 436105272310759426] owners = [281166473102098433, 318866596502306816, 436105272310759426]
async def auth(user, moduleName): async def auth(user, moduleName):
if user.id in owners: if user.id in owners:
return True return True
@ -26,6 +30,7 @@ async def on_ready():
print("Bienvenue, {0.user}, l'heure est venue de faire des fractales.".format(client)) print("Bienvenue, {0.user}, l'heure est venue de faire des fractales.".format(client))
panic = False panic = False
error = None error = None
async def panicLoad(): async def panicLoad():
print("--PANIC LOAD--") print("--PANIC LOAD--")
panic = True panic = True
@ -79,6 +84,7 @@ async def on_ready():
if error: if error:
raise error raise error
@client.event @client.event
async def on_error(event, *args, **kwargs): async def on_error(event, *args, **kwargs):
print(traceback.format_exc()) print(traceback.format_exc())
@ -86,24 +92,28 @@ async def on_error(event, *args, **kwargs):
if 'on_error' in modules[moduleName][1].events: if 'on_error' in modules[moduleName][1].events:
await modules[moduleName][1].on_error(event, *args, **kwargs) await modules[moduleName][1].on_error(event, *args, **kwargs)
@client.event @client.event
async def on_socket_raw_receive(msg): async def on_socket_raw_receive(msg):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_socket_raw_receive' in modules[moduleName][1].events: if 'on_socket_raw_receive' in modules[moduleName][1].events:
await modules[moduleName][1].on_socket_raw_receive(msg) await modules[moduleName][1].on_socket_raw_receive(msg)
@client.event @client.event
async def on_socket_raw_send(payload): async def on_socket_raw_send(payload):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_socket_raw_send' in modules[moduleName][1].events: if 'on_socket_raw_send' in modules[moduleName][1].events:
await modules[moduleName][1].on_socket_raw_send(payload) await modules[moduleName][1].on_socket_raw_send(payload)
@client.event @client.event
async def on_typing(channel, user, when): async def on_typing(channel, user, when):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_typing' in modules[moduleName][1].events: if 'on_typing' in modules[moduleName][1].events:
await modules[moduleName][1].on_typing(channel, user, when) await modules[moduleName][1].on_typing(channel, user, when)
@client.event @client.event
async def on_message(message): async def on_message(message):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
@ -111,238 +121,278 @@ async def on_message(message):
if await auth(message.author, moduleName): if await auth(message.author, moduleName):
await modules[moduleName][1].on_message(message) await modules[moduleName][1].on_message(message)
@client.event @client.event
async def on_message_delete(message): async def on_message_delete(message):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_message_delete' in modules[moduleName][1].events: if 'on_message_delete' in modules[moduleName][1].events:
await modules[moduleName][1].on_message_delete(message) await modules[moduleName][1].on_message_delete(message)
@client.event @client.event
async def on_raw_message_delete(payload): async def on_raw_message_delete(payload):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_raw_message_delete' in modules[moduleName][1].events: if 'on_raw_message_delete' in modules[moduleName][1].events:
await modules[moduleName][1].on_raw_message_delete(payload) await modules[moduleName][1].on_raw_message_delete(payload)
@client.event @client.event
async def on_raw_bulk_message_delete(payload): async def on_raw_bulk_message_delete(payload):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_raw_bulk_message_delete' in modules[moduleName][1].events: if 'on_raw_bulk_message_delete' in modules[moduleName][1].events:
await modules[moduleName][1].on_raw_bulk_message_delete(payload) await modules[moduleName][1].on_raw_bulk_message_delete(payload)
@client.event @client.event
async def on_message_edit(before, after): async def on_message_edit(before, after):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_message_edit' in modules[moduleName][1].events: if 'on_message_edit' in modules[moduleName][1].events:
await modules[moduleName][1].on_message_edit(before, after) await modules[moduleName][1].on_message_edit(before, after)
@client.event @client.event
async def on_raw_message_edit(payload): async def on_raw_message_edit(payload):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_raw_message_edit' in modules[moduleName][1].events: if 'on_raw_message_edit' in modules[moduleName][1].events:
await modules[moduleName][1].on_raw_message_edit(payload) await modules[moduleName][1].on_raw_message_edit(payload)
@client.event @client.event
async def on_reaction_add(reaction, user): async def on_reaction_add(reaction, user):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_reaction_add' in modules[moduleName][1].events: if 'on_reaction_add' in modules[moduleName][1].events:
await modules[moduleName][1].on_reaction_add(reaction, user) await modules[moduleName][1].on_reaction_add(reaction, user)
@client.event @client.event
async def on_raw_reaction_add(payload): async def on_raw_reaction_add(payload):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_raw_reaction_add' in modules[moduleName][1].events: if 'on_raw_reaction_add' in modules[moduleName][1].events:
await modules[moduleName][1].on_raw_reaction_add(payload) await modules[moduleName][1].on_raw_reaction_add(payload)
@client.event @client.event
async def on_reaction_remove(reaction, user): async def on_reaction_remove(reaction, user):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_reaction_remove' in modules[moduleName][1].events: if 'on_reaction_remove' in modules[moduleName][1].events:
await modules[moduleName][1].on_reaction_remove(reaction, user) await modules[moduleName][1].on_reaction_remove(reaction, user)
@client.event @client.event
async def on_raw_reaction_remove(payload): async def on_raw_reaction_remove(payload):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_raw_reaction_remove' in modules[moduleName][1].events: if 'on_raw_reaction_remove' in modules[moduleName][1].events:
await modules[moduleName][1].on_raw_reaction_remove(payload) await modules[moduleName][1].on_raw_reaction_remove(payload)
@client.event @client.event
async def on_reaction_clear(message, reactions): async def on_reaction_clear(message, reactions):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_reaction_clear' in modules[moduleName][1].events: if 'on_reaction_clear' in modules[moduleName][1].events:
await modules[moduleName][1].on_reaction_clear(message, reactions) await modules[moduleName][1].on_reaction_clear(message, reactions)
@client.event @client.event
async def on_raw_reaction_clear(payload): async def on_raw_reaction_clear(payload):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_raw_reaction_clear' in modules[moduleName][1].events: if 'on_raw_reaction_clear' in modules[moduleName][1].events:
await modules[moduleName][1].on_raw_reaction_clear(payload) await modules[moduleName][1].on_raw_reaction_clear(payload)
@client.event @client.event
async def on_private_channel_delete(channel): async def on_private_channel_delete(channel):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_private_channel_delete' in modules[moduleName][1].events: if 'on_private_channel_delete' in modules[moduleName][1].events:
await modules[moduleName][1].on_private_channel_delete(channel) await modules[moduleName][1].on_private_channel_delete(channel)
@client.event @client.event
async def on_private_channel_create(channel): async def on_private_channel_create(channel):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_private_channel_create' in modules[moduleName][1].events: if 'on_private_channel_create' in modules[moduleName][1].events:
await modules[moduleName][1].on_private_channel_create(channel) await modules[moduleName][1].on_private_channel_create(channel)
@client.event @client.event
async def on_private_channel_update(before, after): async def on_private_channel_update(before, after):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_private_channel_update' in modules[moduleName][1].events: if 'on_private_channel_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_private_channel_update(before, after) await modules[moduleName][1].on_private_channel_update(before, after)
@client.event @client.event
async def on_private_channel_pins_update(channel, last_pin): async def on_private_channel_pins_update(channel, last_pin):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_private_channel_pins_update' in modules[moduleName][1].events: if 'on_private_channel_pins_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_private_channel_pins_update(channel, last_pin) await modules[moduleName][1].on_private_channel_pins_update(channel, last_pin)
@client.event @client.event
async def on_guild_channel_delete(channel): async def on_guild_channel_delete(channel):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_channel_delete' in modules[moduleName][1].events: if 'on_guild_channel_delete' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_channel_delete(channel) await modules[moduleName][1].on_guild_channel_delete(channel)
@client.event @client.event
async def on_guild_channel_create(channel): async def on_guild_channel_create(channel):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_channel_create' in modules[moduleName][1].events: if 'on_guild_channel_create' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_channel_create(channel) await modules[moduleName][1].on_guild_channel_create(channel)
@client.event @client.event
async def on_guild_channel_update(before, after): async def on_guild_channel_update(before, after):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_channel_update' in modules[moduleName][1].events: if 'on_guild_channel_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_channel_update(before, after) await modules[moduleName][1].on_guild_channel_update(before, after)
@client.event @client.event
async def on_guild_channel_pins_update(channel, last_pin): async def on_guild_channel_pins_update(channel, last_pin):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_channel_pins_update' in modules[moduleName][1].events: if 'on_guild_channel_pins_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_channel_pins_update(channel, last_pin) await modules[moduleName][1].on_guild_channel_pins_update(channel, last_pin)
@client.event @client.event
async def on_member_join(member): async def on_member_join(member):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_member_join' in modules[moduleName][1].events: if 'on_member_join' in modules[moduleName][1].events:
await modules[moduleName][1].on_member_join(member) await modules[moduleName][1].on_member_join(member)
@client.event @client.event
async def on_member_remove(member): async def on_member_remove(member):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_member_remove' in modules[moduleName][1].events: if 'on_member_remove' in modules[moduleName][1].events:
await modules[moduleName][1].on_member_remove(member) await modules[moduleName][1].on_member_remove(member)
@client.event @client.event
async def on_member_update(before, after): async def on_member_update(before, after):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_member_update' in modules[moduleName][1].events: if 'on_member_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_member_update(before, after) await modules[moduleName][1].on_member_update(before, after)
@client.event @client.event
async def on_guild_join(guild): async def on_guild_join(guild):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_join' in modules[moduleName][1].events: if 'on_guild_join' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_join(guild) await modules[moduleName][1].on_guild_join(guild)
@client.event @client.event
async def on_guild_remove(guild): async def on_guild_remove(guild):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_remove' in modules[moduleName][1].events: if 'on_guild_remove' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_remove(guild) await modules[moduleName][1].on_guild_remove(guild)
@client.event @client.event
async def on_guild_update(before, after): async def on_guild_update(before, after):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_update' in modules[moduleName][1].events: if 'on_guild_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_update(before, after) await modules[moduleName][1].on_guild_update(before, after)
@client.event @client.event
async def on_guild_role_create(role): async def on_guild_role_create(role):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_role_create' in modules[moduleName][1].events: if 'on_guild_role_create' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_role_create(role) await modules[moduleName][1].on_guild_role_create(role)
@client.event @client.event
async def on_guild_role_delete(role): async def on_guild_role_delete(role):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_role_delete' in modules[moduleName][1].events: if 'on_guild_role_delete' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_role_delete(role) await modules[moduleName][1].on_guild_role_delete(role)
@client.event @client.event
async def on_guild_role_update(before, after): async def on_guild_role_update(before, after):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_role_update' in modules[moduleName][1].events: if 'on_guild_role_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_role_update(before, after) await modules[moduleName][1].on_guild_role_update(before, after)
@client.event @client.event
async def on_guild_emojis_update(guild, before, after): async def on_guild_emojis_update(guild, before, after):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_emojis_update' in modules[moduleName][1].events: if 'on_guild_emojis_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_emojis_update(guild, before, after) await modules[moduleName][1].on_guild_emojis_update(guild, before, after)
@client.event @client.event
async def on_guild_available(guild): async def on_guild_available(guild):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_available' in modules[moduleName][1].events: if 'on_guild_available' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_available(guild) await modules[moduleName][1].on_guild_available(guild)
@client.event @client.event
async def on_guild_unavailable(guild): async def on_guild_unavailable(guild):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_guild_unavailable' in modules[moduleName][1].events: if 'on_guild_unavailable' in modules[moduleName][1].events:
await modules[moduleName][1].on_guild_unavailable(guild) await modules[moduleName][1].on_guild_unavailable(guild)
@client.event @client.event
async def on_voice_state_update(member, before, after): async def on_voice_state_update(member, before, after):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_voice_state_update' in modules[moduleName][1].events: if 'on_voice_state_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_voice_state_update(member, before, after) await modules[moduleName][1].on_voice_state_update(member, before, after)
@client.event @client.event
async def on_member_ban(guild, user): async def on_member_ban(guild, user):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_member_ban' in modules[moduleName][1].events: if 'on_member_ban' in modules[moduleName][1].events:
await modules[moduleName][1].on_member_ban(guild, user) await modules[moduleName][1].on_member_ban(guild, user)
@client.event @client.event
async def on_member_unban(guild, user): async def on_member_unban(guild, user):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_member_unban' in modules[moduleName][1].events: if 'on_member_unban' in modules[moduleName][1].events:
await modules[moduleName][1].on_member_unban(guild, user) await modules[moduleName][1].on_member_unban(guild, user)
@client.event @client.event
async def on_group_join(channel, user): async def on_group_join(channel, user):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_group_join' in modules[moduleName][1].events: if 'on_group_join' in modules[moduleName][1].events:
await modules[moduleName][1].on_group_join(channel, user) await modules[moduleName][1].on_group_join(channel, user)
@client.event @client.event
async def on_group_remove(channel, user): async def on_group_remove(channel, user):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_group_remove' in modules[moduleName][1].events: if 'on_group_remove' in modules[moduleName][1].events:
await modules[moduleName][1].on_group_remove(channel, user) await modules[moduleName][1].on_group_remove(channel, user)
@client.event @client.event
async def on_relationship_add(relationship): async def on_relationship_add(relationship):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_relationship_add' in modules[moduleName][1].events: if 'on_relationship_add' in modules[moduleName][1].events:
await modules[moduleName][1].on_relationship_add(relationship) await modules[moduleName][1].on_relationship_add(relationship)
@client.event @client.event
async def on_relationship_remove(relationship): async def on_relationship_remove(relationship):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_relationship_remove' in modules[moduleName][1].events: if 'on_relationship_remove' in modules[moduleName][1].events:
await modules[moduleName][1].on_relationship_remove(relationship) await modules[moduleName][1].on_relationship_remove(relationship)
@client.event @client.event
async def on_relationship_update(before, after): async def on_relationship_update(before, after):
for moduleName in list(modules.keys()): for moduleName in list(modules.keys()):
if 'on_relationship_update' in modules[moduleName][1].events: if 'on_relationship_update' in modules[moduleName][1].events:
await modules[moduleName][1].on_relationship_update(before, after) await modules[moduleName][1].on_relationship_update(before, after)
client.run(os.environ['DISCORD_TOKEN']) client.run(os.environ['DISCORD_TOKEN'])

View File

@ -1,5 +1,4 @@
# dummy module # dummy module
import asyncio
class MainClass(): class MainClass():
def __init__(self, client, modules, owners, prefix): def __init__(self, client, modules, owners, prefix):
self.client = client self.client = client
@ -16,5 +15,6 @@ class MainClass():
self.help = """\ self.help = """\
Aucune fonction. Aucune fonction.
""" """
async def on_message(self, message): async def on_message(self, message):
print(message.content) print(message.content)

View File

@ -1,18 +1,23 @@
import asyncio import asyncio
import traceback
import discord
import random
import pickle
import os.path
import collections import collections
import os.path
import pickle
import random
import traceback
from subprocess import call from subprocess import call
import discord
moduleFiles = "errors" moduleFiles = "errors"
class MainClass(): class MainClass():
def saveObject(self, object, objectname): def saveObject(self, object, objectname):
with open("storage/%s/" % moduleFiles + objectname + "tmp", "wb") as pickleFile: with open("storage/%s/" % moduleFiles + objectname + "tmp", "wb") as pickleFile:
pickler = pickle.Pickler(pickleFile) pickler = pickle.Pickler(pickleFile)
pickler.dump(object) pickler.dump(object)
call(['mv', "storage/%s/" % moduleFiles + objectname + "tmp", "storage/%s/" % moduleFiles + objectname]) call(['mv', "storage/%s/" % moduleFiles + objectname + "tmp", "storage/%s/" % moduleFiles + objectname])
def loadObject(self, objectname): def loadObject(self, objectname):
if self.saveExists(objectname): if self.saveExists(objectname):
with open("storage/%s/" % moduleFiles + objectname, "rb") as pickleFile: with open("storage/%s/" % moduleFiles + objectname, "rb") as pickleFile:
@ -21,6 +26,7 @@ class MainClass():
def saveExists(self, objectname): def saveExists(self, objectname):
return os.path.isfile("storage/%s/" % moduleFiles + objectname) return os.path.isfile("storage/%s/" % moduleFiles + objectname)
def __init__(self, client, modules, owners, prefix): def __init__(self, client, modules, owners, prefix):
if not os.path.isdir("storage/%s" % moduleFiles): if not os.path.isdir("storage/%s" % moduleFiles):
call(['mkdir', 'storage/%s' % moduleFiles]) call(['mkdir', 'storage/%s' % moduleFiles])
@ -48,6 +54,7 @@ class MainClass():
</prefix>licorne </prefix>licorne
=> Crée une erreur. => Crée une erreur.
""" """
async def on_ready(self): async def on_ready(self):
if self.saveExists('errorsDeque'): if self.saveExists('errorsDeque'):
self.errorsDeque = self.loadObject('errorsDeque') self.errorsDeque = self.loadObject('errorsDeque')
@ -62,26 +69,31 @@ class MainClass():
except: except:
raise raise
self.saveObject(self.errorsDeque, 'errorsDeque') self.saveObject(self.errorsDeque, 'errorsDeque')
async def on_message(self, message): async def on_message(self, message):
5 / 0 5 / 0
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()), color=self.color).set_image(url=random.choice(self.memes)) embed = discord.Embed(title="Aïe :/", description="```PYTHON\n{0}```".format(traceback.format_exc()),
color=self.color).set_image(url=random.choice(self.memes))
messagelst = None messagelst = None
try: try:
message = await args[0].channel.send(embed=embed.set_footer(text="Ce message s'autodétruira dans une minute.", icon_url=self.icon)) message = await args[0].channel.send(
embed=embed.set_footer(text="Ce message s'autodétruira dans une minute.", icon_url=self.icon))
messagelst = [message.channel.id, message.id] messagelst = [message.channel.id, message.id]
self.errorsDeque.append(messagelst) self.errorsDeque.append(messagelst)
except: except:
try: try:
message = args[1].channel.send(embed=embed.set_footer(text="Ce message s'autodétruira dans une minute.", icon_url=self.icon)) message = args[1].channel.send(
embed=embed.set_footer(text="Ce message s'autodétruira dans une minute.", icon_url=self.icon))
messagelst = [message.channel.id, message.id] messagelst = [message.channel.id, message.id]
self.errorsDeque.append(messagelst) self.errorsDeque.append(messagelst)
except: except:
pass pass
for chanid in self.devchanids: for chanid in self.devchanids:
try: try:
await self.client.get_channel(chanid).send(embed=embed.set_footer(text="Ce message ne s'autodétruira pas.", icon_url=self.icon)) await self.client.get_channel(chanid).send(
embed=embed.set_footer(text="Ce message ne s'autodétruira pas.", icon_url=self.icon))
except: except:
pass pass
self.saveObject(self.errorsDeque, 'errorsDeque') self.saveObject(self.errorsDeque, 'errorsDeque')

View File

@ -1,11 +1,13 @@
# dummy module # dummy module
import asyncio
import fractale.source.main
import random
import discord
import os import os
from PIL import Image import random
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
import discord
import fractale.source.main
from PIL import Image
class MainClass(): class MainClass():
def __init__(self, client, modules, owners, prefix): def __init__(self, client, modules, owners, prefix):
self.client = client self.client = client
@ -20,14 +22,32 @@ class MainClass():
self.interactive = True self.interactive = True
self.color = 0x78ffc3 self.color = 0x78ffc3
self.fractals = { self.fractals = {
"von_koch_curve_flake":{"Type":"Figures", "Max":((5000,5000), 5000, 10), "Min":((0,0),0,1), "Default":"(2500 2500) 2000 5 #ffffff 1", "Indication":"(départ) (arrivée) longueur iterations color bg stroke", "ParseData":"pfixi"}, "von_koch_curve_flake": {"Type": "Figures", "Max": ((5000, 5000), 5000, 10), "Min": ((0, 0), 0, 1),
"von_koch_curve":{"Type":"Figures", "Max":((5000,5000),(5000,5000),10), "Min":((0,0),(0,0),1), "Default":"(0 2500) (5000 2500) 5 #ffffff 1", "Indication":"(départ) (arrivée) iterations color bg stroke", "ParseData":"ppixi"}, "Default": "(2500 2500) 2000 5 #ffffff 1",
"blanc_manger":{"Type":"Figures", "Max":((5000,5000),(5000,5000),10), "Min":((0,0),(0,0),1), "Default":"(1000 1000) (4000 4000) 7 #ffffff 1", "Indication":"(départ) (arrivée) iterations color bg stroke", "ParseData":"ppixi"}, "Indication": "(départ) (arrivée) longueur iterations color bg stroke",
"dragon":{"Type":"Lsystem", "Max":((5000,5000), 2500,19), "Min":((0,0),1,1), "Default":"(2500 2500)", "Indication":"(origine) longueur iterations color bg stroke", "ParseData":"pfixi"}, "ParseData": "pfixi"},
"sierpinski_triangle":{"Type":"Lsystem", "Max":((5000,5000),2500,11), "Min":((0,0),0,1), "Default":"(0 0)", "Indication":"(origine) longueur iterations color bg stroke", "ParseData":"pfixi"}, "von_koch_curve": {"Type": "Figures", "Max": ((5000, 5000), (5000, 5000), 10), "Min": ((0, 0), (0, 0), 1),
"fractal_plant":{"Type":"Lsystem", "Max":((5000,5000),2500,8), "Min":((0,0),0,1), "Default":"(0 2500)", "Indication":"(origine) longueur iterations color bg stroke", "ParseData":"pfixi"}, "Default": "(0 2500) (5000 2500) 5 #ffffff 1",
"koch_curve_right_angle":{"Type":"Lsystem", "Max":((5000,5000),2500,9), "Min":((0,0),0,1), "Default":"(0 5000)", "Indication":"(origine) longueur iterations color bg stroke", "ParseData":"pfixi"}, "Indication": "(départ) (arrivée) iterations color bg stroke", "ParseData": "ppixi"},
"fractal_binary_tree":{"Type":"Lsystem", "Max":((5000,5000),2500,15), "Min":((0,0),0,1), "Default":"(0 0)", "Indication":"(origine) longueur iterations color bg stroke", "ParseData":"pfixi"} "blanc_manger": {"Type": "Figures", "Max": ((5000, 5000), (5000, 5000), 10), "Min": ((0, 0), (0, 0), 1),
"Default": "(1000 1000) (4000 4000) 7 #ffffff 1",
"Indication": "(départ) (arrivée) iterations color bg stroke", "ParseData": "ppixi"},
"dragon": {"Type": "Lsystem", "Max": ((5000, 5000), 2500, 19), "Min": ((0, 0), 1, 1),
"Default": "(2500 2500)", "Indication": "(origine) longueur iterations color bg stroke",
"ParseData": "pfixi"},
"sierpinski_triangle": {"Type": "Lsystem", "Max": ((5000, 5000), 2500, 11), "Min": ((0, 0), 0, 1),
"Default": "(0 0)", "Indication": "(origine) longueur iterations color bg stroke",
"ParseData": "pfixi"},
"fractal_plant": {"Type": "Lsystem", "Max": ((5000, 5000), 2500, 8), "Min": ((0, 0), 0, 1),
"Default": "(0 2500)", "Indication": "(origine) longueur iterations color bg stroke",
"ParseData": "pfixi"},
"koch_curve_right_angle": {"Type": "Lsystem", "Max": ((5000, 5000), 2500, 9), "Min": ((0, 0), 0, 1),
"Default": "(0 5000)",
"Indication": "(origine) longueur iterations color bg stroke",
"ParseData": "pfixi"},
"fractal_binary_tree": {"Type": "Lsystem", "Max": ((5000, 5000), 2500, 15), "Min": ((0, 0), 0, 1),
"Default": "(0 0)", "Indication": "(origine) longueur iterations color bg stroke",
"ParseData": "pfixi"}
} }
self.help = """\ self.help = """\
</prefix>fractale [fractale] [nombre d'itérations] </prefix>fractale [fractale] [nombre d'itérations]
@ -37,7 +57,6 @@ class MainClass():
```..: Toutes les fractales: ```..: Toutes les fractales:
%s```""" % '\n'.join(['......: %s' % t for t in self.fractals.keys()]) %s```""" % '\n'.join(['......: %s' % t for t in self.fractals.keys()])
def parse(self, inp): def parse(self, inp):
retDic = {"Success": False, "Message": "", "Result": ()} retDic = {"Success": False, "Message": "", "Result": ()}
# Parsing the fractal name and storing the corresponding dic into a variable # Parsing the fractal name and storing the corresponding dic into a variable
@ -55,12 +74,14 @@ class MainClass():
elif char == ')': elif char == ')':
parentheses_count -= 1 parentheses_count -= 1
if not (-1 < parentheses_count < 2): if not (-1 < parentheses_count < 2):
retDic.update({"Success":False, "Message":"Usage invalide de parentheses au charactère numéro %s (à partir d'après le nom de la fractale)."%i}) retDic.update({"Success": False,
"Message": "Usage invalide de parentheses au charactère numéro %s (à partir d'après le nom de la fractale)." % i})
return (retDic) return (retDic)
# Here, we have a coherent parentheses usage # Here, we have a coherent parentheses usage
if ',' in arg: if ',' in arg:
retDic.update({"Success":False, "Message":"Les virgules n'ont pas leur place dans les paramètres de génération. Il ne doit y avoir que des espaces uniques."}) retDic.update({"Success": False,
"Message": "Les virgules n'ont pas leur place dans les paramètres de génération. Il ne doit y avoir que des espaces uniques."})
return (retDic) return (retDic)
# parsing the fractal # parsing the fractal
@ -74,12 +95,14 @@ class MainClass():
int(args[i]) int(args[i])
int(args[i + 1]) int(args[i + 1])
except: except:
retDic.update({"Success":False, "Message":"Les valeurs ne sont pas du bon type. (nombre entiers attendus pour les coordonnées d'un point)"}) retDic.update({"Success": False,
"Message": "Les valeurs ne sont pas du bon type. (nombre entiers attendus pour les coordonnées d'un point)"})
return (retDic) return (retDic)
parsed_args.append((int(args[i]), int(args[i + 1]))) parsed_args.append((int(args[i]), int(args[i + 1])))
i += 2 i += 2
else: else:
parsed_args.append(self.parse(inp.split(' ')[0]+' '+fractal['Default'])['Result'][len(parsed_args)]) parsed_args.append(
self.parse(inp.split(' ')[0] + ' ' + fractal['Default'])['Result'][len(parsed_args)])
i += 1 i += 1
elif parse == 'f': elif parse == 'f':
@ -87,12 +110,14 @@ class MainClass():
try: try:
float(args[i]) float(args[i])
except: except:
retDic.update({"Success":False, "Message":"Les valeurs ne sont pas du bon type. (Nombre à virgule flottante attendu (mettre un point pour la virgule))"}) retDic.update({"Success": False,
"Message": "Les valeurs ne sont pas du bon type. (Nombre à virgule flottante attendu (mettre un point pour la virgule))"})
return (retDic) return (retDic)
parsed_args.append(float(args[i])) parsed_args.append(float(args[i]))
i += 1 i += 1
else: else:
parsed_args.append(self.parse(inp.split(' ')[0]+' '+fractal['Default'])['Result'][len(parsed_args)]) parsed_args.append(
self.parse(inp.split(' ')[0] + ' ' + fractal['Default'])['Result'][len(parsed_args)])
i += 1 i += 1
elif parse == 'i': elif parse == 'i':
@ -102,12 +127,14 @@ class MainClass():
except: except:
print(args[i]) print(args[i])
print(i) print(i)
retDic.update({"Success":False, "Message":"Les valeurs ne sont pas du bon type. (Nombre entier attendu)"}) retDic.update({"Success": False,
"Message": "Les valeurs ne sont pas du bon type. (Nombre entier attendu)"})
return (retDic) return (retDic)
parsed_args.append(int(args[i])) parsed_args.append(int(args[i]))
i += 1 i += 1
else: else:
parsed_args.append(self.parse(inp.split(' ')[0]+' '+fractal['Default'])['Result'][len(parsed_args)]) parsed_args.append(
self.parse(inp.split(' ')[0] + ' ' + fractal['Default'])['Result'][len(parsed_args)])
i += 1 i += 1
elif parse == 'x': elif parse == 'x':
@ -118,12 +145,14 @@ class MainClass():
else: else:
raise raise
except: except:
retDic.update({"Success":False, "Message":"Les valeurs ne sont pas du bon type. (Valeur hexadécimale attendue)"}) retDic.update({"Success": False,
"Message": "Les valeurs ne sont pas du bon type. (Valeur hexadécimale attendue)"})
return (retDic) return (retDic)
parsed_args.append(int(args[i].replace('#', '0x'), 16)) parsed_args.append(int(args[i].replace('#', '0x'), 16))
i += 1 i += 1
else: else:
parsed_args.append(self.parse(inp.split(' ')[0]+' '+fractal['Default'])['Result'][len(parsed_args)]) parsed_args.append(
self.parse(inp.split(' ')[0] + ' ' + fractal['Default'])['Result'][len(parsed_args)])
i += 1 i += 1
retDic.update({"Success": True, "Result": parsed_args}) retDic.update({"Success": True, "Result": parsed_args})
return (retDic) return (retDic)
@ -137,22 +166,26 @@ class MainClass():
fig = fractale.source.main.Figures(im=im) # here fig = fractale.source.main.Figures(im=im) # here
if len(args) == 1: if len(args) == 1:
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve_flake,*((2500, 2500), 2000, 5)) await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve_flake,
*((2500, 2500), 2000, 5))
elif args[1].lower() == "blanc_manger": elif args[1].lower() == "blanc_manger":
iterations = 7 iterations = 7
if len(args) > 2 and int(args[2]) <= 20: if len(args) > 2 and int(args[2]) <= 20:
iterations = int(args[2]) iterations = int(args[2])
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.blanc_manger,*((1000, 1000), (4000, 4000), iterations)) await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.blanc_manger,
*((1000, 1000), (4000, 4000), iterations))
elif args[1].lower() == "von_koch_curve_flake": elif args[1].lower() == "von_koch_curve_flake":
iterations = 5 iterations = 5
if len(args) > 2 and int(args[2]) <= 7: if len(args) > 2 and int(args[2]) <= 7:
iterations = int(args[2]) iterations = int(args[2])
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve_flake,*((2500, 2500), 2000, iterations)) await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve_flake,
*((2500, 2500), 2000, iterations))
elif args[1].lower() == "von_koch_curve": elif args[1].lower() == "von_koch_curve":
iterations = 5 iterations = 5
if len(args) > 2 and int(args[2]) <= 7: if len(args) > 2 and int(args[2]) <= 7:
iterations = int(args[2]) iterations = int(args[2])
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve,*((0, 2500), (5000,2500), iterations)) await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve,
*((0, 2500), (5000, 2500), iterations))
else: else:
await self.modules['help'][1].send_help(message.channel, self) await self.modules['help'][1].send_help(message.channel, self)
return # here return # here

View File

@ -1,6 +1,7 @@
# dummy module # dummy module
import asyncio
import os import os
class MainClass(): class MainClass():
def __init__(self, client, modules, owners, prefix): def __init__(self, client, modules, owners, prefix):
self.client = client self.client = client
@ -22,6 +23,7 @@ class MainClass():
git fetch --all git fetch --all
git reset --hard origin/<branch_name>``` git reset --hard origin/<branch_name>```
""" """
async def on_message(self, message): async def on_message(self, message):
args = message.content.split(' ') args = message.content.split(' ')
if len(args) == 2 and args[1] == 'update': if len(args) == 2 and args[1] == 'update':

View File

@ -1,5 +1,6 @@
import asyncio
import discord import discord
class MainClass(): class MainClass():
async def auth(self, user, moduleName): async def auth(self, user, moduleName):
if user.id in self.owners: if user.id in self.owners:
@ -13,6 +14,7 @@ class MainClass():
for roleid in self.modules[moduleName][1].authlist: for roleid in self.modules[moduleName][1].authlist:
if roleid in [r.id for r in guild.get_member(user.id).roles]: if roleid in [r.id for r in guild.get_member(user.id).roles]:
return True return True
def __init__(self, client, modules, owners, prefix): def __init__(self, client, modules, owners, prefix):
self.client = client self.client = client
self.modules = modules self.modules = modules
@ -35,6 +37,7 @@ class MainClass():
</prefix>help all </prefix>help all
=> Affiche les aides de tous les modules => Affiche les aides de tous les modules
""" """
async def on_message(self, message): async def on_message(self, message):
args = message.content.lower().split(' ') args = message.content.lower().split(' ')
if len(args) == 2 and args[1] == 'list': if len(args) == 2 and args[1] == 'list':
@ -43,13 +46,21 @@ class MainClass():
if self.modules[moduleName][1].interactive and await self.auth(message.author, moduleName): if self.modules[moduleName][1].interactive and await self.auth(message.author, moduleName):
embed.add_field(name=moduleName.capitalize(), value=self.modules[moduleName][1].description) embed.add_field(name=moduleName.capitalize(), value=self.modules[moduleName][1].description)
await message.channel.send(embed=embed) await message.channel.send(embed=embed)
elif len(args)==2 and args[1] in list(self.modules.keys()) and self.modules[args[1]][1].interactive and await self.auth(message.author, args[1]): elif len(args) == 2 and args[1] in list(self.modules.keys()) and self.modules[args[1]][
await message.channel.send(embed=discord.Embed(title="[{0}] - Aide".format(args[1].capitalize()), description=self.modules[args[1]][1].help.replace("</prefix>", self.prefix), color=self.modules[args[1]][1].color)) 1].interactive and await self.auth(message.author, args[1]):
await message.channel.send(embed=discord.Embed(title="[{0}] - Aide".format(args[1].capitalize()),
description=self.modules[args[1]][1].help.replace(
"</prefix>", self.prefix),
color=self.modules[args[1]][1].color))
elif len(args) == 2 and args[1] == 'all': elif len(args) == 2 and args[1] == 'all':
async with message.channel.typing(): async with message.channel.typing():
for moduleName in list(self.modules.keys()): for moduleName in list(self.modules.keys()):
if self.modules[moduleName][1].interactive and await self.auth(message.author, moduleName): if self.modules[moduleName][1].interactive and await self.auth(message.author, moduleName):
await message.channel.send(embed=discord.Embed(title="[{0}] - Aide".format(moduleName.capitalize()), description=self.modules[moduleName][1].help.replace("</prefix>", self.prefix), color=self.modules[moduleName][1].color)) await message.channel.send(
embed=discord.Embed(title="[{0}] - Aide".format(moduleName.capitalize()),
description=self.modules[moduleName][1].help.replace("</prefix>",
self.prefix),
color=self.modules[moduleName][1].color))
else: else:
await self.modules['help'][1].send_help(message.channel, self) await self.modules['help'][1].send_help(message.channel, self)
@ -59,4 +70,7 @@ class MainClass():
if module == listpck[1]: if module == listpck[1]:
moduleName = name moduleName = name
break break
await channel.send(embed=discord.Embed(title="[{0}] - Aide".format(moduleName.capitalize()), description=self.modules[moduleName][1].help.replace("</prefix>", self.prefix), color=self.modules[moduleName][1].color)) await channel.send(embed=discord.Embed(title="[{0}] - Aide".format(moduleName.capitalize()),
description=self.modules[moduleName][1].help.replace("</prefix>",
self.prefix),
color=self.modules[moduleName][1].color))

View File

@ -1,12 +1,15 @@
import discord
import asyncio
import os
import importlib import importlib
import shutil import os
import random import random
import shutil
import time import time
import discord
temp_dir = "temp_load" temp_dir = "temp_load"
moduleFiles = "modules" moduleFiles = "modules"
class MainClass(): class MainClass():
def __init__(self, client, modules, owners, prefix): def __init__(self, client, modules, owners, prefix):
if os.path.exists("storage/" + moduleFiles + "/" + temp_dir): if os.path.exists("storage/" + moduleFiles + "/" + temp_dir):
@ -50,56 +53,76 @@ class MainClass():
==> Unique module ou liste de module séparés par des virgules ==> Unique module ou liste de module séparés par des virgules
""" """
self.states.update({'modules': 'initialized'}) self.states.update({'modules': 'initialized'})
async def on_message(self, message): async def on_message(self, message):
error = None error = None
args = message.content.split(" ") args = message.content.split(" ")
if len(args) == 2 and args[1] == 'list': if len(args) == 2 and args[1] == 'list':
await message.channel.send(embed=discord.Embed(title="[Modules] - Modules list", description="```PYTHON\n{0}```".format(str(self.states).replace(',', '\n,')))) await message.channel.send(embed=discord.Embed(title="[Modules] - Modules list",
description="```PYTHON\n{0}```".format(
str(self.states).replace(',', '\n,'))))
elif len(args) == 3 and args[1] in ['enable', 'disable', 'reload']: elif len(args) == 3 and args[1] in ['enable', 'disable', 'reload']:
if args[1] == 'enable': if args[1] == 'enable':
for moduleName in args[2].split(','): for moduleName in args[2].split(','):
if moduleName + '.py' in os.listdir('modules'): if moduleName + '.py' in os.listdir('modules'):
try: try:
self.enable_module(moduleName) self.enable_module(moduleName)
await message.channel.send(message.author.mention + ", le module {0} a été activé".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} a été activé".format(moduleName))
except Exception as e: except Exception as e:
error = e error = e
await message.channel.send(message.author.mention + ", le module {0} **n'a pas pu être activé**".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} **n'a pas pu être activé**".format(
moduleName))
else: else:
await message.channel.send(message.author.mention + ", le module {0} n'existe pas.".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} n'existe pas.".format(moduleName))
elif args[1] == 'disable': elif args[1] == 'disable':
for moduleName in args[2].split(','): for moduleName in args[2].split(','):
if moduleName == 'modules': if moduleName == 'modules':
await message.channel.send(message.author.mention + ", le module {0} ne peut pas être désactivé car il est nécéssaire pour gérer les modules.".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} ne peut pas être désactivé car il est nécéssaire pour gérer les modules.".format(
moduleName))
else: else:
if moduleName + '.py' in os.listdir('modules'): if moduleName + '.py' in os.listdir('modules'):
self.unload_module(moduleName) self.unload_module(moduleName)
await message.channel.send(message.author.mention + ", le module {0} a été désactivé.".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} a été désactivé.".format(moduleName))
else: else:
await message.channel.send(message.author.mention + ", le module {0} n'existe pas.".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} n'existe pas.".format(moduleName))
elif args[1] == 'reload': elif args[1] == 'reload':
for moduleName in args[2].split(','): for moduleName in args[2].split(','):
if moduleName == 'modules': if moduleName == 'modules':
await message.channel.send(message.author.mention + ", le module {0} ne peut pas être rechargé car il est nécéssaire pour gérer les modules.".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} ne peut pas être rechargé car il est nécéssaire pour gérer les modules.".format(
moduleName))
else: else:
if moduleName in self.modules.keys(): if moduleName in self.modules.keys():
self.unload_module(moduleName) self.unload_module(moduleName)
await message.channel.send(message.author.mention + ", le module {0} a été désactivé.".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} a été désactivé.".format(moduleName))
else: else:
await message.channel.send(message.author.mention + ", le module {0} n'est pas chargé.".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} n'est pas chargé.".format(moduleName))
if moduleName + '.py' in os.listdir('modules'): if moduleName + '.py' in os.listdir('modules'):
try: try:
self.enable_module(moduleName) self.enable_module(moduleName)
await message.channel.send(message.author.mention + ", le module {0} a été activé".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} a été activé".format(moduleName))
except Exception as e: except Exception as e:
error = e error = e
await message.channel.send(message.author.mention + ", le module {0} **n'a pas pu être activé**".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} **n'a pas pu être activé**".format(
moduleName))
else: else:
await message.channel.send(message.author.mention + ", le module {0} n'existe pas.".format(moduleName)) await message.channel.send(
message.author.mention + ", le module {0} n'existe pas.".format(moduleName))
else: else:
await self.modules['help'][1].send_help(message.channel, self) await self.modules['help'][1].send_help(message.channel, self)
if error: if error:
raise error raise error
async def on_ready(self): async def on_ready(self):
error = None error = None
for fileName in os.listdir('modules'): for fileName in os.listdir('modules'):
@ -110,6 +133,7 @@ class MainClass():
error = e error = e
if error: if error:
raise error raise error
def enable_module(self, moduleName): def enable_module(self, moduleName):
self.load_module(moduleName) self.load_module(moduleName)
self.init_module(moduleName) self.init_module(moduleName)
@ -118,7 +142,9 @@ class MainClass():
if moduleName + ".py" in os.listdir('modules'): if moduleName + ".py" in os.listdir('modules'):
if not moduleName in list(self.states.keys()) or self.states[moduleName] == 'not loaded': if not moduleName in list(self.states.keys()) or self.states[moduleName] == 'not loaded':
try: try:
tmpstr=str("storage/"+moduleFiles+"/"+temp_dir+"/"+moduleName+"-%s.py")%random.randint(1,100000000000000000000000000000000) tmpstr = str(
"storage/" + moduleFiles + "/" + temp_dir + "/" + moduleName + "-%s.py") % random.randint(1,
100000000000000000000000000000000)
shutil.copy2("modules/%s.py" % moduleName, tmpstr) shutil.copy2("modules/%s.py" % moduleName, tmpstr)
time.sleep(0.1) time.sleep(0.1)
self.modules.update({moduleName: [importlib.import_module(tmpstr.replace('/', '.')[:-3:])]}) self.modules.update({moduleName: [importlib.import_module(tmpstr.replace('/', '.')[:-3:])]})
@ -128,17 +154,20 @@ class MainClass():
print("[ERROR] Le module {0} n'a pas pu être chargé.".format(moduleName)) print("[ERROR] Le module {0} n'a pas pu être chargé.".format(moduleName))
self.unload_module(moduleName) self.unload_module(moduleName)
raise raise
def init_module(self, moduleName): def init_module(self, moduleName):
if moduleName + ".py" in os.listdir('modules'): if moduleName + ".py" in os.listdir('modules'):
if self.states[moduleName] == 'loaded': if self.states[moduleName] == 'loaded':
try: try:
self.modules[moduleName].append(self.modules[moduleName][0].MainClass(self.client, self.modules, self.owners, self.prefix)) self.modules[moduleName].append(
self.modules[moduleName][0].MainClass(self.client, self.modules, self.owners, self.prefix))
print("Module {0} initialisé.".format(moduleName)) print("Module {0} initialisé.".format(moduleName))
self.states[moduleName] = 'initialized' self.states[moduleName] = 'initialized'
except: except:
print("[ERROR] Le module {0} n'a pas pu être initialisé.".format(moduleName)) print("[ERROR] Le module {0} n'a pas pu être initialisé.".format(moduleName))
self.unload_module(moduleName) self.unload_module(moduleName)
raise raise
def unload_module(self, moduleName): def unload_module(self, moduleName):
if moduleName + ".py" in os.listdir('modules'): if moduleName + ".py" in os.listdir('modules'):
self.states[moduleName] = 'not loaded' self.states[moduleName] = 'not loaded'

View File

@ -1,5 +1,3 @@
import asyncio
class MainClass(): class MainClass():
def __init__(self, client, modules, owners, prefix): def __init__(self, client, modules, owners, prefix):
self.client = client self.client = client
@ -17,6 +15,7 @@ class MainClass():
self.help = """\ self.help = """\
</prefix>restart </prefix>restart
""" """
async def on_message(self, message): async def on_message(self, message):
await message.channel.send(message.author.mention + ", Le bot va redémarrer...") await message.channel.send(message.author.mention + ", Le bot va redémarrer...")
await self.client.logout() await self.client.logout()