passage des methodes non asynchrone dans un fichier extene "core"

This commit is contained in:
Mylloon 2021-05-31 15:14:31 +02:00
parent 9646082083
commit 34459adc5e
7 changed files with 189 additions and 191 deletions

View file

@ -6,6 +6,7 @@ from random import choice
from datetime import datetime from datetime import datetime
from pytz import timezone from pytz import timezone
customTimezone = os.environ['TIMEZONE'] customTimezone = os.environ['TIMEZONE']
from utils.core import goodTimezone, userOrNick
def setup(client): def setup(client):
client.add_cog(ConfrerieDuKassoulait(client)) client.add_cog(ConfrerieDuKassoulait(client))
@ -91,25 +92,13 @@ class ConfrerieDuKassoulait(commands.Cog):
channel = self.client.get_channel(742588187456831659) channel = self.client.get_channel(742588187456831659)
embed = discord.Embed(description = f"{message.content}") embed = discord.Embed(description = f"{message.content}")
embed.set_author(name = self.user_or_nick(message.author), icon_url = message.author.avatar_url) embed.set_author(name = userOrNick(message.author), icon_url = message.author.avatar_url)
if not user_suppressed: if not user_suppressed:
embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {self.goodTimezone(message.created_at, 1)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1, customTimezone)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}")
else: else:
embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {self.goodTimezone(message.created_at, 1)}\nSupprimé par {self.user_or_nick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1, customTimezone)}\nSupprimé par {userOrNick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}")
await channel.send(embed = embed) await channel.send(embed = embed)
# ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré
# info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant) # info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant)
def user_or_nick(user):
if user.nick:
return f"{user.nick} ({user.name}#{user.discriminator})"
else:
return f"{user.name}#{user.discriminator}"
def goodTimezone(self, date, type):
if type == 0:
return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').split()
elif type == 1:
return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ')

View file

@ -4,6 +4,7 @@ from discord.ext import commands
from random import randint, choice from random import randint, choice
from datetime import timedelta from datetime import timedelta
from discord_slash import cog_ext from discord_slash import cog_ext
from utils.core import retirerDoublons
def setup(client): def setup(client):
client.add_cog(Fun(client)) client.add_cog(Fun(client))
@ -84,8 +85,8 @@ class Fun(commands.Cog):
user2 = list(users[1].nick) user2 = list(users[1].nick)
else: else:
user2 = list(users[1].name) user2 = list(users[1].name)
user1_CALC = self._retirerDoublons([x.lower() for x in user1]) user1_CALC = retirerDoublons([x.lower() for x in user1])
user2_CALC = self._retirerDoublons([x.lower() for x in user2]) user2_CALC = retirerDoublons([x.lower() for x in user2])
coef_amour = 0 coef_amour = 0
if len(user1_CALC) > len(user2_CALC): if len(user1_CALC) > len(user2_CALC):
taille_du_pls_grand = len(user1_CALC) taille_du_pls_grand = len(user1_CALC)
@ -107,12 +108,6 @@ class Fun(commands.Cog):
if fromSlash != True: if fromSlash != True:
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
await ctx.send(f"Erreur! Syntaxe : `{ctx.prefix}love <User1> [User2]`\n") await ctx.send(f"Erreur! Syntaxe : `{ctx.prefix}love <User1> [User2]`\n")
def _retirerDoublons(self, liste):
Newliste = []
for element in liste:
if element not in Newliste:
Newliste.append(element)
return Newliste
@_love.error @_love.error
async def _love_error(self, ctx, error): async def _love_error(self, ctx, error):
await ctx.send(str(error).replace('Member "', "Le membre **").replace('" not found', "** n'as pas été trouvé.")) await ctx.send(str(error).replace('Member "', "Le membre **").replace('" not found', "** n'as pas été trouvé."))

View file

