179 lines
7.1 KiB
Python
179 lines
7.1 KiB
Python
import json
|
||
import requests
|
||
from re import findall
|
||
from time import time
|
||
from os import environ, path
|
||
from dotenv import load_dotenv
|
||
|
||
def map_list_among_us(map):
|
||
"""Sélecteur de map pour la commande amongus"""
|
||
maps = {}
|
||
maps["skeld"] = ["skeld", "the skeld", "theskeld"]
|
||
maps["mira"] = ["mira", "mira hq", "mirahq"]
|
||
maps["polus"] = ["polus"]
|
||
maps["airship"] = ["airship", "air ship"]
|
||
if map == "all":
|
||
return maps["skeld"] + maps["mira"] + maps["polus"] + maps["airship"]
|
||
return maps[map]
|
||
|
||
def userOrNick(user):
|
||
"""Affiche le pseudo et/ou le surnom"""
|
||
if user == None:
|
||
return "Utilisateur inconnu" # Mauvais copié/collé -> changement d'ID
|
||
if user.nick:
|
||
return f"{user.nick} ({user.name}#{user.discriminator})"
|
||
else:
|
||
return f"{user.name}#{user.discriminator}"
|
||
|
||
def cleanUser(ctx, stringMessage, stringID):
|
||
"""récupère l'utilisateur avec son id"""
|
||
stringMessage = stringMessage.replace("<@!", "").replace(">", "").replace("<@", "") # améliorer ça avec du regex
|
||
if len(str(stringMessage)) not in (17, 18): # si ce n'est pas un ID valide
|
||
return stringMessage
|
||
associatedID = userOrNick(ctx.author.guild.get_member(int(stringID)))
|
||
try:
|
||
stringMessage = stringMessage.replace(stringID, associatedID)
|
||
except:
|
||
pass
|
||
return stringMessage
|
||
|
||
def cleanCodeStringWithMentionAndURLs(string):
|
||
"""formate un string avec des ` tout en gardant les mention et les liens"""
|
||
string = f"`{removeStartEndSpacesString(string)}`"
|
||
|
||
findedMention = getMentionInString(string)
|
||
for i in range(0, len(findedMention)):
|
||
string = string.replace(findedMention[i], f"`{findedMention[i]}`") # conserve la mention dans le message
|
||
|
||
if string.startswith("``<@"): # conserve le format quand mention au début de la string
|
||
string = string[2:]
|
||
if string.endswith(">``"): # conserve le format quand mention à la fin de la string
|
||
string = string[:-2]
|
||
string = string.replace("``", "") # conserve le format quand deux mentions sont collés
|
||
return string
|
||
|
||
def getMentionInString(string):
|
||
"""récupère les mentions dans un string"""
|
||
findedMention = []
|
||
for findingMention in findall(r'<@[!]?\d*>', string): # récupération mention dans le string
|
||
findedMention.append(findingMention)
|
||
findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention dans la liste
|
||
return findedMention
|
||
|
||
def getURLsInString(string):
|
||
"""récupère les liens dans un string"""
|
||
findedURLs = []
|
||
for findingMention in findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string): # récupération URLs dans le string
|
||
findedURLs.append(findingMention)
|
||
return findedURLs
|
||
|
||
def removeStartEndSpacesString(string):
|
||
"""Retire les espaces en trop au début et à la fin d'un string"""
|
||
while string.startswith(" "):
|
||
string = string[1:]
|
||
while string.endswith(" "):
|
||
string = string[:-1]
|
||
return string
|
||
|
||
def randomImage(link):
|
||
"""Récupération d'une image aléatoirement"""
|
||
temps_requete = int(round(time() * 1000))
|
||
try:
|
||
request_data = requests.get(link)
|
||
except Exception as e:
|
||
raise Exception(f"Une erreur s'est produite lors de la tentative de demande de l'API {link} : {e}")
|
||
|
||
if not request_data.status_code == 200:
|
||
raise Exception(f"Code HTTP {request_data.status_code} au lieu de HTTP 200 à l'appel de {link} : {request_data.text}")
|
||
|
||
try:
|
||
json_data = json.loads(request_data.text)
|
||
except Exception as e:
|
||
raise Exception(f"Erreur lors de la transformation les données de {link} en json : {e}")
|
||
|
||
temps_requete = int(round(time() * 1000)) - temps_requete
|
||
return (json_data, temps_requete)
|
||
|
||
def retirerDoublons(liste):
|
||
"""Supprime les doublons d'une liste"""
|
||
Newliste = []
|
||
for element in liste:
|
||
if element not in Newliste:
|
||
Newliste.append(element)
|
||
return Newliste
|
||
|
||
def ligneFormatage(ligne):
|
||
"""Traduit en français les balises dans les lyrics d'une chanson"""
|
||
liste_balise = [
|
||
('[Hook', '[Accroche'), ('[Verse', '[Couplet'), ('[Chorus', '[Chœur'),
|
||
('[Bridge', '[Pont'),('[Pre-Chorus', '[Pré-chœur'), ('[Post-Chorus', '[Post-chœur')
|
||
]
|
||
for balises in liste_balise:
|
||
ligne = ligne.replace(balises[0], balises[1])
|
||
return ligne
|
||
|
||
def mentionToUser(mention: str):
|
||
"""Récupère une mention et renvois son ID"""
|
||
return int(mention[2:-1].replace("!",""))
|
||
|
||
def getChangelogs(version = 'actual'):
|
||
"""Récupère les changements d'une version (par défaut, la dernière en date) et renvois dans l'ordre : url, n° version, changements"""
|
||
if version == 'actual':
|
||
version = getActualVersion()
|
||
changements = requests.get(f"https://gitlab.com/api/v4/projects/28424435/releases/v{version}")
|
||
|
||
if changements.status_code != 200: # si pas valide
|
||
return [changements.status_code]
|
||
else:
|
||
code = 200
|
||
|
||
changements = changements.json()
|
||
return [code, changements["_links"]["self"], changements["tag_name"][1:], changements["description"]]
|
||
|
||
def getActualVersion():
|
||
with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file:
|
||
return findall(r'https:\/\/img.shields.io\/badge\/version-(\d+\.\d+)-green\?style=for-the-badge\)', file.readlines()[2])[0]
|
||
|
||
def devOrStableChannel():
|
||
with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file:
|
||
return findall(r'https:\/\/img.shields.io\/gitlab\/pipeline\/ConfrerieDuKassoulait\/KassouBot\/([a-z]+)\?style=for-the-badge\)]', file.readlines()[3])[0]
|
||
|
||
def isSlash(arg):
|
||
"""Regarde si la commande viens d'un slash ou pas, retourne l'argument sans le 'True' si c'est le cas"""
|
||
fromSlash = False
|
||
fullarg = arg
|
||
if len(arg) > 0:
|
||
if arg[-1] == True or arg[-1] == None:
|
||
fromSlash = arg[-1]
|
||
fullarg = arg[:-1]
|
||
if len(fullarg) == 0:
|
||
arg = None
|
||
else:
|
||
arg = arg[0]
|
||
|
||
return (arg, fromSlash, fullarg)
|
||
|
||
async def mySendHidden(
|
||
ctx, fromSlash, message = None, tts = False, embed = None, file = None, files = None,
|
||
delete_after = None, allowed_mentions = None):
|
||
if fromSlash == True: # can't delete hidden message
|
||
await ctx.send( # sending hidden message
|
||
content = message, tts = tts, embed = embed, file = file, files = files,
|
||
delete_after = None, allowed_mentions = allowed_mentions, hidden = fromSlash)
|
||
else:
|
||
await ctx.send( # sending normal message
|
||
content = message, tts = tts, embed = embed, file = file, files = files,
|
||
delete_after = delete_after, allowed_mentions = allowed_mentions)
|
||
|
||
def load(variables):
|
||
"""Load env variables"""
|
||
keys = {}
|
||
load_dotenv() # load .env file
|
||
for var in variables:
|
||
try:
|
||
keys[var] = environ[var]
|
||
except KeyError:
|
||
print(f"Please set the environment variable {var} (.env file supported)")
|
||
exit(1)
|
||
|
||
return keys
|