Ton bot mais en respectant la PEP8
This commit is contained in:
parent
1117c77d9b
commit
c4d3a98726
82
main.py
82
main.py
@ -1,12 +1,16 @@
|
||||
#!/usr/bin/python3
|
||||
import discord
|
||||
import os
|
||||
import importlib
|
||||
import os
|
||||
import traceback
|
||||
|
||||
import discord
|
||||
|
||||
client = discord.Client()
|
||||
prefix=";"
|
||||
modules={} # format : {'modulename':[module, initializedclass]}
|
||||
owners=[281166473102098433, 318866596502306816, 436105272310759426]
|
||||
prefix = ";"
|
||||
modules = {} # format : {'modulename':[module, initializedclass]}
|
||||
owners = [281166473102098433, 318866596502306816, 436105272310759426]
|
||||
|
||||
|
||||
async def auth(user, moduleName):
|
||||
if user.id in owners:
|
||||
return True
|
||||
@ -24,20 +28,21 @@ async def auth(user, moduleName):
|
||||
@client.event
|
||||
async def on_ready():
|
||||
print("Bienvenue, {0.user}, l'heure est venue de faire des fractales.".format(client))
|
||||
panic=False
|
||||
error=None
|
||||
panic = False
|
||||
error = None
|
||||
|
||||
async def panicLoad():
|
||||
print("--PANIC LOAD--")
|
||||
panic=True
|
||||
modules={}
|
||||
panic = True
|
||||
modules = {}
|
||||
for filename in os.listdir('modules'):
|
||||
if filename.endswith('.py'):
|
||||
try:
|
||||
modules.update({filename[:-3:]:[importlib.import_module('modules.' + filename[:-3:])]})
|
||||
modules.update({filename[:-3:]: [importlib.import_module('modules.' + filename[:-3:])]})
|
||||
print("Module {0} chargé.".format(filename[:-3:]))
|
||||
except:
|
||||
print("[ERROR] Le module {0} n'a pas pu être chargé.".format(filename))
|
||||
#initialisation
|
||||
# initialisation
|
||||
for moduleName in list(modules.keys()):
|
||||
try:
|
||||
modules[moduleName].append(modules[moduleName][0].MainClass(client, modules, owners, prefix))
|
||||
@ -48,7 +53,7 @@ async def on_ready():
|
||||
|
||||
if 'modules.py' in os.listdir('modules'):
|
||||
try:
|
||||
modules.update({'modules':[importlib.import_module('modules.' + 'modules')]})
|
||||
modules.update({'modules': [importlib.import_module('modules.' + 'modules')]})
|
||||
print("Module {0} chargé.".format('modules'))
|
||||
try:
|
||||
modules['modules'].append(modules['modules'][0].MainClass(client, modules, owners, prefix))
|
||||
@ -56,15 +61,15 @@ async def on_ready():
|
||||
try:
|
||||
await modules['modules'][1].on_ready()
|
||||
except Exception as e:
|
||||
error=e
|
||||
error = e
|
||||
except Exception as e:
|
||||
print("[ERROR] Le module {0} n'a pas pu être initialisé.".format('modules'))
|
||||
await panicLoad()
|
||||
error=e
|
||||
error = e
|
||||
except Exception as e:
|
||||
print("[ERROR] Le module {0} n'a pas pu être chargé.".format('modules.py'))
|
||||
await panicLoad()
|
||||
error=e
|
||||
error = e
|
||||
else:
|
||||
await panicLoad()
|
||||
|
||||
@ -74,11 +79,12 @@ async def on_ready():
|
||||
await modules[moduleName][1].on_ready()
|
||||
else:
|
||||
for moduleName in list(modules.keys()):
|
||||
if (not moduleName=='modules') and 'on_ready' in modules[moduleName][1].events:
|
||||
if (not moduleName == 'modules') and 'on_ready' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_ready()
|
||||
if error:
|
||||
raise error
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_error(event, *args, **kwargs):
|
||||
print(traceback.format_exc())
|
||||
@ -86,24 +92,28 @@ async def on_error(event, *args, **kwargs):
|
||||
if 'on_error' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_error(event, *args, **kwargs)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_socket_raw_receive(msg):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_socket_raw_receive' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_socket_raw_receive(msg)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_socket_raw_send(payload):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_socket_raw_send' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_socket_raw_send(payload)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_typing(channel, user, when):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_typing' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_typing(channel, user, when)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_message(message):
|
||||
for moduleName in list(modules.keys()):
|
||||
@ -111,238 +121,278 @@ async def on_message(message):
|
||||
if await auth(message.author, moduleName):
|
||||
await modules[moduleName][1].on_message(message)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_message_delete(message):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_message_delete' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_message_delete(message)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_raw_message_delete(payload):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_raw_message_delete' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_raw_message_delete(payload)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_raw_bulk_message_delete(payload):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_raw_bulk_message_delete' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_raw_bulk_message_delete(payload)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_message_edit(before, after):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_message_edit' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_message_edit(before, after)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_raw_message_edit(payload):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_raw_message_edit' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_raw_message_edit(payload)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_reaction_add(reaction, user):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_reaction_add' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_reaction_add(reaction, user)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_raw_reaction_add(payload):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_raw_reaction_add' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_raw_reaction_add(payload)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_reaction_remove(reaction, user):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_reaction_remove' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_reaction_remove(reaction, user)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_raw_reaction_remove(payload):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_raw_reaction_remove' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_raw_reaction_remove(payload)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_reaction_clear(message, reactions):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_reaction_clear' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_reaction_clear(message, reactions)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_raw_reaction_clear(payload):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_raw_reaction_clear' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_raw_reaction_clear(payload)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_private_channel_delete(channel):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_private_channel_delete' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_private_channel_delete(channel)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_private_channel_create(channel):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_private_channel_create' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_private_channel_create(channel)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_private_channel_update(before, after):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_private_channel_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_private_channel_update(before, after)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_private_channel_pins_update(channel, last_pin):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_private_channel_pins_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_private_channel_pins_update(channel, last_pin)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_channel_delete(channel):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_channel_delete' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_channel_delete(channel)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_channel_create(channel):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_channel_create' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_channel_create(channel)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_channel_update(before, after):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_channel_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_channel_update(before, after)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_channel_pins_update(channel, last_pin):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_channel_pins_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_channel_pins_update(channel, last_pin)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_member_join(member):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_member_join' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_member_join(member)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_member_remove(member):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_member_remove' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_member_remove(member)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_member_update(before, after):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_member_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_member_update(before, after)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_join(guild):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_join' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_join(guild)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_remove(guild):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_remove' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_remove(guild)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_update(before, after):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_update(before, after)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_role_create(role):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_role_create' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_role_create(role)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_role_delete(role):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_role_delete' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_role_delete(role)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_role_update(before, after):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_role_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_role_update(before, after)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_emojis_update(guild, before, after):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_emojis_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_emojis_update(guild, before, after)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_available(guild):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_available' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_available(guild)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_unavailable(guild):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_guild_unavailable' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_guild_unavailable(guild)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_voice_state_update(member, before, after):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_voice_state_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_voice_state_update(member, before, after)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_member_ban(guild, user):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_member_ban' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_member_ban(guild, user)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_member_unban(guild, user):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_member_unban' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_member_unban(guild, user)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_group_join(channel, user):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_group_join' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_group_join(channel, user)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_group_remove(channel, user):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_group_remove' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_group_remove(channel, user)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_relationship_add(relationship):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_relationship_add' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_relationship_add(relationship)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_relationship_remove(relationship):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_relationship_remove' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_relationship_remove(relationship)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_relationship_update(before, after):
|
||||
for moduleName in list(modules.keys()):
|
||||
if 'on_relationship_update' in modules[moduleName][1].events:
|
||||
await modules[moduleName][1].on_relationship_update(before, after)
|
||||
|
||||
|
||||
client.run(os.environ['DISCORD_TOKEN'])
|
||||
|
@ -1,20 +1,20 @@
|
||||
#dummy module
|
||||
import asyncio
|
||||
# dummy module
|
||||
class MainClass():
|
||||
def __init__(self, client, modules, owners, prefix):
|
||||
self.client = client
|
||||
self.modules = modules
|
||||
self.owners = owners
|
||||
self.prefix = prefix
|
||||
self.events=['on_message'] #events list
|
||||
self.command="%sdummy"%self.prefix #command prefix (can be empty to catch every single messages)
|
||||
self.events = ['on_message'] # events list
|
||||
self.command = "%sdummy" % self.prefix # command prefix (can be empty to catch every single messages)
|
||||
|
||||
self.name="Dummy"
|
||||
self.description="Module d'exemple"
|
||||
self.interactive=False
|
||||
self.color=0x000000
|
||||
self.help="""\
|
||||
self.name = "Dummy"
|
||||
self.description = "Module d'exemple"
|
||||
self.interactive = False
|
||||
self.color = 0x000000
|
||||
self.help = """\
|
||||
Aucune fonction.
|
||||
"""
|
||||
|
||||
async def on_message(self, message):
|
||||
print(message.content)
|
||||
|
@ -1,87 +1,99 @@
|
||||
import asyncio
|
||||
import traceback
|
||||
import discord
|
||||
import random
|
||||
import pickle
|
||||
import os.path
|
||||
import collections
|
||||
import os.path
|
||||
import pickle
|
||||
import random
|
||||
import traceback
|
||||
from subprocess import call
|
||||
moduleFiles="errors"
|
||||
|
||||
import discord
|
||||
|
||||
moduleFiles = "errors"
|
||||
|
||||
|
||||
class MainClass():
|
||||
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.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):
|
||||
if self.saveExists(objectname):
|
||||
with open("storage/%s/"%moduleFiles + objectname, "rb") as pickleFile:
|
||||
with open("storage/%s/" % moduleFiles + objectname, "rb") as pickleFile:
|
||||
unpickler = pickle.Unpickler(pickleFile)
|
||||
return unpickler.load()
|
||||
|
||||
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):
|
||||
if not os.path.isdir("storage/%s"%moduleFiles):
|
||||
call(['mkdir', 'storage/%s'%moduleFiles])
|
||||
self.errorsDeque=None
|
||||
self.devchanids=[549662392120901633]
|
||||
self.memes=[
|
||||
if not os.path.isdir("storage/%s" % moduleFiles):
|
||||
call(['mkdir', 'storage/%s' % moduleFiles])
|
||||
self.errorsDeque = None
|
||||
self.devchanids = [549662392120901633]
|
||||
self.memes = [
|
||||
"https://cdn.discordapp.com/avatars/436105272310759426/6e6850c03fba976f45295a76410a6699.png?size=64",
|
||||
"https://cdn.discordapp.com/avatars/281166473102098433/6e92bff42c9f409334e1580c9f666228.png?size=64",
|
||||
"https://cdn.discordapp.com/avatars/318866596502306816/8e1792132f5b9ceaca6f7aea1fd489f0.png?size=64"
|
||||
]
|
||||
self.icon="https://moriya.zapto.org/avatars/5?s=140"
|
||||
self.icon = "https://moriya.zapto.org/avatars/5?s=140"
|
||||
self.client = client
|
||||
self.modules = modules
|
||||
self.owners = owners
|
||||
self.prefix = prefix
|
||||
self.events=['on_error', 'on_message', 'on_ready'] #events list
|
||||
self.command="%slicorne"%self.prefix #command prefix (can be empty to catch every single messages)
|
||||
self.events = ['on_error', 'on_message', 'on_ready'] # events list
|
||||
self.command = "%slicorne" % self.prefix # command prefix (can be empty to catch every single messages)
|
||||
|
||||
self.name="Error Handling"
|
||||
self.description="Module de gestions des erreurs"
|
||||
self.interactive=True
|
||||
self.authlist=[]
|
||||
self.color=0xdb1348
|
||||
self.help="""\
|
||||
self.name = "Error Handling"
|
||||
self.description = "Module de gestions des erreurs"
|
||||
self.interactive = True
|
||||
self.authlist = []
|
||||
self.color = 0xdb1348
|
||||
self.help = """\
|
||||
</prefix>licorne
|
||||
=> Crée une erreur.
|
||||
"""
|
||||
|
||||
async def on_ready(self):
|
||||
if self.saveExists('errorsDeque'):
|
||||
self.errorsDeque=self.loadObject('errorsDeque')
|
||||
self.errorsDeque = self.loadObject('errorsDeque')
|
||||
else:
|
||||
self.errorsDeque=collections.deque()
|
||||
self.errorsDeque = collections.deque()
|
||||
for i in range(len(self.errorsDeque)):
|
||||
try:
|
||||
messagelst=self.errorsDeque.popleft()
|
||||
messagelst = self.errorsDeque.popleft()
|
||||
channel = self.client.get_channel(messagelst[0])
|
||||
delete_message = await channel.get_message(messagelst[1])
|
||||
await delete_message.delete()
|
||||
except:
|
||||
raise
|
||||
self.saveObject(self.errorsDeque, 'errorsDeque')
|
||||
|
||||
async def on_message(self, message):
|
||||
5/0
|
||||
5 / 0
|
||||
|
||||
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
|
||||
try:
|
||||
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]
|
||||
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]
|
||||
self.errorsDeque.append(messagelst)
|
||||
except:
|
||||
try:
|
||||
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]
|
||||
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]
|
||||
self.errorsDeque.append(messagelst)
|
||||
except:
|
||||
pass
|
||||
for chanid in self.devchanids:
|
||||
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:
|
||||
pass
|
||||
self.saveObject(self.errorsDeque, 'errorsDeque')
|
||||
|
@ -1,161 +1,194 @@
|
||||
#dummy module
|
||||
import asyncio
|
||||
import fractale.source.main
|
||||
import random
|
||||
import discord
|
||||
# dummy module
|
||||
import os
|
||||
from PIL import Image
|
||||
import random
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import discord
|
||||
import fractale.source.main
|
||||
from PIL import Image
|
||||
|
||||
|
||||
class MainClass():
|
||||
def __init__(self, client, modules, owners, prefix):
|
||||
self.client = client
|
||||
self.modules = modules
|
||||
self.owners = owners
|
||||
self.prefix = prefix
|
||||
self.events=['on_message'] #events list
|
||||
self.command="%sfractale"%self.prefix #command prefix (can be empty to catch every single messages)
|
||||
self.events = ['on_message'] # events list
|
||||
self.command = "%sfractale" % self.prefix # command prefix (can be empty to catch every single messages)
|
||||
|
||||
self.name="Fractale"
|
||||
self.description="Module de génération de fractales"
|
||||
self.interactive=True
|
||||
self.color=0x78ffc3
|
||||
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":{"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"},
|
||||
"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.name = "Fractale"
|
||||
self.description = "Module de génération de fractales"
|
||||
self.interactive = True
|
||||
self.color = 0x78ffc3
|
||||
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": {"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"},
|
||||
"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]
|
||||
=> Génère une image fractale. (Si on met le nombre d'itérations, on doit mettre le nom de la fractale.)
|
||||
|
||||
-> Valeurs possible pour [fractale]
|
||||
```..: 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):
|
||||
retDic={"Success":False, "Message":"", "Result":()}
|
||||
#Parsing the fractal name and storing the corresponding dic into a variable
|
||||
retDic = {"Success": False, "Message": "", "Result": ()}
|
||||
# Parsing the fractal name and storing the corresponding dic into a variable
|
||||
try:
|
||||
fractal=self.fractals[inp.split(' ')[0]]
|
||||
fractal = self.fractals[inp.split(' ')[0]]
|
||||
except KeyError:
|
||||
retDic.update({"Success":False, "Message":"La fractale %s n'existe pas."%inp.split(' ')[0]})
|
||||
return(retDic)
|
||||
arg=' '.join(inp.split(' ')[1:]) #Stuff after the fractal name
|
||||
#checking for incoherent parentheses usage
|
||||
parentheses_count=0
|
||||
for i,char in enumerate(arg):
|
||||
if char=='(':
|
||||
parentheses_count+=1
|
||||
elif char==')':
|
||||
parentheses_count-=1
|
||||
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})
|
||||
return(retDic)
|
||||
retDic.update({"Success": False, "Message": "La fractale %s n'existe pas." % inp.split(' ')[0]})
|
||||
return (retDic)
|
||||
arg = ' '.join(inp.split(' ')[1:]) # Stuff after the fractal name
|
||||
# checking for incoherent parentheses usage
|
||||
parentheses_count = 0
|
||||
for i, char in enumerate(arg):
|
||||
if char == '(':
|
||||
parentheses_count += 1
|
||||
elif char == ')':
|
||||
parentheses_count -= 1
|
||||
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})
|
||||
return (retDic)
|
||||
|
||||
#Here, we have a coherent parentheses usage
|
||||
# Here, we have a coherent parentheses usage
|
||||
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."})
|
||||
return(retDic)
|
||||
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)
|
||||
|
||||
#parsing the fractal
|
||||
args=arg.replace(')','').replace('(','').split(' ')
|
||||
parsed_args=[]
|
||||
i=0
|
||||
for parse in fractal['ParseData'] :
|
||||
if parse=='p':
|
||||
if args[i]!='*':
|
||||
# parsing the fractal
|
||||
args = arg.replace(')', '').replace('(', '').split(' ')
|
||||
parsed_args = []
|
||||
i = 0
|
||||
for parse in fractal['ParseData']:
|
||||
if parse == 'p':
|
||||
if args[i] != '*':
|
||||
try:
|
||||
int(args[i])
|
||||
int(args[i+1])
|
||||
int(args[i + 1])
|
||||
except:
|
||||
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)
|
||||
parsed_args.append((int(args[i]),int(args[i+1])))
|
||||
i+=2
|
||||
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)
|
||||
parsed_args.append((int(args[i]), int(args[i + 1])))
|
||||
i += 2
|
||||
else:
|
||||
parsed_args.append(self.parse(inp.split(' ')[0]+' '+fractal['Default'])['Result'][len(parsed_args)])
|
||||
i+=1
|
||||
parsed_args.append(
|
||||
self.parse(inp.split(' ')[0] + ' ' + fractal['Default'])['Result'][len(parsed_args)])
|
||||
i += 1
|
||||
|
||||
elif parse=='f':
|
||||
if args[i]!='*':
|
||||
elif parse == 'f':
|
||||
if args[i] != '*':
|
||||
try:
|
||||
float(args[i])
|
||||
except:
|
||||
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)
|
||||
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)
|
||||
parsed_args.append(float(args[i]))
|
||||
i+=1
|
||||
i += 1
|
||||
else:
|
||||
parsed_args.append(self.parse(inp.split(' ')[0]+' '+fractal['Default'])['Result'][len(parsed_args)])
|
||||
i+=1
|
||||
parsed_args.append(
|
||||
self.parse(inp.split(' ')[0] + ' ' + fractal['Default'])['Result'][len(parsed_args)])
|
||||
i += 1
|
||||
|
||||
elif parse=='i':
|
||||
if args[i]!='*':
|
||||
elif parse == 'i':
|
||||
if args[i] != '*':
|
||||
try:
|
||||
int(args[i])
|
||||
except:
|
||||
print(args[i])
|
||||
print(i)
|
||||
retDic.update({"Success":False, "Message":"Les valeurs ne sont pas du bon type. (Nombre entier attendu)"})
|
||||
return(retDic)
|
||||
retDic.update({"Success": False,
|
||||
"Message": "Les valeurs ne sont pas du bon type. (Nombre entier attendu)"})
|
||||
return (retDic)
|
||||
parsed_args.append(int(args[i]))
|
||||
i+=1
|
||||
i += 1
|
||||
else:
|
||||
parsed_args.append(self.parse(inp.split(' ')[0]+' '+fractal['Default'])['Result'][len(parsed_args)])
|
||||
i+=1
|
||||
parsed_args.append(
|
||||
self.parse(inp.split(' ')[0] + ' ' + fractal['Default'])['Result'][len(parsed_args)])
|
||||
i += 1
|
||||
|
||||
elif parse=='x':
|
||||
if args[i]!='*':
|
||||
elif parse == 'x':
|
||||
if args[i] != '*':
|
||||
try:
|
||||
if '#' in args[i]:
|
||||
int(args[i].replace('#','0x'),16)
|
||||
int(args[i].replace('#', '0x'), 16)
|
||||
else:
|
||||
raise
|
||||
except:
|
||||
retDic.update({"Success":False, "Message":"Les valeurs ne sont pas du bon type. (Valeur hexadécimale attendue)"})
|
||||
return(retDic)
|
||||
parsed_args.append(int(args[i].replace('#','0x'),16))
|
||||
i+=1
|
||||
retDic.update({"Success": False,
|
||||
"Message": "Les valeurs ne sont pas du bon type. (Valeur hexadécimale attendue)"})
|
||||
return (retDic)
|
||||
parsed_args.append(int(args[i].replace('#', '0x'), 16))
|
||||
i += 1
|
||||
else:
|
||||
parsed_args.append(self.parse(inp.split(' ')[0]+' '+fractal['Default'])['Result'][len(parsed_args)])
|
||||
i+=1
|
||||
retDic.update({"Success":True, "Result":parsed_args})
|
||||
return(retDic)
|
||||
parsed_args.append(
|
||||
self.parse(inp.split(' ')[0] + ' ' + fractal['Default'])['Result'][len(parsed_args)])
|
||||
i += 1
|
||||
retDic.update({"Success": True, "Result": parsed_args})
|
||||
return (retDic)
|
||||
|
||||
async def on_message(self, message):
|
||||
#await message.channel.send(str(self.parse(message.content[len("%sfractale "%self.prefix):])))
|
||||
#ħere
|
||||
args=message.content.split(" ")
|
||||
tmpstr="/tmp/%s.png"%random.randint(1,10000000)
|
||||
im=Image.new('RGB', (5000, 5000), (0, 0, 0))#here
|
||||
# await message.channel.send(str(self.parse(message.content[len("%sfractale "%self.prefix):])))
|
||||
# ħere
|
||||
args = message.content.split(" ")
|
||||
tmpstr = "/tmp/%s.png" % random.randint(1, 10000000)
|
||||
im = Image.new('RGB', (5000, 5000), (0, 0, 0)) # here
|
||||
|
||||
fig = fractale.source.main.Figures(im=im)#here
|
||||
if len(args)==1 :
|
||||
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve_flake,*((2500, 2500), 2000, 5))
|
||||
elif args[1].lower()=="blanc_manger" :
|
||||
iterations=7
|
||||
if len(args)>2 and int(args[2])<=20:
|
||||
iterations=int(args[2])
|
||||
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.blanc_manger,*((1000, 1000), (4000, 4000), iterations))
|
||||
elif args[1].lower()=="von_koch_curve_flake" :
|
||||
iterations=5
|
||||
if len(args)>2 and int(args[2])<=7:
|
||||
iterations=int(args[2])
|
||||
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve_flake,*((2500, 2500), 2000, iterations))
|
||||
elif args[1].lower()=="von_koch_curve" :
|
||||
iterations=5
|
||||
if len(args)>2 and int(args[2])<=7:
|
||||
iterations=int(args[2])
|
||||
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve,*((0, 2500), (5000,2500), iterations))
|
||||
fig = fractale.source.main.Figures(im=im) # here
|
||||
if len(args) == 1:
|
||||
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve_flake,
|
||||
*((2500, 2500), 2000, 5))
|
||||
elif args[1].lower() == "blanc_manger":
|
||||
iterations = 7
|
||||
if len(args) > 2 and int(args[2]) <= 20:
|
||||
iterations = int(args[2])
|
||||
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.blanc_manger,
|
||||
*((1000, 1000), (4000, 4000), iterations))
|
||||
elif args[1].lower() == "von_koch_curve_flake":
|
||||
iterations = 5
|
||||
if len(args) > 2 and int(args[2]) <= 7:
|
||||
iterations = int(args[2])
|
||||
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve_flake,
|
||||
*((2500, 2500), 2000, iterations))
|
||||
elif args[1].lower() == "von_koch_curve":
|
||||
iterations = 5
|
||||
if len(args) > 2 and int(args[2]) <= 7:
|
||||
iterations = int(args[2])
|
||||
await self.client.loop.run_in_executor(ThreadPoolExecutor(), fig.von_koch_curve,
|
||||
*((0, 2500), (5000, 2500), iterations))
|
||||
else:
|
||||
await self.modules['help'][1].send_help(message.channel, self)
|
||||
return#here
|
||||
im.save(tmpstr)#here
|
||||
return # here
|
||||
im.save(tmpstr) # here
|
||||
await message.channel.send(file=discord.File(tmpstr))
|
||||
os.remove(tmpstr)#here
|
||||
os.remove(tmpstr) # here
|
||||
|
@ -1,36 +1,38 @@
|
||||
#dummy module
|
||||
import asyncio
|
||||
# dummy module
|
||||
import os
|
||||
|
||||
|
||||
class MainClass():
|
||||
def __init__(self, client, modules, owners, prefix):
|
||||
self.client = client
|
||||
self.modules = modules
|
||||
self.owners = owners
|
||||
self.prefix = prefix
|
||||
self.events=['on_message'] #events list
|
||||
self.command="%sgit"%self.prefix #command prefix (can be empty to catch every single messages)
|
||||
self.events = ['on_message'] # events list
|
||||
self.command = "%sgit" % self.prefix # command prefix (can be empty to catch every single messages)
|
||||
|
||||
self.name="Git"
|
||||
self.description="Module de gestion de Git"
|
||||
self.interactive=True
|
||||
self.authlist=[]
|
||||
self.color=0xdc0000
|
||||
self.help="""\
|
||||
self.name = "Git"
|
||||
self.description = "Module de gestion de Git"
|
||||
self.interactive = True
|
||||
self.authlist = []
|
||||
self.color = 0xdc0000
|
||||
self.help = """\
|
||||
</prefix>git update
|
||||
=> Execute les commandes suivantes dans le dossier du bot:
|
||||
```BASH
|
||||
git fetch --all
|
||||
git reset --hard origin/<branch_name>```
|
||||
"""
|
||||
|
||||
async def on_message(self, message):
|
||||
args=message.content.split(' ')
|
||||
if len(args)==2 and args[1]=='update':
|
||||
args = message.content.split(' ')
|
||||
if len(args) == 2 and args[1] == 'update':
|
||||
with os.popen('git fetch --all') as stdin:
|
||||
await message.channel.send(stdin.read())
|
||||
with os.popen('git symbolic-ref HEAD 2>/dev/null') as stdin:
|
||||
branch=stdin.read().replace('refs/heads/', '')
|
||||
with os.popen('git reset --hard origin/%s'%branch) as stdin:
|
||||
branch = stdin.read().replace('refs/heads/', '')
|
||||
with os.popen('git reset --hard origin/%s' % branch) as stdin:
|
||||
await message.channel.send(stdin.read())
|
||||
await message.channel.send(message.author.mention+", Le dépôt a été mis à jour (fetch + reset --hard).")
|
||||
await message.channel.send(message.author.mention + ", Le dépôt a été mis à jour (fetch + reset --hard).")
|
||||
else:
|
||||
await self.modules['help'][1].send_help(message.channel, self)
|
||||
|
@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import discord
|
||||
|
||||
|
||||
class MainClass():
|
||||
async def auth(self, user, moduleName):
|
||||
if user.id in self.owners:
|
||||
@ -13,19 +14,20 @@ class MainClass():
|
||||
for roleid in self.modules[moduleName][1].authlist:
|
||||
if roleid in [r.id for r in guild.get_member(user.id).roles]:
|
||||
return True
|
||||
|
||||
def __init__(self, client, modules, owners, prefix):
|
||||
self.client = client
|
||||
self.modules = modules
|
||||
self.owners = owners
|
||||
self.prefix = prefix
|
||||
self.events=['on_message'] #events list
|
||||
self.command="%shelp"%self.prefix #command prefix (can be empty to catch every single messages)
|
||||
self.events = ['on_message'] # events list
|
||||
self.command = "%shelp" % self.prefix # command prefix (can be empty to catch every single messages)
|
||||
|
||||
self.name="Aide"
|
||||
self.description="Module d'aide"
|
||||
self.interactive=True
|
||||
self.color=0x3c9653
|
||||
self.help="""\
|
||||
self.name = "Aide"
|
||||
self.description = "Module d'aide"
|
||||
self.interactive = True
|
||||
self.color = 0x3c9653
|
||||
self.help = """\
|
||||
</prefix>help list
|
||||
=> Affiche une liste des modules ainsi qu'une description
|
||||
|
||||
@ -35,28 +37,40 @@ class MainClass():
|
||||
</prefix>help all
|
||||
=> Affiche les aides de tous les modules
|
||||
"""
|
||||
|
||||
async def on_message(self, message):
|
||||
args=message.content.lower().split(' ')
|
||||
if len(args)==2 and args[1]=='list':
|
||||
embed=discord.Embed(title="[Aide] - Liste des modules", color=self.color)
|
||||
args = message.content.lower().split(' ')
|
||||
if len(args) == 2 and args[1] == 'list':
|
||||
embed = discord.Embed(title="[Aide] - Liste des modules", color=self.color)
|
||||
for moduleName in list(self.modules.keys()):
|
||||
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)
|
||||
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]):
|
||||
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] in list(self.modules.keys()) and self.modules[args[1]][
|
||||
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':
|
||||
async with message.channel.typing():
|
||||
for moduleName in list(self.modules.keys()):
|
||||
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:
|
||||
await self.modules['help'][1].send_help(message.channel, self)
|
||||
|
||||
async def send_help(self, channel, module):
|
||||
moduleName=None
|
||||
moduleName = None
|
||||
for name, listpck in self.modules.items():
|
||||
if module == listpck[1]:
|
||||
moduleName=name
|
||||
moduleName = name
|
||||
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))
|
||||
|
@ -1,39 +1,42 @@
|
||||
import discord
|
||||
import asyncio
|
||||
import os
|
||||
import importlib
|
||||
import shutil
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import time
|
||||
temp_dir="temp_load"
|
||||
moduleFiles="modules"
|
||||
|
||||
import discord
|
||||
|
||||
temp_dir = "temp_load"
|
||||
moduleFiles = "modules"
|
||||
|
||||
|
||||
class MainClass():
|
||||
def __init__(self, client, modules, owners, prefix):
|
||||
if os.path.exists("storage/"+moduleFiles+"/"+temp_dir):
|
||||
shutil.rmtree("storage/"+moduleFiles+"/"+temp_dir)
|
||||
if not os.path.exists("storage/"+moduleFiles):
|
||||
os.mkdir("storage/"+moduleFiles)
|
||||
os.mkdir("storage/"+moduleFiles+"/"+temp_dir)
|
||||
self.states={}
|
||||
if os.path.exists("storage/" + moduleFiles + "/" + temp_dir):
|
||||
shutil.rmtree("storage/" + moduleFiles + "/" + temp_dir)
|
||||
if not os.path.exists("storage/" + moduleFiles):
|
||||
os.mkdir("storage/" + moduleFiles)
|
||||
os.mkdir("storage/" + moduleFiles + "/" + temp_dir)
|
||||
self.states = {}
|
||||
for moduleName in os.listdir('modules'):
|
||||
if moduleName.endswith(".py"):
|
||||
self.states.update({moduleName[:-3:]:'not loaded'})
|
||||
self.states.update({moduleName[:-3:]: 'not loaded'})
|
||||
for moduleName in list(modules.keys()):
|
||||
if len(modules[moduleName]) == 2 :
|
||||
self.states.update({moduleName:'initialized'})
|
||||
if len(modules[moduleName]) == 2:
|
||||
self.states.update({moduleName: 'initialized'})
|
||||
self.client = client
|
||||
self.modules = modules
|
||||
self.owners = owners
|
||||
self.prefix=prefix
|
||||
self.events=['on_message', 'on_ready'] #events list
|
||||
self.command="%smodule"%self.prefix #command prefix (can be empty to catch every single messages)
|
||||
self.prefix = prefix
|
||||
self.events = ['on_message', 'on_ready'] # events list
|
||||
self.command = "%smodule" % self.prefix # command prefix (can be empty to catch every single messages)
|
||||
|
||||
self.name="Modules"
|
||||
self.description="Module de gestion des modules"
|
||||
self.interactive=True
|
||||
self.authlist=[549662392120901633]
|
||||
self.color=0x8f3196
|
||||
self.help="""\
|
||||
self.name = "Modules"
|
||||
self.description = "Module de gestion des modules"
|
||||
self.interactive = True
|
||||
self.authlist = [549662392120901633]
|
||||
self.color = 0x8f3196
|
||||
self.help = """\
|
||||
</prefix>modules list
|
||||
=> Liste les modules ainsi que leurs états
|
||||
|
||||
@ -50,66 +53,87 @@ class MainClass():
|
||||
==> Unique module ou liste de module séparés par des virgules
|
||||
"""
|
||||
self.states.update({'modules': 'initialized'})
|
||||
|
||||
async def on_message(self, message):
|
||||
error=None
|
||||
error = None
|
||||
args = message.content.split(" ")
|
||||
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,'))))
|
||||
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,'))))
|
||||
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(','):
|
||||
if moduleName + '.py' in os.listdir('modules'):
|
||||
try:
|
||||
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:
|
||||
error=e
|
||||
await message.channel.send(message.author.mention + ", le module {0} **n'a pas pu être activé**".format(moduleName))
|
||||
error = e
|
||||
await message.channel.send(
|
||||
message.author.mention + ", le module {0} **n'a pas pu être activé**".format(
|
||||
moduleName))
|
||||
else:
|
||||
await message.channel.send(message.author.mention + ", le module {0} n'existe pas.".format(moduleName))
|
||||
elif args[1]=='disable':
|
||||
await message.channel.send(
|
||||
message.author.mention + ", le module {0} n'existe pas.".format(moduleName))
|
||||
elif args[1] == 'disable':
|
||||
for moduleName in args[2].split(','):
|
||||
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:
|
||||
if moduleName + '.py' in os.listdir('modules'):
|
||||
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:
|
||||
await message.channel.send(message.author.mention + ", le module {0} n'existe pas.".format(moduleName))
|
||||
elif args[1]=='reload':
|
||||
await message.channel.send(
|
||||
message.author.mention + ", le module {0} n'existe pas.".format(moduleName))
|
||||
elif args[1] == 'reload':
|
||||
for moduleName in args[2].split(','):
|
||||
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:
|
||||
if moduleName in self.modules.keys():
|
||||
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:
|
||||
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'):
|
||||
try:
|
||||
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:
|
||||
error=e
|
||||
await message.channel.send(message.author.mention + ", le module {0} **n'a pas pu être activé**".format(moduleName))
|
||||
error = e
|
||||
await message.channel.send(
|
||||
message.author.mention + ", le module {0} **n'a pas pu être activé**".format(
|
||||
moduleName))
|
||||
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:
|
||||
await self.modules['help'][1].send_help(message.channel, self)
|
||||
if error:
|
||||
raise error
|
||||
|
||||
async def on_ready(self):
|
||||
error=None
|
||||
error = None
|
||||
for fileName in os.listdir('modules'):
|
||||
try:
|
||||
self.load_module(fileName[:-3:])
|
||||
self.init_module(fileName[:-3:])
|
||||
except Exception as e:
|
||||
error=e
|
||||
error = e
|
||||
if error:
|
||||
raise error
|
||||
|
||||
def enable_module(self, moduleName):
|
||||
self.load_module(moduleName)
|
||||
self.init_module(moduleName)
|
||||
@ -118,27 +142,32 @@ class MainClass():
|
||||
if moduleName + ".py" in os.listdir('modules'):
|
||||
if not moduleName in list(self.states.keys()) or self.states[moduleName] == 'not loaded':
|
||||
try:
|
||||
tmpstr=str("storage/"+moduleFiles+"/"+temp_dir+"/"+moduleName+"-%s.py")%random.randint(1,100000000000000000000000000000000)
|
||||
shutil.copy2("modules/%s.py"%moduleName, tmpstr)
|
||||
tmpstr = str(
|
||||
"storage/" + moduleFiles + "/" + temp_dir + "/" + moduleName + "-%s.py") % random.randint(1,
|
||||
100000000000000000000000000000000)
|
||||
shutil.copy2("modules/%s.py" % moduleName, tmpstr)
|
||||
time.sleep(0.1)
|
||||
self.modules.update({moduleName:[importlib.import_module(tmpstr.replace('/','.')[:-3:])]})
|
||||
self.modules.update({moduleName: [importlib.import_module(tmpstr.replace('/', '.')[:-3:])]})
|
||||
print("Module {0} chargé.".format(moduleName))
|
||||
self.states[moduleName] = 'loaded'
|
||||
except:
|
||||
print("[ERROR] Le module {0} n'a pas pu être chargé.".format(moduleName))
|
||||
self.unload_module(moduleName)
|
||||
raise
|
||||
|
||||
def init_module(self, moduleName):
|
||||
if moduleName + ".py" in os.listdir('modules'):
|
||||
if self.states[moduleName] == 'loaded':
|
||||
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))
|
||||
self.states[moduleName] = 'initialized'
|
||||
except:
|
||||
print("[ERROR] Le module {0} n'a pas pu être initialisé.".format(moduleName))
|
||||
self.unload_module(moduleName)
|
||||
raise
|
||||
|
||||
def unload_module(self, moduleName):
|
||||
if moduleName + ".py" in os.listdir('modules'):
|
||||
self.states[moduleName] = 'not loaded'
|
||||
|
@ -1,22 +1,21 @@
|
||||
import asyncio
|
||||
|
||||
class MainClass():
|
||||
def __init__(self, client, modules, owners, prefix):
|
||||
self.client = client
|
||||
self.modules = modules
|
||||
self.owners = owners
|
||||
self.prefix=prefix
|
||||
self.events=['on_message'] #events list
|
||||
self.command="%srestart"%self.prefix #command prefix (can be empty to catch every single messages)
|
||||
self.prefix = prefix
|
||||
self.events = ['on_message'] # events list
|
||||
self.command = "%srestart" % self.prefix # command prefix (can be empty to catch every single messages)
|
||||
|
||||
self.name="Restart"
|
||||
self.description="Module gérant les redémarrages du bot"
|
||||
self.interactive=True
|
||||
self.authlist=[]
|
||||
self.color=0x000000
|
||||
self.help="""\
|
||||
self.name = "Restart"
|
||||
self.description = "Module gérant les redémarrages du bot"
|
||||
self.interactive = True
|
||||
self.authlist = []
|
||||
self.color = 0x000000
|
||||
self.help = """\
|
||||
</prefix>restart
|
||||
"""
|
||||
|
||||
async def on_message(self, message):
|
||||
await message.channel.send(message.author.mention + ", Le bot va redémarrer...")
|
||||
await self.client.logout()
|
||||
|
Loading…
Reference in New Issue
Block a user