@ -1,13 +1,11 @@
import discord import discord
import json
import requests
import time
import feedparser import feedparser
import os import os
from discord.ext import commands from discord.ext import commands
from random import choice from random import choice
from asyncpraw import Reddit from asyncpraw import Reddit
from discord_slash import cog_ext from discord_slash import cog_ext
from utils.core import randomImage
def setup(client): def setup(client):
client.add_cog(Internet(client)) client.add_cog(Internet(client))
@ -88,25 +86,6 @@ class Internet(commands.Cog):
else: else:
return await self._memes(ctx, subreddit, True) return await self._memes(ctx, subreddit, True)
def _random_image(self, link):
temps_requete = int(round(time.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.time() * 1000)) - temps_requete
return (json_data, temps_requete)
@commands.command(name='cat', aliases = ['chat']) @commands.command(name='cat', aliases = ['chat'])
async def _cat(self, ctx, fromSlash = False): async def _cat(self, ctx, fromSlash = False):
"""Te montre un magnifique chat\n ➡ Syntaxe: {PREFIX}cat/chat""" """Te montre un magnifique chat\n ➡ Syntaxe: {PREFIX}cat/chat"""
@ -116,7 +95,7 @@ class Internet(commands.Cog):
else: else:
name = f"{ctx.author.name}" name = f"{ctx.author.name}"
embed = discord.Embed(title = f"Poticha pour {name}", colour = discord.Colour.random()) embed = discord.Embed(title = f"Poticha pour {name}", colour = discord.Colour.random())
cat = self._random_image("http://aws.random.cat/meow") cat = randomImage("http://aws.random.cat/meow")
embed.set_image(url = cat[0]['file']) embed.set_image(url = cat[0]['file'])
embed.set_footer(text = f"random.cat a pris {cat[1]} ms.") embed.set_footer(text = f"random.cat a pris {cat[1]} ms.")
if fromSlash != True: if fromSlash != True:
@ -136,7 +115,7 @@ class Internet(commands.Cog):
else: else:
name = f"{ctx.author.name}" name = f"{ctx.author.name}"
embed = discord.Embed(title = f"Potichien pour {name}", colour = discord.Colour.random()) embed = discord.Embed(title = f"Potichien pour {name}", colour = discord.Colour.random())
dog = self._random_image("https://dog.ceo/api/breeds/image/random") dog = randomImage("https://dog.ceo/api/breeds/image/random")
embed.set_image(url = dog[0]['message']) embed.set_image(url = dog[0]['message'])
embed.set_footer(text = f"dog.ceo a pris {dog[1]} ms.") embed.set_footer(text = f"dog.ceo a pris {dog[1]} ms.")
if fromSlash != True: if fromSlash != True:
@ -157,7 +136,7 @@ class Internet(commands.Cog):
choice_of_nsfw = choice(liste_hot) choice_of_nsfw = choice(liste_hot)
if ctx.channel.is_nsfw(): if ctx.channel.is_nsfw():
embed = discord.Embed(title = f"{choice_of_nsfw.capitalize()} pour {ctx.author.name}", colour = discord.Colour.random()) embed = discord.Embed(title = f"{choice_of_nsfw.capitalize()} pour {ctx.author.name}", colour = discord.Colour.random())
nsfw = self._random_image(f'http://api.o{choice_of_nsfw}.ru/noise/') nsfw = randomImage(f'http://api.o{choice_of_nsfw}.ru/noise/')
embed.set_image(url = f"http://media.o{choice_of_nsfw}.ru/{nsfw[0][0]['preview']}") embed.set_image(url = f"http://media.o{choice_of_nsfw}.ru/{nsfw[0][0]['preview']}")
embed.set_footer(text = f"o{choice_of_nsfw}.ru a pris {nsfw[1]} ms.") embed.set_footer(text = f"o{choice_of_nsfw}.ru a pris {nsfw[1]} ms.")
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')

View file

