From db76ea2f8d24cc22d2a58e4af0ccafc7af46b584 Mon Sep 17 00:00:00 2001
From: augustin64 <augustin.lucas64@gmail.com>
Date: Fri, 26 Aug 2022 18:34:34 +0200
Subject: [PATCH] Updated status command and added logs command

---
 config_example.py |  3 ++-
 main.py           | 65 +++++++++++++++++++++++++++++++++++++++--------
 2 files changed, 56 insertions(+), 12 deletions(-)

diff --git a/config_example.py b/config_example.py
index 51ccc62..bb387cd 100644
--- a/config_example.py
+++ b/config_example.py
@@ -2,4 +2,5 @@ TOKEN="YOUR-DISCORD-BOT-TOKEN"
 
 allowed_users = ["discorduserid"]
 services = ["services", "you", "want", "to", "monitor"]
-command_prefix = ":"
\ No newline at end of file
+command_prefix = ":"
+logs_dir = "/home/user/logs"
\ No newline at end of file
diff --git a/main.py b/main.py
index 94c40d4..598afa1 100755
--- a/main.py
+++ b/main.py
@@ -1,10 +1,11 @@
 #!/usr/bin/python3
 import asyncio
-import time
 import os
+import subprocess
+import time
 
-import requests
 import discord
+import requests
 from discord.ext import commands
 
 import config
@@ -62,21 +63,38 @@ async def on_ready():
 
 @bot.command(name="status")
 @login_required
-async def status(ctx):
+async def status(ctx, *args):
     """Renvoie le statut des différents services"""
-    embed = discord.Embed(colour=discord.Colour.blue())
-    embed.set_author(name=time.strftime("%m-%d-%Y %H:%M"))
-    for service in config.services:
-        service_status = check_status(service)
+    if len(args) == 0:
+        embed = discord.Embed(colour=discord.Colour.blue())
+        embed.set_author(name=time.strftime("%m-%d-%Y %H:%M"))
+        for service in config.services:
+            service_status = check_status(service)
+            embed.add_field(
+                name=service, value=service_status, inline=False
+            )
+        await ctx.reply(embed=embed)
+    else:
+        if args[0] not in config.services:
+            await ctx.reply(f"Service inconnu `{args[0]}`")
+            return None
+        try:
+            out = subprocess.check_output(["systemctl", "status", args[0]], stderr=subprocess.STDOUT)
+        except Exception as e:
+            out = e.output
+
+        out = out.decode("UTF-8")
+        embed = discord.Embed(colour=discord.Colour.blue())
+        embed.set_author(name=time.strftime("%m-%d-%Y %H:%M"))
         embed.add_field(
-            name=service, value=service_status, inline=False
-        )
-    await ctx.reply(embed=embed)
+                name=args[0], value=f"```\n{out[:min(len(out)-1, 1017)]}```"
+            )
+        await ctx.reply(embed=embed)
 
 
 @bot.command(name="service")
 @login_required
-async def status(ctx, *args):
+async def service(ctx, *args):
     """Exécute une commande systemd"""
     error = None
     commands = ["start", "stop", "enable", "disable", "restart"]
@@ -94,4 +112,29 @@ async def status(ctx, *args):
     await ctx.message.add_reaction("🆗")
 
 
+@bot.command(name="logs")
+@login_required
+async def logs(ctx, *args):
+    """Renvoie des fichier logs"""
+    logs_files = [
+        i[:-4] for i in os.listdir(config.logs_dir) if i.endswith(".txt") and os.path.isfile(os.path.join(config.logs_dir, i))
+    ]
+
+    if len(args) == 0:
+        embed = discord.Embed(colour=discord.Colour.blue())
+        embed.set_author(name=time.strftime("%m-%d-%Y %H:%M"))
+        embed.add_field(
+            name="Fichiers de logs disponibles", value="\n".join(logs_files)
+        )
+        await ctx.reply(embed=embed)
+        return None
+    
+    if args[0] not in logs_files:
+        print(logs_files)
+        await ctx.reply("Ce fichier n'existe pas.")
+        return None
+
+    with open(os.path.join(config.logs_dir, f"{args[0]}.txt"), "r") as fp:
+        await ctx.reply(file=discord.File(fp, filename=f"{args[0]}.txt"))
+
 bot.run(config.TOKEN)