Cogs management

- Cogs file renamed (easier managing)
- Cogs commands in admin cog: cog load/unload/reload/list
This commit is contained in:
voXrey 2023-12-19 22:15:34 +01:00
parent 75f8e041e8
commit 3184035346
5 changed files with 210 additions and 110 deletions

116
cogs/admin.py Normal file
View File

@ -0,0 +1,116 @@
import discord
from discord import app_commands
from discord.app_commands import Choice
from discord.ext import commands
from classes.my_cog import MyCog
class CogGroup(app_commands.Group, name="cog", description="Gérer les cogs"):
def __init__(self, bot: commands.Bot):
super().__init__()
self.bot = bot
@app_commands.command(name="load")
async def cog_load(self, interaction: discord.Interaction, extension: str):
"""
Charge une extension
:param interaction: discord interaction
:param extension: Nom de l'extension
"""
try:
await self.bot.load_extension(f"cogs.{extension.lower()}")
await interaction.response.send_message(f"Extension `{extension}` chargée !")
except commands.ExtensionAlreadyLoaded:
await interaction.response.send_message(f"Extension `{extension}` déjà chargée...")
except commands.ExtensionNotFound:
await interaction.response.send_message(f"Extension `{extension}` non trouvée...")
except Exception as e:
print(e)
await interaction.response.send_message(f"Une erreur inconnue est survenue:\n`{e}`")
@app_commands.command(name="unload")
async def cog_unload(self, interaction: discord.Interaction, extension: str):
"""
Décharge une extension
:param interaction: discord interaction
:param extension: Nom de l'extension
:return:
"""
try:
await self.bot.unload_extension(f"cogs.{extension.lower()}")
await interaction.response.send_message(f"Extension `{extension}` déchargée !")
except commands.ExtensionNotLoaded:
await interaction.response.send_message(f"Extension `{extension}` non chargée...")
except commands.ExtensionNotFound:
await interaction.response.send_message(f"Extension `{extension}` non trouvée...")
except Exception as e:
print(e)
await interaction.response.send_message(f"Une erreur inconnue est survenue:\n`{e}`")
@app_commands.command(name="reload")
async def cog_reload(self, interaction: discord.Interaction, extension: str):
"""
Recharge une extension
:param interaction: discord interaction
:param extension: Nom de l'extension
"""
async def fun():
await self.bot.load_extension(f"cogs.{extension.lower()}")
await interaction.response.send_message(f"Extension `{extension}` rechargée !")
try:
await self.bot.unload_extension(f"cogs.{extension.lower()}")
await fun()
except (commands.ExtensionAlreadyLoaded, commands.ExtensionNotLoaded):
await fun()
except commands.ExtensionNotFound:
await interaction.response.send_message(f"Extension `{extension}` non trouvée...")
except Exception as e:
print(e)
await interaction.response.send_message(f"Une erreur inconnue est survenue:\n`{e}`")
@app_commands.command(name="list")
async def cog_list(self, interaction: discord.Interaction):
"""
Voir la liste des extensions
:param interaction: discord interaction
"""
enabled = [str(ext) for ext in self.bot.extensions]
total_list = self.bot.initial_extensions
disabled = list(set(total_list).difference(enabled))
msg = "✅ **Enabled**\n"
for ext in enabled:
msg += f"* `{ext[5:]}`\n"
msg += "\n❌ **Disabled**\n"
for ext in disabled:
msg += f"* `{ext[5:]}`\n"
embed = discord.Embed(title="Liste des extensions",
description=msg,
color=discord.Color.blurple())
await interaction.response.send_message(embed=embed)
class Admin(MyCog):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
# Add cogs commands group to cog
self.bot.tree.add_command(CogGroup(self.bot))
async def setup(bot):
await bot.add_cog(Admin(bot))

View File

@ -1,16 +0,0 @@
import discord
from discord import app_commands
from discord.app_commands import Choice
from discord.ext import commands
from classes.my_cog import MyCog
class Admin(MyCog):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
async def setup(bot):
await bot.add_cog(Admin(bot))

View File

