[all] Ca marche chez moi

This commit is contained in:
Louis Chauvet 2020-03-19 18:29:58 +01:00
parent 9ae4114a39
commit 89af9403f1
Signed by: fomys
GPG Key ID: 1ECA046A9615ABA0
7 changed files with 69 additions and 28 deletions

View File

@ -1,5 +1,6 @@
from __future__ import annotations
from enum import Enum
from typing import Dict, Any, Optional

11
main.py
View File

@ -203,13 +203,13 @@ def event(func):
return func(self, *args, **kwargs)
return wrapper
def async_event(func):
"""def async_event(func):
async def wrapper(self, *args, **kwargs):
if self.reloading:
return lambda: None
else:
return func(self, *args, **kwargs)
return wrapper
return wrapper"""
setup_logging()
@ -298,7 +298,6 @@ class LBI(discord.Client):
self.config.save()
except AttributeError as e:
self.error("Module {module} doesn't have MainClass.".format(module=module))
raise
return e
return 0
elif MODULES[module].type == "lua":
@ -344,7 +343,7 @@ class LBI(discord.Client):
for module in self.modules.values():
module["initialized_class"].dispatch(event, *args, **kwargs)
@async_event
#@async_event
async def on_error(self, event_method, *args, **kwargs):
# This event is special because it is call directly
for module in self.modules.values():
@ -420,7 +419,7 @@ class Communication(asyncio.Protocol):
critical = log_communication.critical
name = "Communication"
def __init__(self, client=client1):
def __init__(self, client):
self.client = client
self.transport = None
@ -447,8 +446,6 @@ async def start_bot():
print(os.path.join("/tmp", os.path.dirname(os.path.realpath(__file__))) + ".sock")
loop = asyncio.get_event_loop()
#loop.add_signal_handler(signal.SIGINT, loop.stop)
#loop.set_exception_handler(execption_handler)
t = loop.create_unix_server(Communication,
path=os.path.join("/tmp", os.path.dirname(os.path.realpath(__file__)) + ".sock"))
loop.run_until_complete(t)

View File

@ -156,7 +156,7 @@ class BaseClass:
i += 1
return sub_command, args_, kwargs
async def on_message(self, message):
async def on_message(self, message: discord.Message):
"""Override this function to deactivate command_text parsing"""
await self.parse_command(message)

View File

@ -29,7 +29,7 @@ class MainClass(BaseClassPython):
def __init__(self, client):
super().__init__(client)
self.config.init({"dev_chan":[], "memes":[""], "icon":""})
self.config.init({"dev_chan": [], "memes": [""], "icon": ""})
self.errorsDeque = None
async def on_ready(self):
@ -62,13 +62,13 @@ class MainClass(BaseClassPython):
channel = arg
break
if channel is None:
for _,v in kwargs.items():
for _, v in kwargs.items():
if type(v) == discord.Message:
channel = v.channel
break
if type(v) == discord.TextChannel:
channel = v
break# Create embed
break # Create embed
embed = discord.Embed(
title="[Erreur] Aïe :/",
description="```python\n{0}```".format(traceback.format_exc()),
@ -80,14 +80,14 @@ class MainClass(BaseClassPython):
for chanid in self.config["dev_chan"]:
try:
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
embed=embed.set_footer(text="Ce message ne s'autodétruira pas.", icon_url=self.config["icon"]))
except BaseException as e:
raise e
# Send message to current channel if exists
if channel is not None:
message = await channel.send(embed=embed.set_footer(text="Ce message va s'autodétruire dans une minute",
icon_url=self.config["icon"]))
msg_id = {"chan_id": message.channel.id, "msg_id": message.id}
icon_url=self.config["icon"]))
msg_id = {"channel_id": message.channel.id, "msg_id": message.id}
self.errorsDeque.append(msg_id)
# Save message in errorsDeque now to keep them if a reboot happend during next 60 seconds
self.objects.save_object('errorsDeque', self.errorsDeque)
@ -95,7 +95,7 @@ class MainClass(BaseClassPython):
# Wait 60 seconds and delete message
await asyncio.sleep(60)
try:
channel = self.client.get_channel(msg_id["chan_id"])
channel = self.client.get_channel(msg_id["channel_id"])
delete_message = await channel.fetch_message(msg_id["msg_id"])
await delete_message.delete()
except:

View File

@ -58,11 +58,12 @@ class MainClass(BaseClassPython):
return
for arg in args:
e = self.client.load_module(arg)
if e == 1:
await message.channel.send(f"Module {arg} not exists.")
if e == 2:
await message.channel.send("Module {module} is incompatible.")
await message.channel.send(f"Module {arg} is incompatible.")
elif e:
await message.channel.send("An error occurred during the loading of the module {module}: {error}."
.format(module=arg, error=e))
await message.channel.send(f"An error occurred during the loading of the module {arg}: {e}.")
await self.com_list(message, args, kwargs)
async def com_reload(self, message, args, kwargs):
@ -74,15 +75,13 @@ class MainClass(BaseClassPython):
for module in self.get_all_modules():
e = self.client.unload_module(module)
if e:
await message.channel.send("An error occurred during the loading of the module {module}."
.format(module=module))
await message.channel.send(f"An error occurred during the loading of the module {module}.")
await self.com_list(message, args, kwargs)
return
for arg in args:
e = self.client.unload_module(arg)
if e:
await message.channel.send("An error occurred during the loading of the module {module}."
.format(module=arg))
await message.channel.send(f"An error occurred during the loading of the module {arg}.")
await self.com_list(message, [], [])
async def com_disable(self, message, args, kwargs):
@ -94,15 +93,13 @@ class MainClass(BaseClassPython):
for module in self.get_all_modules():
e = self.client.unload_module(module)
if e:
await message.channel.send("An error occurred during the loading of the module {module}."
.format(module=module))
await message.channel.send(f"An error occurred during the loading of the module {module}.")
await self.com_list(message, args, kwargs)
return
for arg in args:
e = self.client.unload_module(arg)
if e:
await message.channel.send("An error occurred during the loading of the module {module}: {error}."
.format(module=arg, error=e))
await message.channel.send(f"An error occurred during the loading of the module {arg}: {e}.")
await self.com_list(message, [], [])
async def com_list(self, message, args, kwargs):

46
modules/panic/__init__.py Normal file
View File

@ -0,0 +1,46 @@
import subprocess
import discord
from modules.base import BaseClassPython
import time
class MainClass(BaseClassPython):
name = "Panic"
help_active = True
help = {
"description": "Dans quel état est Nikola Tesla",
"commands": {
"`{prefix}{command}`": "Donne l'état actuel de Nikola Tesla",
}
}
color = 0x4fffb6
command_text = "panic"
async def command(self, message, args, kwargs):
temperature = 0
with open("/sys/class/thermal/thermal_zone0/temp") as f:
temperature = int(f.read().rstrip("\n")) / 1000
with open("/proc/cpuinfo") as f:
cpu_count = f.read().count('\n\n')
embed = discord.Embed(title="[Panic] - Infos", color=self.color)
with open("/proc/loadavg") as f:
load_average = ["**" + str(round((val / cpu_count) * 100, 1)) + '%**' for val in
map(float, f.read().split(' ')[0:3])]
with open("/proc/uptime") as f:
uptime = time.gmtime(float(f.read().split(' ')[0]))
uptime = "**" + str(int(time.strftime('%-m', uptime)) - 1) + "** mois, **" + str(
int(time.strftime('%-d', uptime)) - 1) + "** jours, " + time.strftime(
'**%H** heures, **%M** minutes, **%S** secondes.', uptime)
embed.add_field(
name="Température",
value="Nikola est à **{temperature}°C**".format(temperature=temperature))
embed.add_field(
name="Charge moyenne",
value="Nikola est en moyenne, utilisé à :\n sur une minute : %s\n sur cinq minutes : %s\n sur quinze minutes : %s" % tuple(
load_average))
embed.add_field(
name="Temps d'éveil",
value="Nikola est éveillé depuis {uptime}".format(uptime=uptime))
await message.channel.send(embed=embed)

View File