@ -22,6 +22,7 @@ import lyricsgenius
import time import time
import os import os
genius = lyricsgenius.Genius(os.environ['TOKEN_GENIUS']) genius = lyricsgenius.Genius(os.environ['TOKEN_GENIUS'])
from utils.core import ligneFormatage, userOrNick
# Silence useless bug reports messages # Silence useless bug reports messages
youtube_dl.utils.bug_reports_message = lambda: '' youtube_dl.utils.bug_reports_message = lambda: ''
@ -518,7 +519,7 @@ class Music(commands.Cog):
type_de_comptage = "\n" type_de_comptage = "\n"
for ligne in paroles.split(type_de_comptage): for ligne in paroles.split(type_de_comptage):
if len(f"{lignetotal}{type_de_comptage}{ligne}") < 1900: if len(f"{lignetotal}{type_de_comptage}{ligne}") < 1900:
lignetotal = f"{lignetotal}{type_de_comptage}{self.ligne_formatage(ligne)}" lignetotal = f"{lignetotal}{type_de_comptage}{ligneFormatage(ligne)}"
else: else:
if premierembed == True: if premierembed == True:
premierembed = False premierembed = False
@ -528,10 +529,10 @@ class Music(commands.Cog):
else: else:
embed = discord.Embed(description = lignetotal, color = couleur_embed) embed = discord.Embed(description = lignetotal, color = couleur_embed)
await ctx.send(embed = embed) await ctx.send(embed = embed)
lignetotal = f"{self.ligne_formatage(ligne)}" lignetotal = f"{ligneFormatage(ligne)}"
temps_requete = int(round(time.time() * 1000)) - temps_requete temps_requete = int(round(time.time() * 1000)) - temps_requete
footer_embed = f"Pour {self.user_or_nick(ctx.author)} par Genius en {round(temps_requete / 1000, 2)} s." footer_embed = f"Pour {userOrNick(ctx.author)} par Genius en {round(temps_requete / 1000, 2)} s."
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
if premierembed == True: if premierembed == True:
premierembed = False premierembed = False
@ -545,19 +546,6 @@ class Music(commands.Cog):
else: else:
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
await ctx.send(f"Aucune musique demandé... `{ctx.prefix}lyrics/l/lyrics <song>`.") await ctx.send(f"Aucune musique demandé... `{ctx.prefix}lyrics/l/lyrics <song>`.")
def ligne_formatage(self, ligne):
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 user_or_nick(self, user):
if user.nick:
return f"{user.nick} ({user.name}#{user.discriminator})"
else:
return f"{user.name}#{user.discriminator}"
@commands.command(name='lyricsromanized', aliases = ['lr', 'lyricromanized'], hidden = True) @commands.command(name='lyricsromanized', aliases = ['lr', 'lyricromanized'], hidden = True)
async def _lyricsromanized(self, ctx, *, song: str = None): async def _lyricsromanized(self, ctx, *, song: str = None):

View file