@ -1,55 +1,55 @@
import discord
import random
import aiohttp
import asyncio
from os import getenv
from dotenv import load_dotenv
from discord import app_commands
from discord import Embed
#from discord.app_commands import Choice
from discord.ext import commands
from classes.my_cog import MyCog
class Fact(MyCog):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
@app_commands.command(name="fact")
async def fact(self, interaction: discord.Interaction, private: bool=False):
"""
Vous reprendriez bien un petit shot de culture G ?
:param interaction: discord interaction
:param private: Garder ce petit bijou pour soi
"""
headers = {
'Authorization': f'Bearer {getenv("WIKIMEDIA_ACCESS_TOKEN")}',
'User-Agent': 'Staticky (https://mp2i-vms.fr)'
}
try:
async with aiohttp.ClientSession() as session:
response = await session.get("https://fr.wikipedia.org/api/rest_v1/page/random/summary", headers=headers)
data = await response.json()
embed = Embed(
title=data.get("title", "Titre inconnu"),
url=data.get("content_urls").get("desktop").get("page"),
description=data.get('extract')
)
embed.set_thumbnail(url=data.get('thumbnail').get('source'))
await interaction.response.send_message("", embed=embed, ephemeral=private)
except Exception as e:
await interaction.response.send_message(f"Le message n'a pas pu être envoyé...\n`Erreur : {e}`",
ephemeral=True)
async def setup(bot):
await bot.add_cog(Fact(bot))
import discord
import random
import aiohttp
import asyncio
from os import getenv
from dotenv import load_dotenv
from discord import app_commands
from discord import Embed
#from discord.app_commands import Choice
from discord.ext import commands
from classes.my_cog import MyCog
class Fact(MyCog):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
@app_commands.command(name="fact")
async def fact(self, interaction: discord.Interaction, private: bool=False):
"""
Vous reprendriez bien un petit shot de culture G ?
:param interaction: discord interaction
:param private: Garder ce petit bijou pour soi
"""
headers = {
'Authorization': f'Bearer {getenv("WIKIMEDIA_ACCESS_TOKEN")}',
'User-Agent': 'Staticky (https://mp2i-vms.fr)'
}
try:
async with aiohttp.ClientSession() as session:
response = await session.get("https://fr.wikipedia.org/api/rest_v1/page/random/summary", headers=headers)
data = await response.json()
embed = Embed(
title=data.get("title", "Titre inconnu"),
url=data.get("content_urls").get("desktop").get("page"),
description=data.get('extract')
)
embed.set_thumbnail(url=data.get('thumbnail').get('source'))
await interaction.response.send_message("", embed=embed, ephemeral=private)
except Exception as e:
await interaction.response.send_message(f"Le message n'a pas pu être envoyé...\n`Erreur : {e}`",
ephemeral=True)
async def setup(bot):
await bot.add_cog(Fact(bot))

View File

@ -1,39 +1,39 @@
import discord
import random
from discord import app_commands
from discord.app_commands import Choice
from discord.ext import commands
from classes.my_cog import MyCog
class Fun(MyCog):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
@app_commands.command(name="chuchoter")
async def chuchoter(self, interaction: discord.Interaction, message: str, channel: discord.TextChannel=None):
"""
Chuchote à Staticky un message qu'il partagera (attention ne lui faites pas aveuglément confiance)
:param interaction: discord interaction
:param channel: Salon dans lequel le message sera partagé
:param message: Message à partagerE
"""
try:
if channel is None:
channel = interaction.channel
to_send = f"**Quelqu'un m'a chuchoté :** \"{message}\""
if random.randint(1, 6) == 1:
to_send += f"\nJe balance, c'est {interaction.user.mention} !"
await channel.send(to_send)
await interaction.response.send_message(f"Message envoyé dans {channel.mention}\n>>> {message}",
ephemeral=True)
except Exception as e:
await interaction.response.send_message(f"Le message n'a pas pu être envoyé...\n`Erreur : {e}`",
ephemeral=True)
async def setup(bot):
await bot.add_cog(Fun(bot))
import discord
import random
from discord import app_commands
from discord.app_commands import Choice
from discord.ext import commands
from classes.my_cog import MyCog
class Fun(MyCog):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
@app_commands.command(name="chuchoter")
async def chuchoter(self, interaction: discord.Interaction, message: str, channel: discord.TextChannel=None):
"""
Chuchote à Staticky un message qu'il partagera (attention ne lui faites pas aveuglément confiance)
:param interaction: discord interaction
:param channel: Salon dans lequel le message sera partagé
:param message: Message à partagerE
"""
try:
if channel is None:
channel = interaction.channel
to_send = f"**Quelqu'un m'a chuchoté :** \"{message}\""
if random.randint(1, 6) == 1:
to_send += f"\nJe balance, c'est {interaction.user.mention} !"
await channel.send(to_send)
await interaction.response.send_message(f"Message envoyé dans {channel.mention}\n>>> {message}",
ephemeral=True)
except Exception as e:
await interaction.response.send_message(f"Le message n'a pas pu être envoyé...\n`Erreur : {e}`",
ephemeral=True)
async def setup(bot):
await bot.add_cog(Fun(bot))