Ajout commandes personnalisés

This commit is contained in:
Mylloon 2021-07-29 00:48:42 +02:00
parent 143e93b3da
commit 19d3d03fa1
6 changed files with 149 additions and 0 deletions

1
.gitignore vendored
View file

@ -1,2 +1,3 @@
.env .env
__pycache__ __pycache__
*.sqlite3

0
src/db/.gitkeep Normal file
View file

View file

@ -1,6 +1,7 @@
from twitchio.ext import commands from twitchio.ext import commands
from os import listdir from os import listdir
from utils.core import load from utils.core import load
from utils.commands import CommandesDB
class Bot(commands.Bot): class Bot(commands.Bot):
def __init__(self): def __init__(self):
@ -8,6 +9,7 @@ class Bot(commands.Bot):
super().__init__(token=self.keys["ACCESS_TOKEN"], prefix=self.keys["PREFIX"], initial_channels=self.keys["CHANNEL"]) super().__init__(token=self.keys["ACCESS_TOKEN"], prefix=self.keys["PREFIX"], initial_channels=self.keys["CHANNEL"])
async def event_ready(self): async def event_ready(self):
CommandesDB().creationTable()
print(f"Logged in as {self.nick}") print(f"Logged in as {self.nick}")
async def event_message(self, message): async def event_message(self, message):

57
src/modules/commandes.py Normal file
View file

@ -0,0 +1,57 @@
from twitchio.ext import commands
from utils.core import load
from utils.commands import CommandesDB
def prepare(bot: commands.Bot):
bot.add_cog(Commandes(bot))
class Commandes(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
self.keys = load(["PREFIX"])
@commands.command()
async def add(self, ctx: commands.Context, commandName = None, commandMessage = None):
"""Ajoute une commande de la base de donnée du bot : add nomDeLaCommande messageDeLaCommande"""
if commandName == None or commandMessage == None:
return
if ctx.author.is_mod:
CommandesDB().ajoutCommande(commandName, commandMessage)
await ctx.send(f"Commande {commandName} ajoutée !")
@commands.command()
async def remove(self, ctx: commands.Context, commandName = None):
"""Supprime une commande de la base de donnée du bot : remove nomDeLaCommande"""
if commandName == None:
return
if ctx.author.is_mod:
CommandesDB().suppressionCommande(commandName)
await ctx.send(f"Commande {commandName} supprimée !")
@commands.command()
async def list(self, ctx: commands.Context):
"""Affiche la liste des commandes de la base de donnée du bot"""
commandes = CommandesDB().listeCommande()
if len(commandes) > 0:
message = ""
for commande in commandes:
message += f"{self.keys['PREFIX']}{commande[0]} -> {commande[1]}\n"
await ctx.send(message)
@commands.command()
async def edit(self, ctx: commands.Context, commandName = None, commandMessage = None):
"""Modifie une commande de la base de donnée du bot : add nomDeLaCommande nouveauMessageDeLaCommande"""
if commandName == None or commandMessage == None:
return
if ctx.author.is_mod:
CommandesDB().suppressionCommande(commandName)
CommandesDB().ajoutCommande(commandName, commandMessage)
await ctx.send(f"Commande {commandName} modifiée !")
@commands.Cog.event()
async def event_message(self, message):
if message.content.startswith(self.keys["PREFIX"]):
commandes = CommandesDB().listeCommande()
for commande in commandes:
if commande[0] == message.content[1:]:
await message.channel.send(commande[1])

39
src/utils/commands.py Normal file
View file

@ -0,0 +1,39 @@
from utils.db import Database
class CommandesDB(Database):
def __init__(self):
super().__init__(r"db/bot.sqlite3")
def creationTable(self):
"""Créer la table qui stocker les commandes."""
requete = """
CREATE TABLE IF NOT EXISTS commandes (
name_str TEXT,
content_str TEXT
);
"""
self.requete(requete)
def ajoutCommande(self, name = str, message = str):
"""Ajoute une commande."""
requete = """
INSERT INTO commandes (
name_str,
content_str
) VALUES (
?, ?
);
"""
self.requete(requete, [name, message])
def suppressionCommande(self, name = str):
"""Supprime une commande."""
requete = """
DELETE FROM commandes
WHERE name_str = ?;
"""
self.requete(requete, name)
def listeCommande(self):
"""Retourne la liste des commandes."""
return self.affichageResultat(self.requete("SELECT * FROM commandes;"))

50
src/utils/db.py Normal file
View file

@ -0,0 +1,50 @@
import sqlite3
class Database:
def __init__(self, urlDatabase: str):
self.connexion = self.createConnection(urlDatabase)
def createConnection(self, path):
"""Connexion à une base de donnée SQLite"""
if not self.isFileExists(path):
open(path, "x")
connnexion = None
try:
connnexion = sqlite3.connect(path)
except sqlite3.Error as e:
print(e)
return connnexion
def isFileExists(self, path):
"""Vérifie qu'un fichier existe"""
try:
open(path, "r")
except FileNotFoundError:
return False
else:
return True
def requete(self, requete, valeurs = None):
"""Envois une requête vers la base de données"""
try:
curseur = self.connexion.cursor()
if valeurs:
if type(valeurs) not in [list, tuple]:
valeurs = [valeurs]
curseur.execute(requete, valeurs)
else:
curseur.execute(requete)
self.connexion.commit()
return (curseur, curseur.lastrowid)
except sqlite3.Error as e:
print(e)
def affichageResultat(self, curseur):
"""Affiche le résultat d'une requête"""
tableau = []
if curseur == None:
return tableau
lignes = curseur[0].fetchall()
for ligne in lignes:
tableau.append(ligne)
return tableau