@ -10,6 +10,7 @@ from datetime import datetime
from pytz import timezone from pytz import timezone
from discord_slash import cog_ext from discord_slash import cog_ext
import shlex import shlex
from utils.core import map_list_among_us, get_age, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick, ageLayout
def setup(client): def setup(client):
client.add_cog(Utils(client)) client.add_cog(Utils(client))
@ -21,7 +22,6 @@ class Utils(commands.Cog):
self.client = client self.client = client
self.customTimezone = os.environ['TIMEZONE'] self.customTimezone = os.environ['TIMEZONE']
@commands.command(name='ping') @commands.command(name='ping')
async def _ping(self, ctx, *, question = '0'): async def _ping(self, ctx, *, question = '0'):
"""Affiche mon ping.\n ➡ Syntaxe: {PREFIX}ping [help]""" """Affiche mon ping.\n ➡ Syntaxe: {PREFIX}ping [help]"""
@ -108,7 +108,7 @@ class Utils(commands.Cog):
equation = f"'{equation}' arrondi à 2" equation = f"'{equation}' arrondi à 2"
equation = equation.replace('*', '×').replace('/', '÷').replace('>=', '').replace('<=', '') equation = equation.replace('*', '×').replace('/', '÷').replace('>=', '').replace('<=', '')
embed = discord.Embed(color = discord.Colour.random(), title = 'Calculatrice') embed = discord.Embed(color = discord.Colour.random(), title = 'Calculatrice')
embed.set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) embed.set_footer(text = userOrNick(ctx.author), icon_url = ctx.author.avatar_url)
embed.add_field(name = 'Calcul :', value = equation, inline = False) embed.add_field(name = 'Calcul :', value = equation, inline = False)
embed.add_field(name = 'Réponse :', value = answer.replace('False', 'Faux').replace('True', 'Vrai'), inline = False) embed.add_field(name = 'Réponse :', value = answer.replace('False', 'Faux').replace('True', 'Vrai'), inline = False)
@ -265,28 +265,28 @@ class Utils(commands.Cog):
else: else:
map = "0" map = "0"
if map.lower() in self._map_list_among_us("mira"): if map.lower() in map_list_among_us("mira"):
image = "https://i.imgur.com/6ijrH1h.jpg" image = "https://i.imgur.com/6ijrH1h.jpg"
embed = discord.Embed(title = f"Map Mira HQ d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") embed = discord.Embed(title = f"Map Mira HQ d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})")
embed.set_image(url = image) embed.set_image(url = image)
if fromSlash != True: if fromSlash != True:
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
await ctx.send(embed = embed) await ctx.send(embed = embed)
elif map.lower() in self._map_list_among_us("polus"): elif map.lower() in map_list_among_us("polus"):
image = "https://i.imgur.com/mhFmcw3.jpg" image = "https://i.imgur.com/mhFmcw3.jpg"
embed = discord.Embed(title = f"Map Polus d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") embed = discord.Embed(title = f"Map Polus d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})")
embed.set_image(url = image) embed.set_image(url = image)
if fromSlash != True: if fromSlash != True:
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
await ctx.send(embed = embed) await ctx.send(embed = embed)
elif map.lower() in self._map_list_among_us("skeld"): elif map.lower() in map_list_among_us("skeld"):
image = "https://i.imgur.com/OSXI4Zv.jpg" image = "https://i.imgur.com/OSXI4Zv.jpg"
embed = discord.Embed(title = f"Map The Skeld d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") embed = discord.Embed(title = f"Map The Skeld d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})")
embed.set_image(url = image) embed.set_image(url = image)
if fromSlash != True: if fromSlash != True:
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
await ctx.send(embed = embed) await ctx.send(embed = embed)
elif map.lower() in self._map_list_among_us("airship"): elif map.lower() in map_list_among_us("airship"):
image = "https://i.imgur.com/cm8Wogw.png" image = "https://i.imgur.com/cm8Wogw.png"
embed = discord.Embed(title = f"Map Airship d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") embed = discord.Embed(title = f"Map Airship d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})")
embed.set_image(url = image) embed.set_image(url = image)
@ -302,22 +302,12 @@ class Utils(commands.Cog):
args = args.split() args = args.split()
del args[0] del args[0]
args = " ".join(args) args = " ".join(args)
if args.lower() in self._map_list_among_us("all"): if args.lower() in map_list_among_us("all"):
await ctx.invoke(self.client.get_command("amongus"), map=args) await ctx.invoke(self.client.get_command("amongus"), map=args)
else: else:
await ctx.invoke(self.client.get_command("amongus")) await ctx.invoke(self.client.get_command("amongus"))
else: else:
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
def _map_list_among_us(self, 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]
@cog_ext.cog_slash(name="amongus", description = "Affiche la carte voulue d'Among Us.") @cog_ext.cog_slash(name="amongus", description = "Affiche la carte voulue d'Among Us.")
async def __amongus(self, ctx, map): async def __amongus(self, ctx, map):
return await self._amongus(ctx, map, True) return await self._amongus(ctx, map, True)
@ -344,14 +334,14 @@ class Utils(commands.Cog):
value = str(user[0].created_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() value = str(user[0].created_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split()
embed.add_field(name = "Compte créé le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") embed.add_field(name = "Compte créé le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}")
embed.add_field(name = "Âge du compte", value = self._ageLayout(self._get_age(user[0].created_at))) embed.add_field(name = "Âge du compte", value = ageLayout(get_age(user[0].created_at)))
embed.add_field(name = "Mention", value = user[0].mention) embed.add_field(name = "Mention", value = user[0].mention)
value = str(user[0].joined_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() value = str(user[0].joined_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split()
embed.add_field(name = "Serveur rejoint le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") embed.add_field(name = "Serveur rejoint le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}")
embed.add_field(name = "Est sur le serveur depuis", value = self._ageLayout(self._get_age(user[0].joined_at))) embed.add_field(name = "Est sur le serveur depuis", value = ageLayout(get_age(user[0].joined_at)))
if fromSlash != True: if fromSlash != True:
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
return await ctx.send(embed = embed) return await ctx.send(embed = embed)
@ -364,90 +354,6 @@ class Utils(commands.Cog):
else: else:
return await self._whois(ctx, user, True) return await self._whois(ctx, user, True)
def _get_age(self, date):
joursRestants = datetime.now() - date
years = joursRestants.total_seconds() / (365.242 * 24 * 3600)
months = (years - int(years)) * 12
days = (months - int(months)) * (365.242 / 12)
hours = (days - int(days)) * 24
minutes = (hours - int(hours)) * 60
seconds = (minutes - int(minutes)) * 60
return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds))
def _ageLayout(self, tuple):
time = {}
time[0], time[1], time[2], time[3], time[4], time[5] = "an", "mois", "jour", "heure", "minute", "seconde"
for i in range(len(tuple)):
if tuple[i] > 1 and i != 1:
time[i] = time[i] + "s"
message = ""
if tuple[5] > 0: # pour les secondes
affichage = [5] # on affiche que : seconde
if tuple[4] > 0:
affichage = [4, 5] # on affiche : minute + seconde
if tuple[3] > 0:
affichage = [3, 4, 5] # on affiche : heure + minute + seconde
if tuple[2] > 0:
affichage = [2, 3, 4] # on affiche : jour + heure + minute
if tuple[1] > 0:
affichage = [1, 2, 3] # on affiche : mois + jour + heure
if tuple[0] > 0:
affichage = [0, 1, 3] # on affiche : an + mois + heure
for i in affichage:
message = message + f", {tuple[i]} {time[i]}"
return message[2:]
def _userOrNick(self, user):
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(self, ctx, stringMessage, stringID):
stringMessage = stringMessage.replace("<@!", "").replace(">", "").replace("<@", "")
associatedID = self._userOrNick(ctx.author.guild.get_member(int(stringID)))
try:
stringMessage = stringMessage.replace(stringID, associatedID)
except:
pass
return stringMessage
def _cleanCodeStringWithMentionAndURLs(self, string):
string = f"`{self._removeStartEndSpacesString(string)}`"
findedMention = self._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(self, string):
findedMention = []
for findingMention in re.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(self, string):
findedURLs = []
for findingMention in re.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(self, string):
while string.startswith(" "):
string = string[1:]
while string.endswith(" "):
string = string[:-1]
return string
@commands.command(name='sondage') @commands.command(name='sondage')
async def _sondage(self, ctx, *args): async def _sondage(self, ctx, *args):
"""Fais un sondage.\n ➡ Syntaxe: {PREFIX}sondage "<Question>" "<Proposition1>" "<Proposition...>" "<Proposition20>" """ """Fais un sondage.\n ➡ Syntaxe: {PREFIX}sondage "<Question>" "<Proposition1>" "<Proposition...>" "<Proposition20>" """
@ -461,7 +367,7 @@ class Utils(commands.Cog):
if len(args) > 2: if len(args) > 2:
question = args[0] question = args[0]
for i in re.findall(r'\d+', question): for i in re.findall(r'\d+', question):
question = self._cleanUser(ctx, question, i) question = cleanUser(ctx, question, i)
propositions = args[1:] propositions = args[1:]
if len(propositions) <= 20: if len(propositions) <= 20:
message = "" message = ""
@ -485,7 +391,7 @@ class Utils(commands.Cog):
shuffle(emojis_chosen) shuffle(emojis_chosen)
for i in range(len(args[1:])): for i in range(len(args[1:])):
message += f"{emojis_chosen[i]} -> {propositions[i]}\n" message += f"{emojis_chosen[i]} -> {propositions[i]}\n"
embed = discord.Embed(title = question, description = message, color = discord.Colour.random()).set_footer(text = f"Sondage de {self._userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url) embed = discord.Embed(title = question, description = message, color = discord.Colour.random()).set_footer(text = f"Sondage de {userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url)
sondage = await ctx.send(embed = embed) sondage = await ctx.send(embed = embed)
for i in range(len(args[1:])): for i in range(len(args[1:])):
await sondage.add_reaction(emoji = emojis_chosen[i]) await sondage.add_reaction(emoji = emojis_chosen[i])
@ -519,9 +425,9 @@ class Utils(commands.Cog):
else: # si titre défini else: # si titre défini
titre = args[0] titre = args[0]
for findedId in re.findall(r'\d+', titre): # récupération mention dans titre for findedId in re.findall(r'\d+', titre): # récupération mention dans titre
titre = self._cleanUser(ctx, titre, findedId) titre = cleanUser(ctx, titre, findedId)
args = args[1:] args = args[1:]
embed = discord.Embed(title = titre, description = self._cleanCodeStringWithMentionAndURLs(args[0]), color = discord.Colour.random()).set_footer(text = f"Sondage de {self._userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url) embed = discord.Embed(title = titre, description = cleanCodeStringWithMentionAndURLs(args[0]), color = discord.Colour.random()).set_footer(text = f"Sondage de {userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url)
message = await ctx.send(embed = embed) message = await ctx.send(embed = embed)
reactions = ['', '🤷', ''] reactions = ['', '🤷', '']
for i in reactions: for i in reactions:
@ -581,7 +487,7 @@ class Utils(commands.Cog):
await asyncio.sleep(seconds) await asyncio.sleep(seconds)
message = ctx.author.mention message = ctx.author.mention
if mention: if mention:
mentionList = self._getMentionInString(reminder) mentionList = getMentionInString(reminder)
for i in mentionList: for i in mentionList:
message += f" {i}" message += f" {i}"
try: try:
@ -589,11 +495,11 @@ class Utils(commands.Cog):
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
except: except:
pass pass
finalEmbed = discord.Embed(description = self._cleanCodeStringWithMentionAndURLs(reminder), timestamp = timestamp, color = discord.Colour.random()) finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = timestamp, color = discord.Colour.random())
finalEmbed.set_footer(text=f"Message d'il y a {counter}") finalEmbed.set_footer(text=f"Message d'il y a {counter}")
links = "" links = ""
findedURLs = self._getURLsInString(reminder) findedURLs = getURLsInString(reminder)
for i in range(0, len(findedURLs)): for i in range(0, len(findedURLs)):
links += f"[Lien {i + 1}]({findedURLs[i]}) · " links += f"[Lien {i + 1}]({findedURLs[i]}) · "
if len(findedURLs) > 0: if len(findedURLs) > 0:

View file

@ -5,9 +5,9 @@ import re
import os import os
from discord_slash import SlashCommand from discord_slash import SlashCommand
from discord.ext import commands from discord.ext import commands
from pytz import timezone
customPrefix = os.environ['PREFIX'] customPrefix = os.environ['PREFIX']
customTimezone = os.environ['TIMEZONE'] customTimezone = os.environ['TIMEZONE']
from utils.core import userOrNick, goodTimezone
client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all())
slash = SlashCommand(client, sync_commands = True) slash = SlashCommand(client, sync_commands = True)
@ -104,18 +104,18 @@ async def on_message(message):
embed.set_author(name = "Citation", icon_url = msgID.author.avatar_url) embed.set_author(name = "Citation", icon_url = msgID.author.avatar_url)
icon_url = message.author.avatar_url icon_url = message.author.avatar_url
date_1 = goodTimezone(msgID.created_at, 0) date_1 = goodTimezone(msgID.created_at, 0, customTimezone)
edit = "" edit = ""
if msgID.edited_at: if msgID.edited_at:
date_edit = goodTimezone(msgID.edited_at, 0) date_edit = goodTimezone(msgID.edited_at, 0, customTimezone)
edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}" edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}"
messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}"
date_2 = goodTimezone(message.created_at, 0) date_2 = goodTimezone(message.created_at, 0, customTimezone)
date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}" date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}"
if auteur == "Auteur": if auteur == "Auteur":
messageDuBas = messageDuBas + f"\nCité par {user_or_nick(message.author)} le {date_2}" messageDuBas = messageDuBas + f"\nCité par {userOrNick(message.author)} le {date_2}"
embed.set_footer(icon_url = icon_url, text = messageDuBas) embed.set_footer(icon_url = icon_url, text = messageDuBas)
if message.content == linkURL.replace(' ',''): if message.content == linkURL.replace(' ',''):
await message.channel.send(embed = embed) await message.channel.send(embed = embed)
@ -127,17 +127,5 @@ async def on_message(message):
if not "invalid literal for int() with base 10:" in e or not "404 Not Found (error code: 10008)" in e: # faute de frappe / message supprimé if not "invalid literal for int() with base 10:" in e or not "404 Not Found (error code: 10008)" in e: # faute de frappe / message supprimé
print(e) print(e)
def user_or_nick(user):
if user.nick:
return f"{user.nick} ({user.name}#{user.discriminator})"
else:
return f"{user.name}#{user.discriminator}"
def goodTimezone(date, type):
if type == 0:
return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').split()
elif type == 1:
return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ')
print("Connexion à Discord...", end = " ") print("Connexion à Discord...", end = " ")
client.run(os.environ['TOKEN_DISCORD']) client.run(os.environ['TOKEN_DISCORD'])

153
src/utils/core.py Normal file
View file

@ -0,0 +1,153 @@
import re
import json
import requests
import time
from pytz import timezone
from datetime import datetime
def goodTimezone(date, type, tz):
"""renvoie une date en fonction d'un timezone"""
if type == 0:
return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').split()
elif type == 1:
return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ')
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 get_age(date):
"""Recupère un age précisément à la seconde près"""
joursRestants = datetime.now() - date
years = joursRestants.total_seconds() / (365.242 * 24 * 3600)
months = (years - int(years)) * 12
days = (months - int(months)) * (365.242 / 12)
hours = (days - int(days)) * 24
minutes = (hours - int(hours)) * 60
seconds = (minutes - int(minutes)) * 60
return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds))
def ageLayout(tuple):
"""avec la méthode 'get_age', permet de mettre en forme un âge"""
time = {}
time[0], time[1], time[2], time[3], time[4], time[5] = "an", "mois", "jour", "heure", "minute", "seconde"
for i in range(len(tuple)):
if tuple[i] > 1 and i != 1:
time[i] = time[i] + "s"
message = ""
if tuple[5] > 0: # pour les secondes
affichage = [5] # on affiche que : seconde
if tuple[4] > 0:
affichage = [4, 5] # on affiche : minute + seconde
if tuple[3] > 0:
affichage = [3, 4, 5] # on affiche : heure + minute + seconde
if tuple[2] > 0:
affichage = [2, 3, 4] # on affiche : jour + heure + minute
if tuple[1] > 0:
affichage = [1, 2, 3] # on affiche : mois + jour + heure
if tuple[0] > 0:
affichage = [0, 1, 3] # on affiche : an + mois + heure
for i in affichage:
message = message + f", {tuple[i]} {time[i]}"
return message[2:]
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
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 re.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 re.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.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.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