Clone from git.gnous.eu/Gnous/tuxbot

This commit is contained in:
Mael G 2019-05-29 18:59:20 -04:00
parent d85a5b8005
commit ed4b1bf866
37 changed files with 2234 additions and 1797 deletions

0
README Normal file → Executable file
View file

219
bot.py
View file

@ -1,120 +1,133 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__author__ = ["Romain", "Maël / Outout"] __author__ = "Maël / Outout | Romain"
__licence__ = "WTFPL Licence 2.0" __licence__ = "WTFPL Licence 2.0"
from discord.ext import commands import copy
import datetime
import os
import sys
import traceback
import aiohttp
import discord import discord
from discord.ext import commands
import cogs.utils.cli_colors as colors
import config
from cogs.utils import checks from cogs.utils import checks
import datetime l_extensions = (
import json 'cogs.admin',
import copy 'cogs.afk',
import traceback 'cogs.atc',
import sys 'cogs.basics',
import os 'cogs.ci',
import aiohttp 'cogs.cog_manager',
'cogs.filter_messages',
import config 'cogs.funs',
import cogs.utils.cli_colors as colors 'cogs.passport',
'cogs.role',
l_extensions = [ 'cogs.search',
'cogs.send_logs',
'cogs.admin', 'cogs.sondage',
# 'cogs.afk', 'cogs.utility',
'cogs.basics', 'cogs.vocal',
'cogs.ci', )
'cogs.cog_manager',
'cogs.filter_messages',
'cogs.funs',
'cogs.passport',
'cogs.role',
'cogs.search',
'cogs.send_logs',
'cogs.sondage',
'cogs.utility'
]
help_attrs = dict(hidden=True, in_help=True, name="DONOTUSE") help_attrs = dict(hidden=True, in_help=True, name="DONOTUSE")
class TuxBot(commands.Bot): class TuxBot(commands.Bot):
def __init__ (self): def __init__(self):
self.config = config self.uptime = datetime.datetime.utcnow()
super().__init__(command_prefix=self.config.prefix[0], self.config = config
description=self.config.description, super().__init__(command_prefix=self.config.prefix[0],
pm_help=None, description=self.config.description,
help_attrs=help_attrs) pm_help=None,
help_command = None
)
self.client_id = self.config.client_id self.client_id = self.config.client_id
self.session = aiohttp.ClientSession(loop=self.loop) self.session = aiohttp.ClientSession(loop=self.loop)
self._events = [] self._events = []
self.add_command(self.do)
for extension in l_extensions:
try:
self.load_extension(extension)
print(f"{colors.text_colors.GREEN}\"{extension}\""
f" chargé !{colors.ENDC}")
except Exception as e:
print(f"{colors.text_colors.RED}"
f"Impossible de charger l'extension {extension}\n"
f"{type(e).__name__}: {e}{colors.ENDC}", file=sys.stderr)
async def on_command_error(self, ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await ctx.author.send('Cette commande ne peut pas être utilisée '
'en message privé.')
elif isinstance(error, commands.DisabledCommand):
await ctx.author.send('Desolé mais cette commande est desactivée, '
'elle ne peut donc pas être utilisée.')
elif isinstance(error, commands.CommandInvokeError):
print(f'In {ctx.command.qualified_name}:', file=sys.stderr)
traceback.print_tb(error.original.__traceback__)
print(f'{error.original.__class__.__name__}: {error.original}',
file=sys.stderr)
async def on_ready(self):
log_channel_id = self.get_channel(int(self.config.log_channel_id))
print('\n\n---------------------')
print('CONNECTÉ :')
print(f'Nom d\'utilisateur: {self.user} {colors.text_style.DIM}'
f'(ID: {self.user.id}){colors.ENDC}')
print(f'Salon de journalisation: {log_channel_id} {colors.text_style.DIM}'
f'(ID: {log_channel_id.id}){colors.ENDC}')
print(f'Prefix: {self.config.prefix[0]}')
print('Merci d\'utiliser TuxBot')
print('---------------------\n\n')
await self.change_presence(status=discord.Status.dnd,
activity=discord.Game(
name=self.config.game),
)
@staticmethod
async def on_resumed():
print('resumed...')
async def on_message(self, message):
if message.author.bot:
return
try:
await self.process_commands(message)
except Exception as e:
print(f'{colors.text_colors.RED}Erreur rencontré : \n'
f' {type(e).__name__}: {e}{colors.ENDC} \n \n')
def run(self):
super().run(self.config.token, reconnect=True)
@checks.has_permissions(administrator=True)
@commands.command(pass_context=True, hidden=True)
async def do(self, ctx, times: int, *, command):
"""Repeats a command a specified number of times."""
msg = copy.copy(ctx.message)
msg.content = command
for i in range(times):
await self.process_commands(msg)
self.add_command(self.do)
for extension in l_extensions:
try:
self.load_extension(extension)
print(f"{colors.text_colors.GREEN}\"{extension}\" chargé !{colors.ENDC}")
except Exception as e:
print(f"{colors.text_colors.RED}Impossible de charger l'extension {extension}\n{type(e).__name__}: {e}{colors.ENDC}", file=sys.stderr)
async def on_command_error(self, ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await ctx.author.send('Cette commande ne peut pas être utilisee en message privee.')
elif isinstance(error, commands.DisabledCommand):
await ctx.author.send('Desoler mais cette commande est desactive, elle ne peut donc pas être utilisée.')
elif isinstance(error, commands.CommandInvokeError):
print(f'In {ctx.command.qualified_name}:', file=sys.stderr)
traceback.print_tb(error.original.__traceback__)
print(f'{error.original.__class__.__name__}: {error.original}', file=sys.stderr)
async def on_ready(self):
if not hasattr(self, 'uptime'):
self.uptime = datetime.datetime.utcnow()
log_channel_id = self.get_channel(int(self.config.log_channel_id))
print('\n\n---------------------')
print('CONNECTÉ :')
print(f'Nom d\'utilisateur: {self.user} {colors.text_style.DIM}(ID: {self.user.id}){colors.ENDC}')
print(f'Channel de log: {log_channel_id} {colors.text_style.DIM}(ID: {log_channel_id.id}){colors.ENDC}')
print(f'Prefix: {self.config.prefix[0]}')
print('Merci d\'utiliser TuxBot')
print('---------------------\n\n')
await self.change_presence(status=discord.Status.dnd, activity=discord.Game(name=self.config.game))
async def on_resumed():
print('resumed...')
async def on_message(self, message):
if message.author.bot:
return
try:
await self.process_commands(message)
except Exception as e:
print(f'{colors.text_colors.RED}Erreur rencontré : \n {type(e).__name__}: {e}{colors.ENDC} \n \n')
def run(self):
super().run(self.config.token, reconnect=True)
@checks.has_permissions(administrator=True)
@commands.command(pass_context=True, hidden=True)
async def do(ctx, times: int, *, command):
"""Repeats a command a specified number of times."""
msg = copy.copy(ctx.message)
msg.content = command
for i in range(times):
await bot.process_commands(msg)
## LOAD ##
if __name__ == '__main__': if __name__ == '__main__':
if os.path.exists('config.py') is not True: if os.path.exists('config.py') is not True:
print(f"{colors.text_colors.RED}Veuillez créer le fichier config.py{colors.ENDC}"); exit() print(f"{colors.text_colors.RED}"
f"Veuillez créer le fichier config.py{colors.ENDC}")
tuxbot = TuxBot() exit()
tuxbot.run()
tuxbot = TuxBot()
tuxbot.run()

0
cogs/.DS_Store vendored Normal file → Executable file
View file

View file

@ -1,336 +1,541 @@
from discord.ext import commands from discord.ext import commands
import discord import discord
import aiohttp
import asyncio import asyncio
import time
from .utils import checks from .utils import checks
from .utils.checks import get_user from .utils.checks import get_user
import json import traceback
import random import textwrap
from contextlib import redirect_stdout
import datetime import inspect
import io
import requests
class Admin: class Admin(commands.Cog):
"""Commandes secrètes d'administration.""" """Commandes secrètes d'administration."""
def __init__(self, bot):
self.bot = bot
self._last_result = None
self.sessions = set()
def __init__(self, bot): @staticmethod
self.bot = bot def cleanup_code(content):
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
return content.strip('` \n')
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(pass_context=True) @commands.command(pass_context=True)
async def ban(self, ctx, user, *, reason=""): async def ban(self, ctx, user, *, reason=""):
"""Ban user""" """Ban user"""
user = get_user(ctx.message, user) user = get_user(ctx.message, user)
if user: if user:
try: try:
await user.ban(reason=reason) await user.ban(reason=reason)
return_msg = "`{}` a été banni\n".format(user.mention) return_msg = f"`{user.mention}` a été banni\n"
if reason: if reason:
return_msg += "raison : `{}`".format(reason) return_msg += f"raison : `{reason}`"
return_msg += "." return_msg += "."
await ctx.send(return_msg) await ctx.send(return_msg)
except discord.Forbidden: except discord.Forbidden:
await ctx.send('Impossible de bannir cet user, probleme de permission.') await ctx.send('Impossible de bannir cet user,'
else: ' probleme de permission.')
return await ctx.send('Impossible de trouver l\'user.') else:
return await ctx.send('Impossible de trouver l\'user.')
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(pass_context=True) @commands.command(pass_context=True)
async def kick(self, ctx, user, *, reason=""): async def kick(self, ctx, user, *, reason=""):
"""Kick a user""" """Kick a user"""
user = get_user(ctx.message, user) user = get_user(ctx.message, user)
if user: if user:
try: try:
await user.kick(reason=reason) await user.kick(reason=reason)
return_msg = "`{}` a été kické\n".format(user.mention) return_msg = f"`{user.mention}` a été kické\n"
if reason: if reason:
return_msg += "raison : `{}`".format(reason) return_msg += f"raison : `{reason}`"
return_msg += "." return_msg += "."
await ctx.send(return_msg) await ctx.send(return_msg)
except discord.Forbidden: except discord.Forbidden:
await ctx.send('Impossible de kicker cet user, probleme de permission.') await ctx.send('Impossible de kicker cet user,'
else: ' probleme de permission.')
return await ctx.send('Impossible de trouver l\'user.') else:
return await ctx.send('Impossible de trouver l\'user.')
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(name='clear', pass_context=True) @commands.command(name='clear', pass_context=True)
async def _clear(self, ctx, number: int, silent: str = True): async def _clear(self, ctx, number: int, silent: str = True):
"""Clear <number> of message(s)""" """Clear <number> of message(s)"""
try: try:
await ctx.message.delete() await ctx.message.delete()
except: except Exception:
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") print(f"Impossible de supprimer le message "
if number < 1000: f"\"{str(ctx.message.content)}\"")
async for message in ctx.message.channel.history(limit=number): if number < 1000:
try: try:
await message.delete() await ctx.message.channel.purge(limit=number)
except Exception as e: #TODO : A virer dans l'event on_error except Exception as e: # TODO : A virer dans l'event on_error
if silent is not True: if silent is not True:
await ctx.send(':sob: Une erreur est survenue : \n {}: {}'.format(type(e).__name__, e)) await ctx.send(f':sob: Une erreur est survenue : \n'
if silent is not True: f' {type(e).__name__}: {e}')
await ctx.send("Hop voila j'ai viré des messages! Hello World") if silent is not True:
print(str(number)+" messages ont été supprimés") await ctx.send("Hop voila j'ai viré des messages! Hello World")
else: print(f"{str(number)} messages ont été supprimés")
await ctx.send('Trop de messages, entre un nombre < 1000') else:
await ctx.send('Trop de messages, entre un nombre < 1000')
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(name='say', pass_context=True) @commands.command(name='say', pass_context=True)
async def _say(self, ctx, *, tosay:str): async def _say(self, ctx, *, tosay: str):
"""Say a message in the current channel""" """Say a message in the current channel"""
try: try:
try: try:
await ctx.message.delete() await ctx.message.delete()
except: except Exception:
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") print(f"Impossible de supprimer le message "
await ctx.send(tosay) f"\"{str(ctx.message.content)}\"")
except Exception as e: #TODO : A virer dans l'event on_error await ctx.send(tosay)
await ctx.send(':sob: Une erreur est survenue : \n {}: {}'.format(type(e).__name__, e)) except Exception as e: # TODO : A virer dans l'event on_error
await ctx.send(f':sob: Une erreur est survenue : \n'
f' {type(e).__name__}: {e}')
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(name='sayto', pass_context=True) @commands.command(name='sayto', pass_context=True)
async def _sayto(self, ctx, id:int, *, tosay:str): async def _sayto(self, ctx, channel_id: int, *, tosay: str):
"""Say a message in the <id> channel""" """Say a message in the <channel_id> channel"""
try: try:
chan = self.bot.get_channel(id) chan = self.bot.get_channel(channel_id)
try: try:
await ctx.message.delete() await ctx.message.delete()
except: except Exception:
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") print(f"Impossible de supprimer le message "
try: f"\"{str(ctx.message.content)}\"")
await chan.send(tosay) try:
except Exception as e: await chan.send(tosay)
print("Impossible d'envoyer le message dans " + str(id)) except Exception:
except Exception as e: #TODO : A virer dans l'event on_error print(f"Impossible d'envoyer le message dans {str(channel_id)}")
await ctx.send(':sob: Une erreur est survenue : \n {}: {}'.format(type(e).__name__, e)) except Exception as e: # TODO : A virer dans l'event on_error
await ctx.send(f':sob: Une erreur est survenue : \n'
f' {type(e).__name__}: {e}')
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(name='sayto_dm', pass_context=True) @commands.command(name='sayto_dm', pass_context=True)
async def _sayto_dm(self, ctx, id:int, *, tosay:str): async def _sayto_dm(self, ctx, user_id: int, *, tosay: str):
"""Say a message to the <id> user""" """Say a message to the <user_id> user"""
try: try:
user = self.bot.get_user(id) user = self.bot.get_user(user_id)
try: try:
await ctx.message.delete() await ctx.message.delete()
except: except Exception:
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") print(f"Impossible de supprimer le message "
try: f"\"{str(ctx.message.content)}\"")
await user.send(tosay) try:
except Exception as e: await user.send(tosay)
print("Impossible d'envoyer le message dans " + str(id)) except Exception:
except Exception as e: #TODO : A virer dans l'event on_error print(f"Impossible d'envoyer le message dans {str(user_id)}")
await ctx.send(':sob: Une erreur est survenue : \n {}: {}'.format(type(e).__name__, e)) except Exception as e: # TODO : A virer dans l'event on_error
await ctx.send(f':sob: Une erreur est survenue : \n'
f' {type(e).__name__}: {e}')
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(name='editsay', pass_context=True) @commands.command(name='editsay', pass_context=True)
async def _editsay(self, ctx, id:int, *, new_content:str): async def _editsay(self, ctx, id: int, *, new_content: str):
"""Edit a bot's message""" """Edit a bot's message"""
try: try:
try: try:
await ctx.message.delete() await ctx.message.delete()
except: except Exception:
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") print(f"Impossible de supprimer le message "
toedit = await ctx.channel.get_message(id) f"\"{str(ctx.message.content)}\"")
except discord.errors.NotFound: toedit = await ctx.channel.get_message(id)
await ctx.send("Impossible de trouver le message avec l'id `{}` sur ce salon".format(id)) except discord.errors.NotFound:
return await ctx.send(f"Impossible de trouver le message avec l'id "
try: f"`{id}` sur ce salon")
await toedit.edit(content=str(new_content)) return
except discord.errors.Forbidden: try:
await ctx.send("J'ai po les perms pour editer mes messages :(") await toedit.edit(content=str(new_content))
except discord.errors.Forbidden:
await ctx.send("J'ai po les perms pour editer mes messages :(")
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(name='addreaction', pass_context=True) @commands.command(name='addreaction', pass_context=True)
async def _addreaction(self, ctx, id:int, reaction:str): async def _addreaction(self, ctx, id: int, reaction: str):
"""Add reactions to a message""" """Add reactions to a message"""
try: try:
try: try:
await ctx.message.delete() await ctx.message.delete()
except: except Exception:
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") print(f"Impossible de supprimer le message "
toadd = await ctx.channel.get_message(id) f"\"{str(ctx.message.content)}\"")
except discord.errors.NotFound: toadd = await ctx.channel.get_message(id)
await ctx.send("Impossible de trouver le message avec l'id `{}` sur ce salon".format(id)) except discord.errors.NotFound:
return await ctx.send(f"Impossible de trouver le message avec l'id "
try: f"`{id}` sur ce salon")
await toadd.add_reaction(reaction) return
except discord.errors.Forbidden: try:
await ctx.send("J'ai po les perms pour ajouter des réactions :(") await toadd.add_reaction(reaction)
except discord.errors.Forbidden:
await ctx.send("J'ai po les perms pour ajouter des réactions :(")
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(name='delete', pass_context=True) @commands.command(name='delete', pass_context=True)
async def _delete(self, ctx, id:int): async def _delete(self, ctx, id: int):
"""Delete message in current channel""" """Delete message in current channel"""
try: try:
try: try:
await ctx.message.delete() await ctx.message.delete()
except: except Exception:
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") print(f"Impossible de supprimer le message "
todelete = await ctx.channel.get_message(id) f"\"{str(ctx.message.content)}\"")
except discord.errors.NotFound: todelete = await ctx.channel.get_message(id)
await ctx.send("Impossible de trouver le message avec l'id `{}` sur ce salon".format(id)) except discord.errors.NotFound:
return await ctx.send(f"Impossible de trouver le message avec l'id "
try: f"`{id}` sur ce salon")
await todelete.delete() return
except discord.errors.Forbidden: try:
await ctx.send("J'ai po les perms pour supprimer des messages :(") await todelete.delete()
except discord.errors.Forbidden:
await ctx.send("J'ai po les perms pour supprimer des messages :(")
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(name='deletefrom', pass_context=True) @commands.command(name='deletefrom', pass_context=True)
async def _deletefrom(self, ctx, chan_id:int, *, message_id:str): async def _deletefrom(self, ctx, chan_id: int, *, message_id: str):
"""Delete message in <chan_id> channel""" """Delete message in <chan_id> channel"""
try: try:
chan = self.bot.get_channel(chan_id) chan = self.bot.get_channel(chan_id)
try: try:
await ctx.message.delete() await ctx.message.delete()
except: except Exception:
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") print(f"Impossible de supprimer le message "
todelete = await chan.get_message(message_id) f"\"{str(ctx.message.content)}\"")
except discord.errors.NotFound: todelete = await chan.get_message(message_id)
await ctx.send("Impossible de trouver le message avec l'id `{}` sur le salon".format(id)) except discord.errors.NotFound:
return await ctx.send(f"Impossible de trouver le message avec l'id "
try: f"`{id}` sur le salon")
await todelete.delete() return
except discord.errors.Forbidden: try:
await ctx.send("J'ai po les perms pour supprimer le message :(") await todelete.delete()
except discord.errors.Forbidden:
await ctx.send("J'ai po les perms pour supprimer le message :(")
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.command(name='embed', pass_context=True) @commands.command(name='embed', pass_context=True)
async def _embed(self, ctx, *, msg: str = "help"): async def _embed(self, ctx, *, msg: str = "help"):
"""Send an embed""" """Send an embed"""
if msg != "help": if msg != "help":
ptext = title = description = image = thumbnail = color = footer = author = None ptext = title \
timestamp = discord.Embed.Empty = description \
embed_values = msg.split('|') = image \
for i in embed_values: = thumbnail \
if i.strip().lower().startswith('ptext='): = color \
ptext = i.strip()[6:].strip() = footer \
elif i.strip().lower().startswith('title='): = author \
title = i.strip()[6:].strip() = None
elif i.strip().lower().startswith('description='): timestamp = discord.Embed.Empty
description = i.strip()[12:].strip() embed_values = msg.split('|')
elif i.strip().lower().startswith('desc='): for i in embed_values:
description = i.strip()[5:].strip() if i.strip().lower().startswith('ptext='):
elif i.strip().lower().startswith('image='): ptext = i.strip()[6:].strip()
image = i.strip()[6:].strip() elif i.strip().lower().startswith('title='):
elif i.strip().lower().startswith('thumbnail='): title = i.strip()[6:].strip()
thumbnail = i.strip()[10:].strip() elif i.strip().lower().startswith('description='):
elif i.strip().lower().startswith('colour='): description = i.strip()[12:].strip()
color = i.strip()[7:].strip() elif i.strip().lower().startswith('desc='):
elif i.strip().lower().startswith('color='): description = i.strip()[5:].strip()
color = i.strip()[6:].strip() elif i.strip().lower().startswith('image='):
elif i.strip().lower().startswith('footer='): image = i.strip()[6:].strip()
footer = i.strip()[7:].strip() elif i.strip().lower().startswith('thumbnail='):
elif i.strip().lower().startswith('author='): thumbnail = i.strip()[10:].strip()
author = i.strip()[7:].strip() elif i.strip().lower().startswith('colour='):
elif i.strip().lower().startswith('timestamp'): color = i.strip()[7:].strip()
timestamp = ctx.message.created_at elif i.strip().lower().startswith('color='):
else: color = i.strip()[6:].strip()
if description is None and not i.strip().lower().startswith('field='): elif i.strip().lower().startswith('footer='):
description = i.strip() footer = i.strip()[7:].strip()
elif i.strip().lower().startswith('author='):
author = i.strip()[7:].strip()
elif i.strip().lower().startswith('timestamp'):
timestamp = ctx.message.created_at
else:
if description is None and not i.strip()\
.lower().startswith('field='):
description = i.strip()
if color: if color:
if color.startswith('#'): if color.startswith('#'):
color = color[1:] color = color[1:]
if not color.startswith('0x'): if not color.startswith('0x'):
color = '0x' + color color = '0x' + color
if ptext is title is description is image is thumbnail is color is footer is author is None and 'field=' not in msg: if ptext \
try: is title \
await ctx.message.delete() is description \
except: is image \
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") is thumbnail \
return await ctx.send(content=None, is color \
embed=discord.Embed(description=msg)) is footer \
is author \
is None \
and 'field=' not in msg:
try:
await ctx.message.delete()
except Exception:
print("Impossible de supprimer le message \"" + str(
ctx.message.content) + "\"")
return await ctx.send(content=None,
embed=discord.Embed(description=msg))
if color: if color:
em = discord.Embed(timestamp=timestamp, title=title, description=description, color=int(color, 16)) em = discord.Embed(timestamp=timestamp, title=title,
else: description=description,
em = discord.Embed(timestamp=timestamp, title=title, description=description) color=int(color, 16))
for i in embed_values: else:
if i.strip().lower().startswith('field='): em = discord.Embed(timestamp=timestamp, title=title,
field_inline = True description=description)
field = i.strip().lstrip('field=') for i in embed_values:
field_name, field_value = field.split('value=') if i.strip().lower().startswith('field='):
if 'inline=' in field_value: field_inline = True
field_value, field_inline = field_value.split('inline=') field = i.strip().lstrip('field=')
if 'false' in field_inline.lower() or 'no' in field_inline.lower(): field_name, field_value = field.split('value=')
field_inline = False if 'inline=' in field_value:
field_name = field_name.strip().lstrip('name=') field_value, field_inline = field_value.split(
em.add_field(name=field_name, value=field_value.strip(), inline=field_inline) 'inline=')
if author: if 'false' in field_inline.lower() \
if 'icon=' in author: or 'no' in field_inline.lower():
text, icon = author.split('icon=') field_inline = False
if 'url=' in icon: field_name = field_name.strip().lstrip('name=')
em.set_author(name=text.strip()[5:], icon_url=icon.split('url=')[0].strip(), url=icon.split('url=')[1].strip()) em.add_field(name=field_name, value=field_value.strip(),
else: inline=field_inline)
em.set_author(name=text.strip()[5:], icon_url=icon) if author:
else: if 'icon=' in author:
if 'url=' in author: text, icon = author.split('icon=')
em.set_author(name=author.split('url=')[0].strip()[5:], url=author.split('url=')[1].strip()) if 'url=' in icon:
else: em.set_author(name=text.strip()[5:],
em.set_author(name=author) icon_url=icon.split('url=')[0].strip(),
url=icon.split('url=')[1].strip())
else:
em.set_author(name=text.strip()[5:], icon_url=icon)
else:
if 'url=' in author:
em.set_author(name=author.split('url=')[0].strip()[5:],
url=author.split('url=')[1].strip())
else:
em.set_author(name=author)
if image: if image:
em.set_image(url=image) em.set_image(url=image)
if thumbnail: if thumbnail:
em.set_thumbnail(url=thumbnail) em.set_thumbnail(url=thumbnail)
if footer: if footer:
if 'icon=' in footer: if 'icon=' in footer:
text, icon = footer.split('icon=') text, icon = footer.split('icon=')
em.set_footer(text=text.strip()[5:], icon_url=icon) em.set_footer(text=text.strip()[5:], icon_url=icon)
else: else:
em.set_footer(text=footer) em.set_footer(text=footer)
try: try:
await ctx.message.delete() await ctx.message.delete()
except: except Exception:
print("Impossible de supprimer le message \"" + str(ctx.message.content) + "\"") print("Impossible de supprimer le message \"" + str(
await ctx.send(content=ptext, embed=em) ctx.message.content) + "\"")
await ctx.send(content=ptext, embed=em)
else: else:
embed=discord.Embed(title="Aide sur l'utilisation de la commande .embed:") embed = discord.Embed(
embed.add_field(name="Titre:", value="title=<le titre>", inline=True) title="Aide sur l'utilisation de la commande .embed:")
embed.add_field(name="Description:", value="description=<la description>", inline=True) embed.add_field(name="Titre:", value="title=<le titre>",
embed.add_field(name="Couleur:", value="color=<couleur en hexa>", inline=True) inline=True)
embed.add_field(name="Image:", value="image=<url de l'image (en https)>", inline=True) embed.add_field(name="Description:",
embed.add_field(name="Thumbnail:", value="thumbnail=<url de l'image>", inline=True) value="description=<la description>", inline=True)
embed.add_field(name="Auteur:", value="author=<nom de l'auteur>", inline=True) embed.add_field(name="Couleur:", value="color=<couleur en hexa>",
embed.add_field(name="Icon", value="icon=<url de l'image>", inline=True) inline=True)
embed.add_field(name="Footer", value="footer=<le footer>", inline=True) embed.add_field(name="Image:",
embed.set_footer(text="Exemple: .embed title=Un titre | description=Une description | color=3AB35E | field=name=test value=test") value="image=<url de l'image (en https)>",
inline=True)
embed.add_field(name="Thumbnail:",
value="thumbnail=<url de l'image>", inline=True)
embed.add_field(name="Auteur:", value="author=<nom de l'auteur>",
inline=True)
embed.add_field(name="Icon", value="icon=<url de l'image>",
inline=True)
embed.add_field(name="Footer", value="footer=<le footer>",
inline=True)
embed.set_footer(text="Exemple: .embed title=Un titre |"
" description=Une description |"
" color=3AB35E |"
" field=name=test value=test")
await ctx.send(embed=embed) await ctx.send(embed=embed)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True)
@commands.command(pass_context=True, hidden=True)
async def repl(self, ctx):
"""Launches an interactive REPL session."""
variables = {
'ctx': ctx,
'bot': self.bot,
'message': ctx.message,
'guild': ctx.guild,
'channel': ctx.channel,
'author': ctx.author,
'_': None,
}
if ctx.channel.id in self.sessions:
await ctx.send('Already running a REPL session in this channel.'
' Exit it with `quit`.')
return
self.sessions.add(ctx.channel.id)
await ctx.send(
'Enter code to execute or evaluate. `exit()` or `quit` to exit.')
def check(m):
return m.author.id == ctx.author.id and \
m.channel.id == ctx.channel.id and \
m.content.startswith('`')
while True:
try:
response = await self.bot.wait_for('message', check=check,
timeout=10.0 * 60.0)
except asyncio.TimeoutError:
await ctx.send('Exiting REPL session.')
self.sessions.remove(ctx.channel.id)
break
cleaned = self.cleanup_code(response.content)
if cleaned in ('quit', 'exit', 'exit()'):
await ctx.send('Exiting.')
self.sessions.remove(ctx.channel.id)
return
executor = exec
if cleaned.count('\n') == 0:
# single statement, potentially 'eval'
try:
code = compile(cleaned, '<repl session>', 'eval')
except SyntaxError:
pass
else:
executor = eval
if executor is exec:
try:
code = compile(cleaned, '<repl session>', 'exec')
except SyntaxError as e:
await ctx.send(self.get_syntax_error(e))
continue
variables['message'] = response
fmt = None
stdout = io.StringIO()
try:
with redirect_stdout(stdout):
result = executor(code, variables)
if inspect.isawaitable(result):
result = await result
except Exception as e:
value = stdout.getvalue()
fmt = f'```py\n{value}{traceback.format_exc()}\n```'
else:
value = stdout.getvalue()
if result is not None:
fmt = f'```py\n{value}{result}\n```'
variables['_'] = result
elif value:
fmt = f'```py\n{value}\n```'
try:
if fmt is not None:
if len(fmt) > 2000:
await ctx.send('Content too big to be printed.')
else:
await ctx.send(fmt)
except discord.Forbidden:
pass
except discord.HTTPException as e:
await ctx.send(f'Unexpected error: `{e}`')
"""---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True)
@commands.command(pass_context=True, hidden=True, name='eval')
async def _eval(self, ctx, *, body: str):
"""Evaluates a code"""
env = {
'bot': self.bot,
'ctx': ctx,
'channel': ctx.channel,
'author': ctx.author,
'guild': ctx.guild,
'message': ctx.message,
'_': self._last_result
}
env.update(globals())
body = self.cleanup_code(body)
stdout = io.StringIO()
to_compile = f'async def func():\n{textwrap.indent(body, " ")}'
try:
exec(to_compile, env)
except Exception as e:
return await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```')
func = env['func']
try:
with redirect_stdout(stdout):
ret = await func()
except Exception:
value = stdout.getvalue()
await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```')
else:
value = stdout.getvalue()
try:
await ctx.message.add_reaction('\u2705')
except Exception:
pass
if ret is None:
if value:
await ctx.send(f'```py\n{value}\n```')
else:
self._last_result = ret
await ctx.send(f'```py\n{value}{ret}\n```')
def setup(bot): def setup(bot):
bot.add_cog(Admin(bot)) bot.add_cog(Admin(bot))

View file

@ -1,62 +1,53 @@
from discord.ext import commands from discord.ext import commands
import discord
import random import random
class AFK: class AFK(commands.Cog):
"""Commandes utilitaires.""" """Commandes utilitaires."""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.afk_users = []
"""---------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command(pass_context=True) @commands.command(pass_context=True)
async def afk(self, ctx): async def afk(self, ctx, action: str = ""):
user = ctx.message.author
try: if action.lower() == "list":
await user.edit(nick="[AFK] "+str(user.name)) try:
author = ctx.message.author await ctx.send(*self.afk_users)
channel = await author.create_dm() except discord.HTTPException:
await channel.send("Ton pseudo a prit le prefix `[AFK]` pour " await ctx.send("Il n'y a personne d'afk...")
"monter que tu es absent,") else:
await channel.send("tu auras juste a mettre un message pour que " user = ctx.author
"je signale ton retour parmis nous et que je " self.afk_users.append(user)
"retire le prefix `[AFK]` de ton pseudo 😉") msgs = ["s'absente de discord quelques instants",
"se casse de son pc",
"va sortir son chien",
"reviens bientôt",
"va nourrir son cochon",
"va manger des cookies",
"va manger de la poutine",
"va faire caca",
"va faire pipi"]
except KeyError: await ctx.send(f"**{user.mention}** {random.choice(msgs)}...")
print('')
author = ctx.message.author
channel = await author.create_dm()
await channel.send("Tu auras juste a mettre un message pour que "
"je signale ton retour parmis nous 😉")
msgs = ["s'absente de discord quelques instants",
"se casse de son pc",
"va sortir son chien",
"reviens bientôt",
"va nourrir son cochon",
"va manger des cookies",
"va manger de la poutine",
"va faire caca",
"va faire pipi"]
msg = random.choice(msgs)
await ctx.send("**{}** {}...".format(ctx.message.author.mention, msg))
"""---------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot \
or message.guild.id != int(self.bot.config.main_server_id):
return
async def on_message(message): user = message.author
ni = str(message.author.nick) if user in self.afk_users \
and message.content != self.bot.config.prefix[0] + "afk":
if ni: self.afk_users.remove(user)
ni2 = ni.split(" ")
if "[AFK]" in ni2:
user = message.author
await user.edit(nick=None)
msgs = ["a réssuscité", msgs = ["a réssuscité",
"est de nouveau parmi nous", "est de nouveau parmi nous",
@ -68,10 +59,9 @@ async def on_message(message):
"a fini de danser", "a fini de danser",
"s'est réveillé", "s'est réveillé",
"est de retour dans ce monde cruel"] "est de retour dans ce monde cruel"]
msg = random.choice(msgs)
await message.channel.send("**{}** {} !".format( await message.channel.send(f"**{user.mention}**"
message.author.mention, msg)) f" {random.choice(msgs)}...")
def setup(bot): def setup(bot):

124
cogs/atc.py Executable file
View file

@ -0,0 +1,124 @@
import asyncio
from bs4 import BeautifulSoup
import requests
import re
import discord
from discord.ext import commands
class ATC(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.playing = False
self.author = None
self.voice = None
@staticmethod
async def extra(self, ctx, icao):
if icao == "stop_playing":
if self.playing and (
ctx.author.id == self.author.id
or ctx.message.channel.permissions_for(ctx.message.author).administrator is True
):
await self.voice.disconnect()
self.playing = False
await ctx.send("Écoute terminée !")
return "quit"
else:
await ctx.send("Veuillez specifier un icao")
return "quit"
if icao == "info":
em = discord.Embed(title=f"Infos sur les services utilisés par {self.bot.config.prefix[0]}atc")
em.add_field(name="Service pour les communications:",
value="[liveatc.net](https://www.liveatc.net/)",
inline=False)
em.add_field(name="Service pour les plans des aéroports:",
value="[universalweather.com](http://www.universalweather.com/)",
inline=False)
await ctx.send(embed=em)
return "quit"
"""---------------------------------------------------------------------"""
@commands.command(name="atc", no_pm=True, pass_context=True)
async def _atc(self, ctx, icao="stop_playing"):
user = ctx.author
if not user.voice:
await ctx.send('Veuillez aller dans un channel vocal.')
return
if await self.extra(self, ctx, icao) == "quit":
return
if self.playing:
await ctx.send(f"Une écoute est déja en court, "
f"demandez à {self.author.mention} de faire "
f"`.atc stop_playing` pour l'arreter")
return
self.author = user
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.35 Safari/537.36',
}
req = requests.post("https://www.liveatc.net/search/",
data={'icao': icao},
headers=headers)
html = BeautifulSoup(req.text, features="lxml")
regex = r"(javascript: pageTracker\._trackPageview\('\/listen\/)(.*)(\'\)\;)"
possibilities = {}
emojis = ['1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣', '🔟',
'0⃣', '🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬', '🇭', '🇮']
to_react = []
idx = 0
for a in html.findAll("a", onclick=True):
val = a.get('onclick')
for match in re.finditer(regex, val):
possibilities[idx] = f"{emojis[idx]} - {match.groups()[1]}\n"
to_react.append(emojis[idx])
idx += 1
em = discord.Embed(title='Résultats pour : ' + icao,
description=str(''.join(possibilities.values())),
colour=0x4ECDC4)
em.set_image(
url=f"http://www.universalweather.com/regusers/mod-bin/uvtp_airport_image?icao={icao}")
poll_msg = await ctx.send(embed=em)
for emote in to_react:
await poll_msg.add_reaction(emote)
def check(reaction, user):
return user == ctx.author and reaction.emoji in to_react and \
reaction.message.id == poll_msg.id
async def waiter(future: asyncio.Future):
reaction, user = await self.bot.wait_for('reaction_add',
check=check)
future.set_result(emojis.index(reaction.emoji))
added_emoji = asyncio.Future()
self.bot.loop.create_task(waiter(added_emoji))
while not added_emoji.done():
await asyncio.sleep(0.1)
freq = possibilities[added_emoji.result()].split('- ')[1]
if possibilities:
self.playing = True
self.voice = await user.voice.channel.connect()
self.voice.play(
discord.FFmpegPCMAudio(f"http://yyz.liveatc.net/{freq}"))
await poll_msg.delete()
await ctx.send(f"Écoute de {freq}")
else:
await ctx.send(f"Aucun résultat trouvé pour {icao} {freq}")
def setup(bot):
bot.add_cog(ATC(bot))

View file

@ -1,67 +1,70 @@
from discord.ext import commands
import discord
import platform import platform
import socket import socket
import subprocess import subprocess
import discord
from discord.ext import commands
from discord.http import Route
class Basics:
"""Commandes générales."""
def __init__(self, bot): class Basics(commands.Cog):
self.bot = bot """Commandes générales."""
@commands.command() def __init__(self, bot):
async def ping(self, ctx): self.bot = bot
ping_res = str(subprocess.Popen(["/bin/ping", "-c1", "discordapp.com"], stdout=subprocess.PIPE).stdout.read())
formated_res = [item for item in ping_res.split() if 'time=' in item]
result = str(formated_res[0])[5:]
if float(result) >= 200: @commands.command()
em = discord.Embed(title="Ping : " + str(result) + "ms", async def ping(self, ctx):
description="... c'est quoi ce ping !", ping_res = str(subprocess.Popen(["/bin/ping", "-c1", "discordapp.com"],
colour=0xFF1111) stdout=subprocess.PIPE).stdout.read())
await ctx.send(embed=em) formated_res = [item for item in ping_res.split() if 'time=' in item]
elif float(result) > 100 < 200: result = str(formated_res[0])[5:]
em = discord.Embed(title="Ping : " + str(result) + "ms",
description="Ca va, ça peut aller, mais j'ai "
"l'impression d'avoir 40 ans !",
colour=0xFFA500)
await ctx.send(embed=em)
else:
em = discord.Embed(title="Ping : " + str(result) + "ms",
description="Wow c'te vitesse de réaction, "
"je m'épate moi-même !",
colour=0x11FF11)
await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" if float(result) >= 200:
em = discord.Embed(title="Ping : " + str(result) + "ms",
description="... c'est quoi ce ping !",
colour=0xFF1111)
await ctx.send(embed=em)
elif float(result) > 100 < 200:
em = discord.Embed(title="Ping : " + str(result) + "ms",
description="Ca va, ça peut aller, mais j'ai "
"l'impression d'avoir 40 ans !",
colour=0xFFA500)
await ctx.send(embed=em)
else:
em = discord.Embed(title="Ping : " + str(result) + "ms",
description="Wow c'te vitesse de réaction, "
"je m'épate moi-même !",
colour=0x11FF11)
await ctx.send(embed=em)
@commands.command() """---------------------------------------------------------------------"""
async def info(self, ctx):
"""Affiches des informations sur le bot"""
text = open('texts/info.md').read()
os_info = str(platform.system()) + " / " + str(platform.release())
em = discord.Embed(title='Informations sur TuxBot',
description=text.format(os_info,
platform.python_version(),
socket.gethostname(),
discord.__version__),
colour=0x89C4F9)
em.set_footer(text="/home/****/bot.py")
await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" @commands.command()
async def info(self, ctx):
"""Affiches des informations sur le bot"""
text = open('texts/info.md').read()
os_info = str(platform.system()) + " / " + str(platform.release())
em = discord.Embed(title='Informations sur TuxBot',
description=text.format(os_info,
platform.python_version(),
socket.gethostname(),
discord.__version__,
Route.BASE),
colour=0x89C4F9)
em.set_footer(text="/home/****/bot.py")
await ctx.send(embed=em)
@commands.command() """---------------------------------------------------------------------"""
async def help(self, ctx):
"""Affiches l'aide du bot"""
text = open('texts/help.md').read()
em = discord.Embed(title='Commandes de TuxBot', description=text,
colour=0x89C4F9)
await ctx.send(embed=em)
@commands.command()
async def help(self, ctx):
"""Affiches l'aide du bot"""
text = open('texts/help.md').read()
text = text.split("[split]")
for text_result in text:
em = discord.Embed(title='Commandes de TuxBot', description=text_result,colour=0x89C4F9)
await ctx.send(embed=em)
def setup(bot): def setup(bot):
bot.add_cog(Basics(bot)) bot.add_cog(Basics(bot))

View file

@ -1,313 +1,311 @@
from discord.ext import commands import datetime
import random
import discord import discord
import requests
from discord.ext import commands
from .utils import checks from .utils import checks
from .utils import db from .utils import db
from .utils.checks import get_user, check_date from .utils.checks import get_user, check_date
import datetime
import random
import pymysql class Identity(commands.Cog):
import requests """Commandes des cartes d'identité ."""
def __init__(self, bot):
self.bot = bot
class Identity: self.conn = db.connect_to_db(self)
"""Commandes des cartes d'identité .""" self.cursor = self.conn.cursor()
def __init__(self, bot): self.cursor.execute("""SHOW TABLES LIKE 'users'""")
self.bot = bot result = self.cursor.fetchone()
self.conn = db.connect_to_db(self) if not result:
self.cursor = self.conn.cursor() # Creation table Utilisateur si premiere fois
sql = "CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, userid TEXT null, username TEXT null, os TEXT null, config TEXT null, useravatar TEXT null, userbirth TEXT null, pays TEXT null, cidate TEXT null, cibureau TEXT null);"
self.cursor.execute(sql)
self.cursor.execute("""SHOW TABLES LIKE 'users'""") """--------------------------------------------------------------------------------------------------------------------------"""
result = self.cursor.fetchone()
if not result: @commands.group(name="ci", no_pm=True, pass_context=True)
# Creation table Utilisateur si premiere fois async def _ci(self, ctx):
sql = "CREATE TABLE users ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, userid TEXT null, username TEXT null, os TEXT null, config TEXT null, useravatar TEXT null, userbirth TEXT null, pays TEXT null, cidate TEXT null, cibureau TEXT null);" """Cartes d'identité"""
self.cursor.execute(sql)
if ctx.invoked_subcommand is None:
text = open('texts/ci-info.md').read()
em = discord.Embed(title='Commandes de carte d\'identité de TuxBot', description=text, colour=0x89C4F9)
await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" """--------------------------------------------------------------------------------------------------------------------------"""
@commands.group(name="ci", no_pm=True, pass_context=True) @_ci.command(pass_context=True, name="show")
async def _ci(self, ctx): async def ci_show(self, ctx, args: str = None):
"""Cartes d'identité""" self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
if ctx.invoked_subcommand is None:
text = open('texts/ci-info.md').read()
em = discord.Embed(title='Commandes de carte d\'identité de TuxBot', description=text, colour=0x89C4F9)
await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" if args == None:
user = get_user(ctx.message, ctx.author.name)
else:
user = get_user(ctx.message, args)
@_ci.command(pass_context=True, name="show") if user:
async def ci_show(self, ctx, args: str = None): self.cursor.execute("""SELECT userid, username, useravatar, userbirth, cidate, cibureau, os, config, pays, id FROM users WHERE userid=%s""",(str(user.id)))
self.conn = db.connect_to_db(self) result = self.cursor.fetchone()
self.cursor = self.conn.cursor()
if args == None: def isexist(var):
user = get_user(ctx.message, ctx.author.name) if not var:
else: return "Non renseigné."
user = get_user(ctx.message, args) else:
return var
if user: if not result:
self.cursor.execute("""SELECT userid, username, useravatar, userbirth, cidate, cibureau, os, config, pays, id FROM users WHERE userid=%s""",(str(user.id))) await ctx.send(f"{ctx.author.mention}> :x: Désolé mais {user.mention} est sans papier !")
result = self.cursor.fetchone() else:
try:
user_birth = datetime.datetime.fromisoformat(result[3])
user_birth_day = check_date(str(user_birth.day))
user_birth_month = check_date(str(user_birth.month))
def isexist(var): formated_user_birth = str(user_birth_day) + "/" + str(user_birth_month) + "/" + str(user_birth.year)
if not var:
return "Non renseigné."
else:
return var
if not result: try: ## a virer une fois le patch appliqué pour tout le monde
await ctx.send(f"{ctx.author.mention}> :x: Désolé mais {user.mention} est sans papier !") cidate = datetime.datetime.fromisoformat(result[4])
else: cidate_day = check_date(str(cidate.day)) ## a garder
try: cidate_month = check_date(str(cidate.month)) ## a garder
user_birth = datetime.datetime.fromisoformat(result[3])
user_birth_day = check_date(str(user_birth.day))
user_birth_month = check_date(str(user_birth.month))
formated_user_birth = str(user_birth_day) + "/" + str(user_birth_month) + "/" + str(user_birth.year) formated_cidate = str(cidate_day) + "/" + str(cidate_month) + "/" + str(cidate.year) ## a garder
except ValueError: ## a virer une fois le patch appliqué pour tout le monde
formated_cidate = str(result[4]).replace('-', '/') ## a virer une fois le patch appliqué pour tout le monde
await ctx.send(f"{user.mention} vous êtes prié(e) de faire la commande `.ci update` afin de regler un probleme de date coté bdd") ## a virer une fois le patch appliqué pour tout le monde
try: ## a virer une fois le patch appliqué pour tout le monde embed=discord.Embed(title="Carte d'identité | Communisme Linuxien")
cidate = datetime.datetime.fromisoformat(result[4]) embed.set_author(name=result[1], icon_url=result[2])
cidate_day = check_date(str(cidate.day)) ## a garder embed.set_thumbnail(url = result[2])
cidate_month = check_date(str(cidate.month)) ## a garder embed.add_field(name="Nom :", value=result[1], inline=True)
embed.add_field(name="Système d'exploitation :", value=isexist(result[6]), inline=True)
embed.add_field(name="Configuration Système : ", value=isexist(result[7]), inline=True)
embed.add_field(name="Date de naissance sur discord : ", value=formated_user_birth, inline=True)
embed.add_field(name="Pays : ", value=isexist(result[8]), inline=True)
embed.add_field(name="Profil sur le web : ", value=f"https://tuxbot.gnous.eu/users/{result[9]}", inline=True)
embed.set_footer(text=f"Enregistré dans le bureau {result[5]} le {formated_cidate}.")
await ctx.send(embed=embed)
except Exception as e:
await ctx.send(f"{ctx.author.mention}> :x: Désolé mais la carte d'identité de {user.mention} est trop longue de ce fait je ne peux te l'envoyer, essaye de l'aléger, {user.mention} :wink: !")
await ctx.send(f':sob: Une erreur est survenue : \n {type(e).__name__}: {e}')
else:
return await ctx.send('Impossible de trouver l\'user.')
formated_cidate = str(cidate_day) + "/" + str(cidate_month) + "/" + str(cidate.year) ## a garder """--------------------------------------------------------------------------------------------------------------------------"""
except ValueError: ## a virer une fois le patch appliqué pour tout le monde
formated_cidate = str(result[4]).replace('-', '/') ## a virer une fois le patch appliqué pour tout le monde @_ci.command(pass_context=True, name="register")
await ctx.send(f"{user.mention} vous êtes prié(e) de faire la commande `.ci update` afin de regler un probleme de date coté bdd") ## a virer une fois le patch appliqué pour tout le monde async def ci_register(self, ctx):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
embed=discord.Embed(title="Carte d'identité | Communisme Linuxien") self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id)))
embed.set_author(name=result[1], icon_url=result[2]) result = self.cursor.fetchone()
embed.set_thumbnail(url = result[2])
embed.add_field(name="Nom :", value=result[1], inline=True)
embed.add_field(name="Système d'exploitation :", value=isexist(result[6]), inline=True)
embed.add_field(name="Configuration Système : ", value=isexist(result[7]), inline=True)
embed.add_field(name="Date de naissance sur discord : ", value=formated_user_birth, inline=True)
embed.add_field(name="Pays : ", value=isexist(result[8]), inline=True)
embed.add_field(name="Profil sur le web : ", value=f"https://tuxbot.gnous.eu/users/{result[9]}", inline=True)
embed.set_footer(text=f"Enregistré dans le bureau {result[5]} le {formated_cidate}.")
await ctx.send(embed=embed)
except Exception as e:
await ctx.send(f"{ctx.author.mention}> :x: Désolé mais la carte d'identité de {user.mention} est trop longue de ce fait je ne peux te l'envoyer, essaye de l'aléger, {user.mention} :wink: !")
await ctx.send(f':sob: Une erreur est survenue : \n {type(e).__name__}: {e}')
else:
return await ctx.send('Impossible de trouver l\'user.')
"""--------------------------------------------------------------------------------------------------------------------------""" if result:
await ctx.send("Mais tu as déja une carte d'identité ! u_u")
@_ci.command(pass_context=True, name="register") else:
async def ci_register(self, ctx): now = datetime.datetime.now()
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id))) self.cursor.execute("""INSERT INTO users(userid, username, useravatar, userbirth, cidate, cibureau) VALUES(%s, %s, %s, %s, %s, %s)""", (str(ctx.author.id), str(ctx.author), str(ctx.author.avatar_url_as(format="jpg", size=512)), str(ctx.author.created_at), now, str(ctx.message.guild.name)))
result = self.cursor.fetchone() self.conn.commit()
await ctx.send(f":clap: Bievenue à toi {ctx.author.name} dans le communisme {ctx.message.guild.name} ! Fait ``.ci`` pour plus d'informations !")
if result: """--------------------------------------------------------------------------------------------------------------------------"""
await ctx.send("Mais tu as déja une carte d'identité ! u_u")
else: @_ci.command(pass_context=True, name="delete")
now = datetime.datetime.now() async def ci_delete(self, ctx):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
self.cursor.execute("""INSERT INTO users(userid, username, useravatar, userbirth, cidate, cibureau) VALUES(%s, %s, %s, %s, %s, %s)""", (str(ctx.author.id), str(ctx.author), str(ctx.author.avatar_url_as(format="jpg", size=512)), str(ctx.author.created_at), now, str(ctx.message.guild.name))) self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id)))
self.conn.commit() result = self.cursor.fetchone()
await ctx.send(f":clap: Bievenue à toi {ctx.author.name} dans le communisme {ctx.message.guild.name} ! Fait ``.ci`` pour plus d'informations !")
"""--------------------------------------------------------------------------------------------------------------------------""" if result:
self.cursor.execute("""DELETE FROM users WHERE userid =%s""", (str(ctx.author.id)))
@_ci.command(pass_context=True, name="delete") self.conn.commit()
async def ci_delete(self, ctx): await ctx.send("Tu es maintenant sans papiers !")
self.conn = db.connect_to_db(self) else:
self.cursor = self.conn.cursor() await ctx.send("Déja enregistre ta carte d'identité avant de la supprimer u_u (après c'est pas logique...)")
self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id))) """--------------------------------------------------------------------------------------------------------------------------"""
result = self.cursor.fetchone()
@_ci.command(pass_context=True, name="update")
async def ci_update(self, ctx):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
if result: try:
self.cursor.execute("""DELETE FROM users WHERE userid =%s""", (str(ctx.author.id))) self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id)))
self.conn.commit() result = self.cursor.fetchone()
await ctx.send("Tu es maintenant sans papiers !")
else:
await ctx.send("Déja enregistre ta carte d'identité avant de la supprimer u_u (après c'est pas logique...)")
"""--------------------------------------------------------------------------------------------------------------------------""" if result:
self.cursor.execute("""SELECT cidate FROM users WHERE userid=%s""",(str(ctx.author.id)))
@_ci.command(pass_context=True, name="update") old_ci_date = self.cursor.fetchone()
async def ci_update(self, ctx):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
try: try:
self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id))) new_ci_date = datetime.datetime.fromisoformat(old_ci_date[0])
result = self.cursor.fetchone() except ValueError:
old_ci_date = datetime.datetime.strptime(old_ci_date[0].replace('/', '-'), '%d-%m-%Y')
if result: old_ci_date_day = check_date(str(old_ci_date.day))
self.cursor.execute("""SELECT cidate FROM users WHERE userid=%s""",(str(ctx.author.id))) old_ci_date_month = check_date(str(old_ci_date.month))
old_ci_date = self.cursor.fetchone()
try: new_ci_date = f"{str(old_ci_date.year)}-{str(old_ci_date_month)}-{str(old_ci_date_day)} 00:00:00.000000"
new_ci_date = datetime.datetime.fromisoformat(old_ci_date[0])
except ValueError:
old_ci_date = datetime.datetime.strptime(old_ci_date[0].replace('/', '-'), '%d-%m-%Y')
old_ci_date_day = check_date(str(old_ci_date.day)) await ctx.send("succes update")
old_ci_date_month = check_date(str(old_ci_date.month))
new_ci_date = f"{str(old_ci_date.year)}-{str(old_ci_date_month)}-{str(old_ci_date_day)} 00:00:00.000000" self.cursor.execute("""UPDATE users SET cidate = %s WHERE userid = %s""", (str(new_ci_date), str(ctx.author.id)))
self.conn.commit()
await ctx.send("succes update") self.cursor.execute("""UPDATE users SET useravatar = %s, username = %s, cibureau = %s WHERE userid = %s""", (str(ctx.author.avatar_url_as(format="jpg", size=512)), str(ctx.author), str(ctx.message.guild), str(ctx.author.id)))
self.conn.commit()
await ctx.send(f"{ctx.author.mention}> Tu viens, en quelques sortes, de renaitre !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Veuillez enregistrer votre carte d'identité pour commencer !")
self.cursor.execute("""UPDATE users SET cidate = %s WHERE userid = %s""", (str(new_ci_date), str(ctx.author.id))) except Exception as e: #TODO : A virer dans l'event on_error
self.conn.commit() await ctx.send(':( Erreur veuillez contacter votre administrateur :')
await ctx.send(f'{type(e).__name__}: {e}')
self.cursor.execute("""UPDATE users SET useravatar = %s, username = %s, cibureau = %s WHERE userid = %s""", (str(ctx.author.avatar_url_as(format="jpg", size=512)), str(ctx.author), str(ctx.message.guild), str(ctx.author.id))) """--------------------------------------------------------------------------------------------------------------------------"""
self.conn.commit()
await ctx.send(f"{ctx.author.mention}> Tu viens, en quelques sortes, de renaitre !") @_ci.command(pass_context=True, name="setconfig")
else: async def ci_setconfig(self, ctx, *, conf: str = None):
await ctx.send(f"{ctx.author.mention}> :x: Veuillez enregistrer votre carte d'identité pour commencer !") self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
except Exception as e: #TODO : A virer dans l'event on_error if conf:
await ctx.send(':( Erreur veuillez contacter votre administrateur :') self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id)))
await ctx.send(f'{type(e).__name__}: {e}') result = self.cursor.fetchone()
"""--------------------------------------------------------------------------------------------------------------------------""" if result:
self.cursor.execute("""UPDATE users SET config = %s WHERE userid = %s""", (str(conf), str(ctx.author.id)))
@_ci.command(pass_context=True, name="setconfig") self.conn.commit()
async def ci_setconfig(self, ctx, *, conf: str = None): await ctx.send(f"{ctx.author.mention}> :ok_hand: Carte d'identité mise à jour !")
self.conn = db.connect_to_db(self) else:
self.cursor = self.conn.cursor() await ctx.send(f"{ctx.author.mention}> :x: Veuillez enregistrer votre carte d'identité pour commencer !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Il manque un paramètre !")
if conf: """--------------------------------------------------------------------------------------------------------------------------"""
self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id)))
result = self.cursor.fetchone() @_ci.command(pass_context=True, name="setos")
async def ci_setos(self, ctx, *, conf: str = None):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
if result: if conf:
self.cursor.execute("""UPDATE users SET config = %s WHERE userid = %s""", (str(conf), str(ctx.author.id))) self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id)))
self.conn.commit() result = self.cursor.fetchone()
await ctx.send(f"{ctx.author.mention}> :ok_hand: Carte d'identité mise à jour !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Veuillez enregistrer votre carte d'identité pour commencer !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Il manque un paramètre !")
"""--------------------------------------------------------------------------------------------------------------------------""" if result:
self.cursor.execute("""UPDATE users SET os = %s WHERE userid = %s""", (str(conf), str(ctx.author.id)))
@_ci.command(pass_context=True, name="setos") self.conn.commit()
async def ci_setos(self, ctx, *, conf: str = None): await ctx.send(f"{ctx.author.mention}> :ok_hand: Carte d'identité mise à jour !")
self.conn = db.connect_to_db(self) else:
self.cursor = self.conn.cursor() await ctx.send(f"{ctx.author.mention}> :x: Veuillez enregistrer votre carte d'identité pour commencer !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Il manque un paramètre !")
if conf: """--------------------------------------------------------------------------------------------------------------------------"""
self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id)))
result = self.cursor.fetchone() @_ci.command(pass_context=True, name="setcountry")
async def ci_setcountry(self, ctx, *, country: str = None):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
if result: if country:
self.cursor.execute("""UPDATE users SET os = %s WHERE userid = %s""", (str(conf), str(ctx.author.id))) self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id)))
self.conn.commit() result = self.cursor.fetchone()
await ctx.send(f"{ctx.author.mention}> :ok_hand: Carte d'identité mise à jour !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Veuillez enregistrer votre carte d'identité pour commencer !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Il manque un paramètre !")
"""--------------------------------------------------------------------------------------------------------------------------""" if result:
self.cursor.execute("""UPDATE users SET pays = %s WHERE userid = %s""", (str(country), str(ctx.author.id)))
@_ci.command(pass_context=True, name="setcountry") self.conn.commit()
async def ci_setcountry(self, ctx, *, country: str = None): await ctx.send(f"{ctx.author.mention}> :ok_hand: Carte d'identité mise à jour !")
self.conn = db.connect_to_db(self) else:
self.cursor = self.conn.cursor() await ctx.send(f"{ctx.author.mention}> :x: Veuillez enregistrer votre carte d'identité pour commencer !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Il manque un paramètre !")
if country: """--------------------------------------------------------------------------------------------------------------------------"""
self.cursor.execute("""SELECT id, userid FROM users WHERE userid=%s""", (str(ctx.author.id)))
result = self.cursor.fetchone() @_ci.command(pass_context=True, name="online_edit")
async def ci_online_edit(self, ctx):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
if result: self.cursor.execute("""SELECT id FROM users WHERE userid=%s""",(str(ctx.author.id)))
self.cursor.execute("""UPDATE users SET pays = %s WHERE userid = %s""", (str(country), str(ctx.author.id))) result = self.cursor.fetchone()
self.conn.commit()
await ctx.send(f"{ctx.author.mention}> :ok_hand: Carte d'identité mise à jour !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Veuillez enregistrer votre carte d'identité pour commencer !")
else:
await ctx.send(f"{ctx.author.mention}> :x: Il manque un paramètre !")
"""--------------------------------------------------------------------------------------------------------------------------""" if not result:
return await ctx.send(f"Déja enregistre ta carte d'identité avant de l'éditer u_u (après c'est pas logique...)")
@_ci.command(pass_context=True, name="online_edit")
async def ci_online_edit(self, ctx):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
self.cursor.execute("""SELECT id FROM users WHERE userid=%s""",(str(ctx.author.id))) dm = await ctx.author.create_dm()
result = self.cursor.fetchone()
if not result: try:
return await ctx.send(f"Déja enregistre ta carte d'identité avant de l'éditer u_u (après c'est pas logique...)") def is_exist(key, value):
self.cursor.execute("""SELECT * FROM sessions WHERE {}=%s""".format(str(key)), (str(value)))
return self.cursor.fetchone()
dm = await ctx.author.create_dm() user_id = result[0]
is_admin = '1' if str(ctx.author.id) in self.bot.config.authorized_id else '0'
token = ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'*25, 25))
created_at = datetime.datetime.utcnow()
try: while is_exist('token', token):
def is_exist(key, value): token = ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'*25, 25))
self.cursor.execute("""SELECT * FROM sessions WHERE {}=%s""".format(str(key)), (str(value)))
return self.cursor.fetchone()
user_id = result[0] if is_exist('user_id', user_id):
is_admin = '1' if str(ctx.author.id) in self.bot.config.authorized_id else '0' self.cursor.execute("""UPDATE sessions SET is_admin = %s, token = %s, updated_at = %s WHERE user_id = %s""", (str(is_admin), str(token), str(created_at), str(user_id)))
token = ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'*25, 25)) self.conn.commit()
created_at = datetime.datetime.utcnow() else:
self.cursor.execute("""INSERT INTO sessions(user_id, is_admin, token, created_at, updated_at) VALUES(%s, %s, %s, %s, %s)""", (str(user_id), str(is_admin), str(token), str(created_at), str(created_at)))
self.conn.commit()
while is_exist('token', token): embed=discord.Embed(title="Clé d'édition pour tuxweb", description=f"Voici ta clé d'édition, vas sur [https://tuxbot.gnous.eu/fr/users/{user_id}](https://tuxbot.gnous.eu/fr/users/{user_id}) puis cliques sur `editer` et entre la clé afin de pouvoir modifier ta ci", colour=0x89C4F9)
token = ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'*25, 25)) embed.set_footer(text=f"Cette clé sera valide durant les 10 prochaines minutes, ne la communiques à personne !")
await dm.send(embed=embed)
await dm.send(token)
if is_exist('user_id', user_id): await ctx.send(f"{ctx.author.mention} ta clé d'édition t'a été envoyée en message privé")
self.cursor.execute("""UPDATE sessions SET is_admin = %s, token = %s, updated_at = %s WHERE user_id = %s""", (str(is_admin), str(token), str(created_at), str(user_id)))
self.conn.commit()
else:
self.cursor.execute("""INSERT INTO sessions(user_id, is_admin, token, created_at, updated_at) VALUES(%s, %s, %s, %s, %s)""", (str(user_id), str(is_admin), str(token), str(created_at), str(created_at)))
self.conn.commit()
embed=discord.Embed(title="Clé d'édition pour tuxweb", description=f"Voici ta clé d'édition, vas sur [https://tuxbot.gnous.eu/fr/users/{user_id}](https://tuxbot.gnous.eu/fr/users/{user_id}) puis cliques sur `editer` et entre la clé afin de pouvoir modifier ta ci", colour=0x89C4F9) except Exception as e:
embed.set_footer(text=f"Cette clé sera valide durant les 10 prochaines minutes, ne la communiques à personne !") await ctx.send(f"{ctx.author.mention}, je ne peux pas t'envoyer de message privé :(. Penses à autoriser les messages privés provenant des membres du serveur pour que je puisse te donner ta clef d'édition")
await dm.send(embed=embed)
await dm.send(token)
await ctx.send(f"{ctx.author.mention} ta clé d'édition t'a été envoyée en message privé") """--------------------------------------------------------------------------------------------------------------------------"""
@checks.has_permissions(administrator=True)
@_ci.command(pass_context=True, name="list")
async def ci_list(self, ctx):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
except Exception as e: self.cursor.execute("""SELECT id, username FROM users""")
await ctx.send(f"{ctx.author.mention}, je ne peux pas t'envoyer de message privé :(. Penses à autoriser les messages privés provenant des membres du serveur pour que je puisse te donner ta clef d'édition") rows = self.cursor.fetchall()
msg = ""
try:
for row in rows:
row_id = row[0]
row_name = row[1].encode('utf-8')
msg += f"{str(row_id)} : {str(row_name)} \n"
post = requests.post("https://hastebin.com/documents", data=msg)
await ctx.send(f"{ctx.author.mention} liste posté avec succès sur :\nhttps://hastebin.com/{post.json()['key']}.txt")
"""--------------------------------------------------------------------------------------------------------------------------""" with open('ci_list.txt', 'w', encoding='utf-8') as fp:
for row in rows:
@checks.has_permissions(administrator=True) row_id = row[0]
@_ci.command(pass_context=True, name="list") row_name = row[1]
async def ci_list(self, ctx):
self.conn = db.connect_to_db(self)
self.cursor = self.conn.cursor()
self.cursor.execute("""SELECT id, username FROM users""") fp.write(f"{str(row_id)} : {str(row_name)} \n")
rows = self.cursor.fetchall()
msg = ""
try:
for row in rows:
row_id = row[0]
row_name = row[1].encode('utf-8')
msg += f"{str(row_id)} : {str(row_name)} \n"
post = requests.post("https://hastebin.com/documents", data=msg)
await ctx.send(f"{ctx.author.mention} liste posté avec succès sur :\nhttps://hastebin.com/{post.json()['key']}.txt")
with open('ci_list.txt', 'w', encoding='utf-8') as fp: except Exception as e:
for row in rows: await ctx.send(f':sob: Une erreur est survenue : \n {type(e).__name__}: {e}')
row_id = row[0]
row_name = row[1]
fp.write(f"{str(row_id)} : {str(row_name)} \n")
except Exception as e:
await ctx.send(f':sob: Une erreur est survenue : \n {type(e).__name__}: {e}')
def setup(bot): def setup(bot):
bot.add_cog(Identity(bot)) bot.add_cog(Identity(bot))

View file

@ -4,107 +4,113 @@ from .utils import checks
from .utils.paginator import HelpPaginator from .utils.paginator import HelpPaginator
class CogManager: class CogManager(commands.Cog):
"""Gestionnaire des cogs""" """Gestionnaire des cogs"""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.help = discord.Embed(title='Tuxbot - Commandes cogs', description="Tuxbot - Commandes cogs\n"
"-> .cogs <load/unload/reload/info> *{cog}* : <load/unload/reload/info> *{cog}*\n"
"-> .cogs <list> : donne la liste de tous les cogs\n"
"-> .cogs <null/!(load/unload/reload)>: affiche cette aide", colour=0x89C4F9)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@checks.has_permissions(administrator=True) @checks.has_permissions(administrator=True)
@commands.group(name="cogs", no_pm=True, pass_context=True, case_insensitive=True) @commands.group(name="cogs", no_pm=True, pass_context=True,
async def _cogs(self, ctx): case_insensitive=True)
"""show help about 'cogs' command""" async def _cogs(self, ctx):
"""show help about 'cogs' command"""
if ctx.invoked_subcommand is None: if ctx.invoked_subcommand is None:
text = "Tuxbot - Commandes cogs\n-> .cogs <load/unload/reload/info> *{cog}* : <load/unload/reload/info> *{cog}*\n-> .cogs <null/!(load/unload/reload)>: affiche cette aide" await ctx.send(embed=self.help)
em = discord.Embed(title='Tuxbot - Commandes cogs', description=text, colour=0x89C4F9)
await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@_cogs.command(name="load", pass_context=True) @_cogs.command(name="load", pass_context=True)
async def cogs_load(self, ctx, cog: str = ""): async def cogs_load(self, ctx, cog: str = ""):
"""load a cog""" """load a cog"""
if cog != "": if cog != "":
try: try:
self.bot.load_extension(cog) self.bot.load_extension(cog)
await ctx.send('\N{OK HAND SIGN}') await ctx.send('\N{OK HAND SIGN}')
print("cog : " + str(cog) + " chargé") print("cog : " + str(cog) + " chargé")
except Exception as e: except Exception as e:
await ctx.send('\N{PISTOL}') await ctx.send('\N{PISTOL}')
await ctx.send(f'{type(e).__name__}: {e}') await ctx.send(f'{type(e).__name__}: {e}')
else: else:
text = "Tuxbot - Commandes cogs\n-> .cogs <load/unload/reload/info> *{cog}* : <load/unload/reload/info> *{cog}*\n-> .cogs <null/!(load/unload/reload)>: affiche cette aide" await ctx.send(embed=self.help)
em = discord.Embed(title='Tuxbot - Commandes cogs', description=text, colour=0x89C4F9)
await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@_cogs.command(name="unload", pass_context=True) @_cogs.command(name="unload", pass_context=True)
async def cogs_unload(self, ctx, cog: str = ""): async def cogs_unload(self, ctx, cog: str = ""):
"""unload a cog""" """unload a cog"""
if cog != "": if cog != "":
try: try:
self.bot.unload_extension(cog) self.bot.unload_extension(cog)
await ctx.send('\N{OK HAND SIGN}') await ctx.send('\N{OK HAND SIGN}')
print("cog : " + str(cog) + " déchargé") print("cog : " + str(cog) + " déchargé")
except Exception as e: except Exception as e:
await ctx.send('\N{PISTOL}') await ctx.send('\N{PISTOL}')
await ctx.send(f'{type(e).__name__}: {e}') await ctx.send(f'{type(e).__name__}: {e}')
else: else:
text = "Tuxbot - Commandes cogs\n-> .cogs <load/unload/reload/info> *{cog}* : <load/unload/reload/info> *{cog}*\n-> .cogs <null/!(load/unload/reload)>: affiche cette aide" await ctx.send(embed=self.help)
em = discord.Embed(title='Tuxbot - Commandes cogs', description=text, colour=0x89C4F9)
await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@_cogs.command(name="reload", pass_context=True) @_cogs.command(name="reload", pass_context=True)
async def cogs_reload(self, ctx, cog: str = ""): async def cogs_reload(self, ctx, cog: str = ""):
"""reload a cog""" """reload a cog"""
if cog != "": if cog != "":
try: try:
self.bot.unload_extension(cog) self.bot.unload_extension(cog)
self.bot.load_extension(cog) self.bot.load_extension(cog)
await ctx.send('\N{OK HAND SIGN}') await ctx.send('\N{OK HAND SIGN}')
print("cog : " + str(cog) + " rechargé") print("cog : " + str(cog) + " rechargé")
except Exception as e: except Exception as e:
await ctx.send('\N{PISTOL}') await ctx.send('\N{PISTOL}')
await ctx.send(f'{type(e).__name__}: {e}') await ctx.send(f'{type(e).__name__}: {e}')
else: else:
text = "Tuxbot - Commandes cogs\n-> .cogs <load/unload/reload/info> *{cog}* : <load/unload/reload/info> *{cog}*\n-> .cogs <null/!(load/unload/reload)>: affiche cette aide" await ctx.send(embed=self.help)
em = discord.Embed(title='Tuxbot - Commandes cogs', description=text, colour=0x89C4F9)
await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@_cogs.command(name="info", pass_context=True) @_cogs.command(name="info", pass_context=True)
async def cogs_info(self, ctx, cog: str = ""): async def cogs_info(self, ctx, cog: str = ""):
"""show info about a cog""" """show info about a cog"""
if cog != "": if cog != "":
try: try:
entity = self.bot.get_cog(cog) entity = self.bot.get_cog(cog)
if entity is None: if entity is None:
clean = cog.replace('@', '@\u200b') clean = cog.replace('@', '@\u200b')
await ctx.send(f'Command or category "{clean}" not found.') await ctx.send(f'Command or category "{clean}" not found.')
else: else:
p = await HelpPaginator.from_cog(ctx, entity) p = await HelpPaginator.from_cog(ctx, entity)
await p.paginate() await p.paginate()
except Exception as e:
await ctx.send('\N{PISTOL}')
await ctx.send(f'{type(e).__name__}: {e}')
else:
await ctx.send(embed=self.help)
except Exception as e: """---------------------------------------------------------------------"""
await ctx.send('\N{PISTOL}')
await ctx.send(f'{type(e).__name__}: {e}') @_cogs.command(name="list", pass_context=True)
else: async def cogs_list(self, ctx):
text = "Tuxbot - Commandes cogs\n-> .cogs <load/unload/reload/info> *{cog}* : <load/unload/reload/info> *{cog}*\n-> .cogs <null/!(load/unload/reload)>: affiche cette aide" """list all cogs"""
em = discord.Embed(title='Tuxbot - Commandes cogs', description=text, colour=0x89C4F9)
await ctx.send(embed=em) cogs = ""
for cog in self.bot.cogs:
cogs += f"{cog} *`({self.bot.cogs[cog].__module__})`*:" \
f" {len(self.bot.get_cog_commands(cog))} commandes\n"
await ctx.send(cogs)
def setup(bot): def setup(bot):
bot.add_cog(CogManager(bot)) bot.add_cog(CogManager(bot))

View file

@ -1,52 +1,60 @@
from discord.ext import commands from discord.ext import commands
import discord
import asyncio
import discord
import re import re
class FilterMessages: class FilterMessages(commands.Cog):
"""Flitre des messages""" """Flitre des messages"""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
async def on_message(self, message): @commands.Cog.listener()
no_pub_guild = [280805240977227776, 303633056944881686, 274247231534792704] async def on_message(self, message):
lien_channel = [280805783795662848, 508794201509593088] no_pub_guild = [280805240977227776, 303633056944881686,
sondage_channel = [394146769107419146, 477147964393914388] 274247231534792704]
lien_channel = [280805783795662848, 508794201509593088,
516017286948061204]
sondage_channel = [394146769107419146, 477147964393914388]
if message.author.bot \ if message.author.bot \
or str(message.author.id) in self.bot.config.authorized_id \ or str(message.author.id) in self.bot.config.authorized_id \
or message.channel.permissions_for(message.author).administrator is True: or message.channel.permissions_for(message.author).administrator is True:
return return
discord_invite_regex = re.compile(r"(discord\.(gg|io|me|li)|discordapp\.com\/invite)\/[0-9A-Za-z]*", re.IGNORECASE) discord_invite_regex = re.compile(r"(discord\.(gg|io|me|li)|discordapp\.com\/invite)\/[0-9A-Za-z]*", re.IGNORECASE)
invalid_link_regex = re.compile(r"^(\[[^\]]+\]|<\:[a-z0-9]+\:[0-9]+>) .+ https?:\/\/\S*$", re.IGNORECASE) invalid_link_regex = re.compile(r"^(\[[^\]]+\]|<\:[a-z0-9]+\:[0-9]+>) .+ https?:\/\/\S*$", re.IGNORECASE)
try: try:
if message.guild.id in no_pub_guild: ## discord invitation send by a non-admin and a non-authorized_id if message.guild.id in no_pub_guild:
if isinstance(discord_invite_regex.search(message.content), re.Match): if isinstance(discord_invite_regex.search(message.content), re.Match):
author = self.bot.get_user(message.author.id) author = self.bot.get_user(message.author.id)
await message.delete() await message.delete()
await author.send("La pub pour les serveurs discord n'est pas autorisée ici") await author.send("La pub pour les serveurs discord n'est pas autorisée ici")
if message.channel.id in lien_channel \ if message.channel.id in lien_channel \
and not isinstance(invalid_link_regex.search(message.content), re.Match): ## link send without pattern and not isinstance(invalid_link_regex.search(message.content), re.Match):
author = self.bot.get_user(message.author.id) author = self.bot.get_user(message.author.id)
await message.delete() await message.delete()
await author.send("Votre message `" + content + "` a été supprimé du channel `liens` car il ne respecte pas la structure définie. Pour partager un lien veuillez suivre la structure suivante : ` [Sujet] Descirption http(s)://....`") await author.send(f"Votre message `{message.content}` a été "
await author.send("Si vous voulez commenter ou discuter à propos d'un lien, veuillez le faire dans le channel `#discussion-des-liens`.") f"supprimé du channel `liens` ou `projets` "
f"car il ne respecte pas la structure "
f"définie. Pour partager un lien veuillez "
f"suivre la structure suivante :"
f" ` [Sujet] Descirption http(s)://....`")
await author.send("Si vous voulez commenter ou discuter à "
"propos d'un lien ou d'un projet, veuillez "
"le faire dans le channel"
" `#discussion-des-liens` ou"
" `#discussion-projets`.")
if message.channel.id in sondage_channel: ## a non-sondage send by a non-admin if message.channel.id in sondage_channel:
prefix_lenght = len(await self.bot.get_prefix(message)) prefix_lenght = len(await self.bot.get_prefix(message))
command = (message.content.split()[0])[prefix_lenght:] command = (message.content.split()[0])[prefix_lenght:]
if command != "sondage": if command != "sondage":
await message.delete() await message.delete()
except AttributeError: except AttributeError:
pass pass
def setup(bot): def setup(bot):
bot.add_cog(FilterMessages(bot)) bot.add_cog(FilterMessages(bot))

View file

@ -7,182 +7,185 @@ import random
import requests import requests
class Funs: class Funs(commands.Cog):
"""Commandes funs.""" """Commandes funs."""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command() @commands.command()
async def avatar(self, ctx, user: discord.Member = None): async def avatar(self, ctx, user: discord.Member = None):
"""Récuperer l'avatar de ...""" """Récuperer l'avatar de ..."""
if user == None: if user is None:
user = ctx.message.author user = ctx.message.author
embed = discord.Embed(title="Avatar de : " + user.name, embed = discord.Embed(title="Avatar de : " + user.name,
url=user.avatar_url_as(format="png"), url=user.avatar_url_as(format="png"),
description=f"[Voir en plus grand]({user.avatar_url_as(format='png')})") description=f"[Voir en plus grand]"
embed.set_thumbnail(url=user.avatar_url_as(format="png")) f"({user.avatar_url_as(format='png')})")
await ctx.send(embed=embed) embed.set_thumbnail(url=user.user.avatar_url_as(format="png"))
await ctx.send(embed=embed)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command(pass_context=True) @commands.command(pass_context=True)
async def poke(self, ctx, user: discord.Member): async def poke(self, ctx, user: discord.Member):
"""Poke quelqu'un""" """Poke quelqu'un"""
await ctx.send(":clap: Hey {0} tu t'es fait poker par {1} !".format( await ctx.send(f":clap: Hey {user.mention} tu t'es fait poker par"
user.mention, ctx.message.author.name)) f" {ctx.message.author} !")
await ctx.message.delete() await ctx.message.delete()
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command()
async def btcprice(self, ctx):
"""Le prix du BTC"""
loading = await ctx.send("_réfléchis..._")
try:
url = urllib.request.urlopen("https://blockchain.info/fr/ticker")
btc = json.loads(url.read().decode())
except KeyError:
btc = 1
if btc == 1: @commands.command()
await loading.edit(content="Impossible d'accèder à l'API blockchain.info, " async def btcprice(self, ctx):
"veuillez réessayer ultérieurment ! :c") """Le prix du BTC"""
else: loading = await ctx.send("_réfléchis..._")
frbtc = str(btc["EUR"]["last"]).replace(".", ",") try:
usbtc = str(btc["USD"]["last"]).replace(".", ",") url = urllib.request.urlopen("https://blockchain.info/fr/ticker")
await loading.edit(content="Un bitcoin est égal à : {0}$US soit {1}€.".format(usbtc, frbtc)) btc = json.loads(url.read().decode())
except KeyError:
btc = 1
"""--------------------------------------------------------------------------------------------------------------------------""" if btc == 1:
await loading.edit(content="Impossible d'accèder à l'API"
" blockchain.info, veuillez réessayer"
" ultérieurment ! :c")
else:
frbtc = str(btc["EUR"]["last"]).replace(".", ",")
usbtc = str(btc["USD"]["last"]).replace(".", ",")
await loading.edit(content=f"Un bitcoin est égal à :"
f" {usbtc}$US soit {frbtc}€.")
@commands.command() """---------------------------------------------------------------------"""
async def joke(self, ctx, number:str = 0):
"""Print a random joke in a json file"""
with open('texts/jokes.json') as js:
jk = json.load(js)
try: @commands.command()
if int(number) <= 15 and int(number) > 0: async def joke(self, ctx, number: str = 0):
clef = str(number) """Print a random joke in a json file"""
else: with open('texts/jokes.json') as js:
clef = str(random.randint(1,15)) jk = json.load(js)
except:
clef = str(random.randint(1,15))
try:
if 15 >= int(number) > 0:
clef = str(number)
else:
clef = str(random.randint(1, 15))
except Exception:
clef = str(random.randint(1, 15))
joke = jk["{}".format(clef)] joke = jk["{}".format(clef)]
embed = discord.Embed(title="Blague _{}_ : ".format(clef), description=joke['content'], colour=0x03C9A9) embed = discord.Embed(title="Blague _{}_ : ".format(clef),
embed.set_footer(text="Par " + joke['author']) description=joke['content'], colour=0x03C9A9)
embed.set_thumbnail(url='https://outout.tech/tuxbot/blobjoy.png') embed.set_footer(text="Par " + joke['author'])
await ctx.send(embed=embed) embed.set_thumbnail(url='https://outout.tech/tuxbot/blobjoy.png')
await ctx.send(embed=embed)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command() @commands.command()
async def ethylotest(self, ctx): async def ethylotest(self, ctx):
"""Ethylotest simulator 2018""" """Ethylotest simulator 2018"""
results_poulet = ["Désolé mais mon ethylotest est sous Windows Vista, " results_poulet = ["Désolé mais mon ethylotest est sous Windows Vista, "
"merci de patienter...", "merci de patienter...",
"_(ethylotest)_ : Une erreur est survenue. Windows " "_(ethylotest)_ : Une erreur est survenue. Windows "
"cherche une solution à se problème.", "cherche une solution à se problème.",
"Mais j'l'ai foutu où ce p\\*\\*\\* d'ethylotest de m\\*\\*\\* " "Mais j'l'ai foutu où ce p\\*\\*\\* d'ethylotest de m\\*\\*\\* "
"bordel fait ch\\*\\*\\*", "bordel fait ch\\*\\*\\*",
"C'est pas possible z'avez cassé l'ethylotest !"] "C'est pas possible z'avez cassé l'ethylotest !"]
results_client = ["D'accord, il n'y a pas de problème à cela je suis " results_client = ["D'accord, il n'y a pas de problème à cela je suis "
"complètement clean", "complètement clean",
"Bien sur si c'est votre devoir !", "Suce bi\\*e !", "Bien sur si c'est votre devoir !", "Suce bi\\*e !",
"J'ai l'air d'être bourré ?", "J'ai l'air d'être bourré ?",
"_laissez moi prendre un bonbon à la menthe..._"] "_laissez moi prendre un bonbon à la menthe..._"]
result_p = random.choice(results_poulet) result_p = random.choice(results_poulet)
result_c = random.choice(results_client) result_c = random.choice(results_client)
await ctx.send(":oncoming_police_car: Bonjour bonjour, contrôle " await ctx.send(":oncoming_police_car: Bonjour bonjour, contrôle "
"d'alcoolémie !") "d'alcoolémie !")
await asyncio.sleep(0.5) await asyncio.sleep(0.5)
await ctx.send(":man: " + result_c) await ctx.send(":man: " + result_c)
await asyncio.sleep(1) await asyncio.sleep(1)
await ctx.send(":police_car: " + result_p) await ctx.send(":police_car: " + result_p)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command() @commands.command()
async def coin(self, ctx): async def coin(self, ctx):
"""Coin flip simulator 2025""" """Coin flip simulator 2025"""
starts_msg = ["Je lance la pièce !", "C'est parti !", "C'est une pièce" starts_msg = ["Je lance la pièce !", "C'est parti !", "C'est une pièce"
" d'un cent faut" " d'un cent faut"
" pas la perdre", " pas la perdre",
"C'est une pièce d'un euro faut pas la perdre", "C'est une pièce d'un euro faut pas la perdre",
"Je lance !"] "Je lance !"]
results_coin = ["{0} pile", "{0} face", "{1} Heu c'est quoi pile c'est" results_coin = ["{0} pile", "{0} face", "{1} Heu c'est quoi pile c'est"
" quoi face enfaite ?", " quoi face enfaite ?",
"{1} Oh shit, je crois que je l'ai perdue", "{1} Oh shit, je crois que je l'ai perdue",
"{1} Et bim je te vol ta pièce !", "{1} Et bim je te vol ta pièce !",
"{0} Oh une erreur d'impression il n'y a ni pile ni" "{0} Oh une erreur d'impression il n'y a ni pile ni"
" face !"] " face !"]
start = random.choice(starts_msg) start = random.choice(starts_msg)
result = random.choice(results_coin) result = random.choice(results_coin)
await ctx.send(start) await ctx.send(start)
await asyncio.sleep(0.6) await asyncio.sleep(0.6)
await ctx.send(result.format(":moneybag: Et la pièce retombe sur ...", await ctx.send(result.format(":moneybag: Et la pièce retombe sur ...",
":robot:")) ":robot:"))
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command() @commands.command()
async def pokemon(self, ctx): async def pokemon(self, ctx):
"""Random pokemon fight""" """Random pokemon fight"""
with open('texts/pokemons.json') as js: with open('texts/pokemons.json') as js:
jk = json.load(js) jk = json.load(js)
poke1 = jk[random.randint(1, 150)] poke1 = jk[random.randint(1, 150)]
poke2 = jk[random.randint(1, 150)] poke2 = jk[random.randint(1, 150)]
try: try:
if poke1['MaxHP'] > poke2['MaxHP']: if poke1['MaxHP'] > poke2['MaxHP']:
winer = poke1 winer = poke1
else: else:
winer = poke2 winer = poke2
except KeyError: except KeyError:
winer = poke1 winer = poke1
await ctx.send(":flag_white: **Le combat commence !**") await ctx.send(":flag_white: **Le combat commence !**")
await asyncio.sleep(1) await asyncio.sleep(1)
await ctx.send(":loudspeaker: Les concurants sont {} contre {} ! Bonne" await ctx.send(":loudspeaker: Les concurants sont {} contre {} ! Bonne"
" chance à eux !".format(poke1["Name"], poke2["Name"])) " chance à eux !".format(poke1["Name"], poke2["Name"]))
await asyncio.sleep(0.5) await asyncio.sleep(0.5)
await ctx.send(":boom: {} commence et utilise {}".format( await ctx.send(":boom: {} commence et utilise {}".format(
poke1["Name"], poke1["Fast Attack(s)"][0]["Name"])) poke1["Name"], poke1["Fast Attack(s)"][0]["Name"]))
await asyncio.sleep(1) await asyncio.sleep(1)
await ctx.send(":dash: {} réplique avec {}".format( await ctx.send(":dash: {} réplique avec {}".format(
poke2["Name"], poke2["Fast Attack(s)"][0]["Name"])) poke2["Name"], poke2["Fast Attack(s)"][0]["Name"]))
await asyncio.sleep(1.2) await asyncio.sleep(1.2)
await ctx.send("_le combat continue de se dérouler..._") await ctx.send("_le combat continue de se dérouler..._")
await asyncio.sleep(1.5) await asyncio.sleep(1.5)
await ctx.send(":trophy: Le gagnant est **{}** !".format( await ctx.send(":trophy: Le gagnant est **{}** !".format(
winer["Name"])) winer["Name"]))
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command() @commands.command()
async def randomcat(self, ctx): async def randomcat(self, ctx):
"""Display a random cat""" """Display a random cat"""
r = requests.get('http://aws.random.cat/meow') r = requests.get('http://aws.random.cat/meow')
cat = str(r.json()['file']) cat = str(r.json()['file'])
embed = discord.Embed(title="Meow", embed = discord.Embed(title="Meow",
description="[Voir le chat plus grand]({})". description="[Voir le chat plus grand]({})".
format(cat), colour=0x03C9A9) format(cat), colour=0x03C9A9)
embed.set_thumbnail(url=cat) embed.set_thumbnail(url=cat)
embed.set_author(name="Random.cat", url='https://random.cat/') embed.set_author(name="Random.cat", url='https://random.cat/')
await ctx.send(embed=embed) await ctx.send(embed=embed)
def setup(bot): def setup(bot):
bot.add_cog(Funs(bot)) bot.add_cog(Funs(bot))

View file

@ -1,17 +1,19 @@
from discord.ext import commands import aiohttp
import datetime
import discord import discord
import imghdr
import os
import shutil
from PIL import Image from PIL import Image
from PIL import ImageOps from PIL import ImageOps
from discord.ext import commands
from .utils import checks
from .utils import db from .utils import db
from .utils.checks import get_user
from .utils.passport_generator import generate_passport from .utils.passport_generator import generate_passport
from .utils.checks import get_user, check_date
import asyncio, aiohttp, io, time, imghdr, os, shutil, json, textwrap, re, math, datetime
class Passport: class Passport(commands.Cog):
"""Commandes des passeports .""" """Commandes des passeports ."""
def __init__(self, bot): def __init__(self, bot):

View file

@ -1,127 +1,152 @@
from discord.ext import commands from discord.ext import commands
import discord import discord
class Role:
"""Commandes role."""
def __init__(self, bot): class Role(commands.Cog):
self.bot = bot """Commandes role."""
self.ARCH_ROLE = 393077257826205706 def __init__(self, bot):
self.DEBIAN_ROLE = 393077933209550859 self.bot = bot
self.RHEL_ROLE = 393078333245751296
self.ANDROID_ROLE = 393087862972612627
self.BSD_ROLE = 401791543708745738
@commands.group(name="role", no_pm=True, pass_context=True, case_insensitive=True) self.ARCH_ROLE = 393077257826205706
async def _role(self, ctx): self.DEBIAN_ROLE = 393077933209550859
"""Affiche l'aide sur la commande role""" self.RHEL_ROLE = 393078333245751296
if ctx.message.guild.id != 280805240977227776: self.ANDROID_ROLE = 393087862972612627
return self.BSD_ROLE = 401791543708745738
if ctx.invoked_subcommand is None: @commands.group(name="role", no_pm=True, pass_context=True,
text = open('texts/roles.md').read() case_insensitive=True)
em = discord.Embed(title='Gestionnaires de rôles', description=text,colour=0x89C4F9) async def _role(self, ctx):
await ctx.send(embed=em) """Affiche l'aide sur la commande role"""
if ctx.message.guild.id != 280805240977227776:
return
"""--------------------------------------------------------------------------------------------------------------------------""" if ctx.invoked_subcommand is None:
text = open('texts/roles.md').read()
em = discord.Embed(title='Gestionnaires de rôles',
description=text, colour=0x89C4F9)
await ctx.send(embed=em)
@_role.command(name="arch", aliases=["archlinux", "arch_linux"], pass_context=True) """---------------------------------------------------------------------"""
async def role_arch(self, ctx):
"""Ajoute/retire le role 'Arch user'"""
roles = ctx.message.author.roles
role_id = []
for role in roles:
role_id.append(role.id)
user = ctx.message.author @_role.command(name="arch", aliases=["archlinux", "arch_linux"],
if self.ARCH_ROLE in role_id: pass_context=True)
await user.remove_roles(discord.Object(id=self.ARCH_ROLE)) async def role_arch(self, ctx):
await ctx.send(ctx.message.author.mention + " > Pourquoi tu viens de supprimer Arch Linux, c'était trop compliqué pour toi ? <:sad:343723037331292170>") """Ajoute/retire le role 'Arch user'"""
else: roles = ctx.message.author.roles
await user.add_roles(discord.Object(id=self.ARCH_ROLE)) role_id = []
await ctx.send(ctx.message.author.mention + " > How un ArchLinuxien, c'est bon les ``yaourt`` ? <:hap:354275645574086656>") for role in roles:
role_id.append(role.id)
"""--------------------------------------------------------------------------------------------------------------------------""" user = ctx.message.author
if self.ARCH_ROLE in role_id:
await user.remove_roles(discord.Object(id=self.ARCH_ROLE))
await ctx.send(f"{ctx.message.author.mention} > Pourquoi tu viens "
f"de supprimer Arch Linux, c'était trop compliqué "
f"pour toi ? <:sad:343723037331292170>")
else:
await user.add_roles(discord.Object(id=self.ARCH_ROLE))
await ctx.send(f"{ctx.message.author.mention} > How un "
f"ArchLinuxien, c'est bon les ``yaourt`` ? "
f"<:hap:354275645574086656>")
@_role.command(name="debian", pass_context=True) """---------------------------------------------------------------------"""
async def role_debian(self, ctx):
"""Ajoute/retire le role 'debian user'"""
roles = ctx.message.author.roles
role_id = []
for role in roles:
role_id.append(role.id)
user = ctx.message.author @_role.command(name="debian", pass_context=True)
if self.DEBIAN_ROLE in role_id: async def role_debian(self, ctx):
await user.remove_roles(discord.Object(id=self.DEBIAN_ROLE)) """Ajoute/retire le role 'debian user'"""
await ctx.send(ctx.message.author.mention + " > Adieu ! Tu verras, APT te manquera ! ") roles = ctx.message.author.roles
else: role_id = []
await user.add_roles(discord.Object(id=self.DEBIAN_ROLE)) for role in roles:
await ctx.send(ctx.message.author.mention + " > Un utilisateur de Debian, encore et encore ! <:stuck_out_tongue:343723077412323339>") role_id.append(role.id)
"""--------------------------------------------------------------------------------------------------------------------------""" user = ctx.message.author
if self.DEBIAN_ROLE in role_id:
await user.remove_roles(discord.Object(id=self.DEBIAN_ROLE))
await ctx.send(f"{ctx.message.author.mention} > Adieu ! Tu verras, "
f"APT te manquera ! ")
else:
await user.add_roles(discord.Object(id=self.DEBIAN_ROLE))
await ctx.send(f"{ctx.message.author.mention} > Un utilisateur de "
f"Debian, encore et encore ! "
f"<:stuck_out_tongue:343723077412323339>")
@_role.command(name="rhel", pass_context=True) """---------------------------------------------------------------------"""
async def role_rhel(self, ctx):
"""Ajoute/retire le role 'rhel user'"""
roles = ctx.message.author.roles
role_id = []
for role in roles:
role_id.append(role.id)
user = ctx.message.author @_role.command(name="rhel", pass_context=True)
if self.RHEL_ROLE in role_id: async def role_rhel(self, ctx):
await user.remove_roles(discord.Object(id=self.RHEL_ROLE)) """Ajoute/retire le role 'rhel user'"""
await ctx.send(ctx.message.author.mention + " > Pourquoi tu t'en vas, il sont déjà assez seul là-bas <:sad:343723037331292170>") roles = ctx.message.author.roles
else: role_id = []
await user.add_roles(discord.Object(id=self.RHEL_ROLE)) for role in roles:
await ctx.send(ctx.message.author.mention + " > Mais, voila quelqu'un qui porte des chapeaux ! <:hap:354275645574086656>") role_id.append(role.id)
"""--------------------------------------------------------------------------------------------------------------------------""" user = ctx.message.author
if self.RHEL_ROLE in role_id:
await user.remove_roles(discord.Object(id=self.RHEL_ROLE))
await ctx.send(f"{ctx.message.author.mention} > Pourquoi tu t'en "
f"vas, il sont déjà assez seul là-bas "
f"<:sad:343723037331292170>")
else:
await user.add_roles(discord.Object(id=self.RHEL_ROLE))
await ctx.send(f"{ctx.message.author.mention} > Mais, voila "
f"quelqu'un qui porte des chapeaux ! "
f"<:hap:354275645574086656>")
@_role.command(name="android", pass_context=True) """---------------------------------------------------------------------"""
async def role_android(self, ctx):
"""Ajoute/retire le role 'android user'"""
roles = ctx.message.author.roles
role_id = []
for role in roles:
role_id.append(role.id)
user = ctx.message.author @_role.command(name="android", pass_context=True)
if self.ANDROID_ROLE in role_id: async def role_android(self, ctx):
await user.remove_roles(discord.Object(id=self.ANDROID_ROLE)) """Ajoute/retire le role 'android user'"""
await ctx.send(ctx.message.author.mention + " > How, me dit pas que tu as compris que les Android's allaient exterminer le monde ? <:trollface:375327667160875008>") roles = ctx.message.author.roles
else: role_id = []
await user.add_roles(discord.Object(id=self.ANDROID_ROLE)) for role in roles:
await ctx.send(ctx.message.author.mention + " > Hey, un utilisateur d'Android, prêt à continuer l'extermination de WP et iOS ? <:stuck_out_tongue:343723077412323339>") role_id.append(role.id)
"""--------------------------------------------------------------------------------------------------------------------------""" user = ctx.message.author
if self.ANDROID_ROLE in role_id:
await user.remove_roles(discord.Object(id=self.ANDROID_ROLE))
await ctx.send(f"{ctx.message.author.mention} >How, me dit pas "
f"que tu as compris que les Android's allaient "
f"exterminer le monde ? "
f"<:trollface:375327667160875008>")
else:
await user.add_roles(discord.Object(id=self.ANDROID_ROLE))
await ctx.send(f"{ctx.message.author.mention} > Hey, un utilisateur"
f" d'Android, prêt à continuer l'extermination de "
f"WP et iOS ? "
f"<:stuck_out_tongue:343723077412323339>")
@_role.command(name="bsd", pass_context=True) """---------------------------------------------------------------------"""
async def role_bsd(self, ctx):
"""Ajoute/retire le role 'BSD user'"""
roles = ctx.message.author.roles
role_id = []
for role in roles:
role_id.append(role.id)
user = ctx.message.author @_role.command(name="bsd", pass_context=True)
if self.BSD_ROLE in role_id: async def role_bsd(self, ctx):
await user.remove_roles(discord.Object(id=self.BSD_ROLE)) """Ajoute/retire le role 'BSD user'"""
await ctx.send(ctx.message.author.mention + " > Ohhhh fait gaffe ou le démon va te piquer") roles = ctx.message.author.roles
else: role_id = []
await user.add_roles(discord.Object(id=self.BSD_ROLE)) for role in roles:
await ctx.send(ctx.message.author.mention + " > Quelqu'un sous BSD ! Au moins il a pas besoin de mettre GNU devant son OS à chaque fois :d") role_id.append(role.id)
"""--------------------------------------------------------------------------------------------------------------------------""" user = ctx.message.author
if self.BSD_ROLE in role_id:
await user.remove_roles(discord.Object(id=self.BSD_ROLE))
await ctx.send(f"{ctx.message.author.mention} > Ohhhh fait gaffe "
f"ou le démon va te piquer")
else:
await user.add_roles(discord.Object(id=self.BSD_ROLE))
await ctx.send(f"{ctx.message.author.mention} > Quelqu'un sous "
f"BSD ! Au moins il a pas besoin de mettre GNU "
f"devant son OS à chaque fois :d")
@_role.command(name="staff", pass_context=True, hidden=True) """---------------------------------------------------------------------"""
async def role_staff(self, ctx):
"""Easter egg""" @_role.command(name="staff", pass_context=True, hidden=True)
user = ctx.message.author async def role_staff(self, ctx):
await ctx.send(ctx.message.author.mention + " > Vous n'avez pas le rôle staff, tu crois quoi :joy:") """Easter egg"""
await ctx.send(f"{ctx.message.author.mention} > Vous n'avez pas "
f"le rôle staff, tu crois quoi :joy:")
def setup(bot): def setup(bot):
bot.add_cog(Role(bot)) bot.add_cog(Role(bot))

View file

@ -4,165 +4,154 @@ import asyncio
import urllib.request import urllib.request
import wikipedia import wikipedia
wikipedia.set_lang("fr")
class Search:
"""Commandes de WWW."""
def __init__(self, bot): class Search(commands.Cog):
self.bot = bot """Commandes de WWW."""
@commands.group(name="search", no_pm=True, pass_context=True) def __init__(self, bot):
async def _search(self, ctx): self.bot = bot
"""Rechercher sur le world wide web"""
if ctx.invoked_subcommand is None:
text = open('texts/search.md').read()
em = discord.Embed(title='Commandes de search TuxBot',
description=text,
colour=0x89C4F9)
await ctx.send(embed=em)
@_search.command(pass_context=True, name="docubuntu") @commands.group(name="search", no_pm=True, pass_context=True)
async def search_docubuntu(self, ctx, args): async def _search(self, ctx):
attends = await ctx.send("_Je te cherche ça {} !_".format( """Rechercher sur le world wide web"""
ctx.author.mention)) if ctx.invoked_subcommand is None:
html = urllib.request.urlopen("https://doc.ubuntu-fr.org/" + text = open('texts/search.md').read()
args).read() em = discord.Embed(title='Commandes de search TuxBot',
if "avez suivi un lien" in str(html): description=text,
await attends.edit(content=":sob: Nooooon ! Cette page n'existe " colour=0x89C4F9)
"pas, mais tu peux toujours la créer : " await ctx.send(embed=em)
"https://doc.ubuntu-fr.org/" + args)
else:
await attends.delete()
embed = discord.Embed(description="Voila j'ai trouvé ! Voici la "
"page ramenant à votre recherche,"
" toujours aussi bien rédigée "
":wink: : https://doc.ubuntu-fr."
"org/" + args,
url='http://doc.ubuntu-fr.org/')
embed.set_author(name="DocUbuntu-Fr",
url='http://doc.ubuntu-fr.org/',
icon_url='https://tuxbot.outout.xyz/data/ubuntu.png')
embed.set_thumbnail(url='https://tuxbot.outout.xyz/data/ubuntu.png')
embed.set_footer(text="Merci à ceux qui ont pris le temps d'écrire "
"cette documentation")
await ctx.send(embed=embed)
@_search.command(pass_context=True, name="docarch") @_search.command(pass_context=True, name="docubuntu")
async def search_docarch(self, ctx, args): async def search_docubuntu(self, ctx, args):
attends = await ctx.send("_Je te cherche ça {} !_".format( attends = await ctx.send("_Je te cherche ça {} !_".format(
ctx.author.mention)) ctx.message.author.mention))
html = urllib.request.urlopen("https://wiki.archlinux.org/index.php/" + html = urllib.request.urlopen("https://doc.ubuntu-fr.org/" +
args).read() args).read()
if "There is currently no text in this page" in str(html): if "avez suivi un lien" in str(html):
await attends.edit(content=":sob: Nooooon ! Cette page n'existe " await attends.edit(content=":sob: Nooooon ! Cette page n'existe "
"pas.") "pas, mais tu peux toujours la créer : "
else: "https://doc.ubuntu-fr.org/" + args)
await attends.delete() else:
embed = discord.Embed(description="Voila j'ai trouvé ! Voici la " await attends.delete()
"page ramenant à votre recherche," embed = discord.Embed(description="Voila j'ai trouvé ! Voici la "
" toujours aussi bien rédigée " "page ramenant à votre recherche,"
":wink: : https://wiki.archlinux." " toujours aussi bien rédigée "
"org/index.php/" + args, ":wink: : https://doc.ubuntu-fr."
url='https://wiki.archlinux.org/index.php/') "org/" + args,
embed.set_author(name="Doc ArchLinux", url='http://doc.ubuntu-fr.org/')
url='https://wiki.archlinux.org/index.php/', embed.set_author(name="DocUbuntu-Fr",
icon_url='https://tuxbot.outout.xyz/data/arch.png') url='http://doc.ubuntu-fr.org/',
embed.set_thumbnail(url='https://tuxbot.outout.xyz/data/arch.png') icon_url='https://tuxbot.outout.xyz/data/ubuntu.png')
embed.set_footer(text="Merci à ceux qui ont pris le temps d'écrire " embed.set_thumbnail(url='https://tuxbot.outout.xyz/data/ubuntu.png')
"cette documentation") embed.set_footer(text="Merci à ceux qui ont pris le temps d'écrire "
await ctx.send(embed=embed) "cette documentation")
await ctx.send(embed=embed)
@_search.command(pass_context=True, name="wikipedia") @_search.command(pass_context=True, name="docarch")
async def search_wikipedia(self, ctx: commands.Context, *, args): async def search_docarch(self, ctx, args):
"""Fait une recherche sur wikipd""" attends = await ctx.send("_Je te cherche ça {} !_".format(
ctx.message.author.mention))
html = urllib.request.urlopen("https://wiki.archlinux.org/index.php/" +
args).read()
if "There is currently no text in this page" in str(html):
await attends.edit(content=":sob: Nooooon ! Cette page n'existe "
"pas.")
else:
await attends.delete()
embed = discord.Embed(description="Voila j'ai trouvé ! Voici la "
"page ramenant à votre recherche,"
" toujours aussi bien rédigée "
":wink: : https://wiki.archlinux."
"org/index.php/" + args,
url='https://wiki.archlinux.org/index.php/')
embed.set_author(name="Doc ArchLinux",
url='https://wiki.archlinux.org/index.php/',
icon_url='https://tuxbot.outout.xyz/data/arch.png')
embed.set_thumbnail(url='https://tuxbot.outout.xyz/data/arch.png')
embed.set_footer(text="Merci à ceux qui ont pris le temps d'écrire "
"cette documentation")
await ctx.send(embed=embed)
params = args.split(" ") @_search.command(pass_context=True, name="wikipedia")
async def search_wikipedia(self, ctx: commands.Context, args):
"""Fait une recherche sur wikipd"""
lang = [x for x in params if x.startswith("lang=")] wait = await ctx.send("_Je cherche..._")
if lang: results = wikipedia.search(args)
lang = lang[0] nbmr = 0
params.remove(lang) mmssgg = ""
lang = lang.replace("lang=", "")
wikipedia.set_lang(lang)
else:
wikipedia.set_lang("fr")
params = ' '.join(params) for value in results:
nbmr = nbmr + 1
mmssgg = mmssgg + "**{}**: {} \n".format(str(nbmr), value)
wait = await ctx.send("_Je cherche..._") em = discord.Embed(title='Résultats de : ' + args,
results = wikipedia.search(params) description = mmssgg,
nbmr = 0 colour=0x4ECDC4)
mmssgg = "" em.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/"
"2/26/Paullusmagnus-logo_%28large%29.png")
await wait.delete()
for value in results: sending = ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣", "🔟"]
nbmr = nbmr + 1
mmssgg = mmssgg + "**{}**: {} \n".format(str(nbmr), value)
em = discord.Embed(title='Résultats de : ' + params, def check(reaction, user):
description = mmssgg, return user == ctx.author and reaction.emoji in sending and \
colour=0x4ECDC4) reaction.message.id == msg.id
em.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/"
"2/26/Paullusmagnus-logo_%28large%29.png")
await wait.delete()
sending = ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣", "🔟"] async def waiter(future: asyncio.Future):
reaction, user = await self.bot.wait_for('reaction_add',
check=check)
future.set_result(reaction.emoji)
def check(reaction, user): emoji = asyncio.Future()
return user == ctx.author and reaction.emoji in sending and \ self.bot.loop.create_task(waiter(emoji))
reaction.message.id == msg.id
async def waiter(future: asyncio.Future): msg = await ctx.send(embed=em)
reaction, user = await self.bot.wait_for('reaction_add', for e in sending:
check=check) await msg.add_reaction(e)
future.set_result(reaction.emoji) if emoji.done():
break
emoji = asyncio.Future() while not emoji.done():
self.bot.loop.create_task(waiter(emoji)) await asyncio.sleep(0.1)
msg = await ctx.send(embed=em) page = int(sending.index(emoji.result()))
for e in sending:
await msg.add_reaction(e)
if emoji.done():
break
while not emoji.done(): args_ = results[page]
await asyncio.sleep(0.1)
sPage = int(sending.index(emoji.result())) try:
await msg.delete()
await ctx.trigger_typing()
wait = await ctx.send(ctx.message.author.mention +
" ah ok sympa cette recherche, je l'effectue de suite !")
wp = wikipedia.page(args_)
wp_contenu = wp.summary[:200] + "..."
em = discord.Embed(title='Wikipedia : ' + wp.title,
description = "{} \n_Lien_ : {} ".format(
wp_contenu, wp.url),
colour=0x9B59B6)
em.set_author(name="Wikipedia",
url='http://wikipedia.org',
icon_url='https://upload.wikimedia.org/wikipedia/'
'commons/2/26/Paullusmagnus-logo_%28large'
'%29.png')
em.set_thumbnail(url = "https://upload.wikimedia.org/wikipedia/"
"commons/2/26/Paullusmagnus-logo_%28large"
"%29.png")
em.set_footer(text="Merci à eux de nous fournir une encyclopédie "
"libre !")
await wait.delete()
await ctx.send(embed=em)
args_ = results[sPage] except wikipedia.exceptions.PageError:
# TODO : A virer dans l'event on_error
try: await ctx.send(":open_mouth: Une **erreur interne** est survenue,"
await msg.delete() " si cela ce reproduit contactez votre"
await ctx.trigger_typing() " administrateur ou faites une Issue sur"
wait = await ctx.send(ctx.author.mention + " ``gitea`` !")
" ah ok sympa cette recherche, je l'effectue de suite !")
wp = wikipedia.page(args_)
wp_contenu = wp.summary[:200] + "..."
em = discord.Embed(title='Wikipedia : ' + wp.title,
description = "{} \n_Lien_ : {} ".format(
wp_contenu, wp.url),
colour=0x9B59B6)
em.set_author(name="Wikipedia",
url='http://wikipedia.org',
icon_url='https://upload.wikimedia.org/wikipedia/'
'commons/2/26/Paullusmagnus-logo_%28large'
'%29.png')
em.set_thumbnail(url = "https://upload.wikimedia.org/wikipedia/"
"commons/2/26/Paullusmagnus-logo_%28large"
"%29.png")
em.set_footer(text="Merci à eux de nous fournir une encyclopédie "
"libre !")
await wait.delete()
await ctx.send(embed=em)
except wikipedia.exceptions.PageError:
# TODO : A virer dans l'event on_error
await ctx.send(":open_mouth: Une **erreur interne** est survenue,"
" si cela ce reproduit contactez votre"
" administrateur ou faites une Issue sur"
" ``github`` !")
def setup(bot): def setup(bot):
bot.add_cog(Search(bot)) bot.add_cog(Search(bot))

View file

@ -1,80 +1,105 @@
from discord.ext import commands import datetime
import socket
import discord import discord
from discord.ext import commands
import datetime, socket
class SendLogs: class SendLogs(commands.Cog):
"""Send logs to a specific channel""" """Send logs to a specific channel"""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.log_channel = None self.log_channel = None
self.main_server_id = int(self.bot.config.main_server_id) self.main_server_id = int(self.bot.config.main_server_id)
async def on_resumed(self): @commands.Cog.listener()
em = discord.Embed(title="Et hop je me reconnecte à l'api 😃", colour=0x5cb85c) async def on_resumed(self):
em.timestamp = datetime.datetime.utcnow() em = discord.Embed(title="Et hop je me reconnecte à l'api 😃",
await self.log_channel.send(embed=em) colour=0x5cb85c)
em.timestamp = datetime.datetime.utcnow()
await self.log_channel.send(embed=em)
async def on_ready(self): @commands.Cog.listener()
self.log_channel = self.bot.get_channel(int(self.bot.config.log_channel_id)) async def on_ready(self):
em = discord.Embed(title="Je suis opérationnel 😃", description=f"*Instance lancée sur {socket.gethostname()}*", colour=0x5cb85c) self.log_channel = self.bot.get_channel(int(self.bot.config.log_channel_id))
em.timestamp = datetime.datetime.utcnow() em = discord.Embed(title="Je suis opérationnel 😃",
await self.log_channel.send(embed=em) description=f"*Instance lancée sur "
f"{socket.gethostname()}*", colour=0x5cb85c)
em.timestamp = datetime.datetime.utcnow()
await self.log_channel.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
async def on_guild_join(self, guild: discord.Guild): @commands.Cog.listener()
em = discord.Embed(title=f"On m'a ajouté à : {str(guild.name)} 😃", colour=0x51A351) async def on_guild_join(self, guild: discord.Guild):
em.timestamp = datetime.datetime.utcnow() em = discord.Embed(title=f"On m'a ajouté à : {str(guild.name)} 😃",
await self.log_channel.send(embed=em) colour=0x51A351)
em.timestamp = datetime.datetime.utcnow()
await self.log_channel.send(embed=em)
async def on_guild_remove(self, guild: discord.Guild): @commands.Cog.listener()
em = discord.Embed(title=f"On m'a viré de : {str(guild.name)} 😦", colour=0xBD362F) async def on_guild_remove(self, guild: discord.Guild):
em.timestamp = datetime.datetime.utcnow() em = discord.Embed(title=f"On m'a viré de : {str(guild.name)} 😦",
await self.log_channel.send(embed=em) colour=0xBD362F)
em.timestamp = datetime.datetime.utcnow()
await self.log_channel.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
async def on_member_join(self, member): @commands.Cog.listener()
if member.guild.id == self.main_server_id: async def on_member_join(self, member):
em = discord.Embed(title=f"{str(member)} *`({str(member.id)})`* nous a rejoint 😃", colour=0x51A351) if member.guild.id == self.main_server_id:
em.set_footer(text="Compte crée le " + str(member.created_at), ) em = discord.Embed(title=f"{str(member)} *`({str(member.id)})`* "
em.timestamp = datetime.datetime.utcnow() f"nous a rejoint 😃", colour=0x51A351)
await self.log_channel.send(embed=em) em.set_footer(text=f"Compte crée le {member.created_at}")
em.timestamp = datetime.datetime.utcnow()
await self.log_channel.send(embed=em)
async def on_member_remove(self, member): @commands.Cog.listener()
if member.guild.id == self.main_server_id: async def on_member_remove(self, member):
em = discord.Embed(title=f"{str(member)} *`({str(member.id)})`* nous a quitter 😦", colour=0xBD362F) if member.guild.id == self.main_server_id:
em.timestamp = datetime.datetime.utcnow() em = discord.Embed(title=f"{str(member)} *`({str(member.id)})`* "
await self.log_channel.send(embed=em) f"nous a quitté 😦", colour=0xBD362F)
em.timestamp = datetime.datetime.utcnow()
await self.log_channel.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
async def on_message_delete(self, message): @commands.Cog.listener()
if message.guild.id == self.main_server_id and not message.author.bot: async def on_message_delete(self, message):
async def is_a_command(message): if message.guild.id == self.main_server_id and not message.author.bot:
prefix_lenght = len(await self.bot.get_prefix(message)) async def is_a_command(message):
command = (message.content.split()[0])[prefix_lenght:] prefix_lenght = len(await self.bot.get_prefix(message))
if command == '': command = (message.content.split()[0])[prefix_lenght:]
command = "not_a_command" if command == '':
command = "not_a_command"
return self.bot.get_command(str(command)) return self.bot.get_command(str(command))
if await is_a_command(message) is None: if await is_a_command(message) is None:
em = discord.Embed(title=f"Message supprimé dans : {str(message.channel.name)}", colour=0xBD362F) em = discord.Embed(title=f"Message supprimé dans :"
em.add_field(name=f"{str(message.author)} *`({str(message.author.id)})`* a supprimé :", value=str(message.content)) f" {str(message.channel.name)}",
em.timestamp = datetime.datetime.utcnow() colour=0xBD362F)
await self.log_channel.send(embed=em) em.add_field(name=f"{str(message.author)} "
f"*`({str(message.author.id)})`* "
f"a supprimé :", value=str(message.content))
em.timestamp = datetime.datetime.utcnow()
await self.log_channel.send(embed=em)
@commands.Cog.listener()
async def on_message_edit(self, before, after):
if before.guild.id == self.main_server_id and not before.author.bot:
em = discord.Embed(title=f"Message edité dans : "
f"{before.channel.name}", colour=0x0088CC)
em.add_field(name=f"{str(before.author)} "
f"*`({str(before.author.id)})`* a"
f" edité :", value=str(before.content))
em.add_field(name="Pour remplacer par :", value=str(after.content))
em.timestamp = datetime.datetime.utcnow()
await self.log_channel.send(embed=em)
async def on_message_edit(self, before, after):
if before.guild.id == self.main_server_id and not before.author.bot:
em = discord.Embed(title="Message edité dans : " + str(before.channel.name), colour=0x0088CC)
em.add_field(name=f"{str(before.author)} *`({str(before.author.id)})`* a edité :", value=str(before.content))
em.add_field(name="Pour remplacer par :", value=str(after.content))
em.timestamp = datetime.datetime.utcnow()
await self.log_channel.send(embed=em)
def setup(bot): def setup(bot):
bot.add_cog(SendLogs(bot)) bot.add_cog(SendLogs(bot))

View file

@ -1,107 +1,111 @@
from discord.ext import commands
import discord
import random
import asyncio import asyncio
import datetime
import discord
from discord.ext import commands
class Sondage: class Sondage(commands.Cog):
"""Commandes sondage.""" """Commandes sondage."""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@commands.command(pass_context=True) @commands.command(pass_context=True)
async def sondage(self, ctx, *, msg="help"): async def sondage(self, ctx, *, msg="help"):
if msg != "help": if msg != "help":
await ctx.message.delete() await ctx.message.delete()
options = msg.split(" | ") options = msg.split(" | ")
time = [x for x in options if x.startswith("time=")] time = [x for x in options if x.startswith("time=")]
if time: if time:
time = time[0] time = time[0]
options.remove(time) if time:
time = int(time.strip("time=")) options.remove(time)
else: if len(options) <= 1:
time = 0 raise commands.errors.MissingRequiredArgument
if len(options) <= 1: if len(options) >= 22:
raise commands.errors.MissingRequiredArgument return await ctx.send(f"{ctx.message.author.mention}> "
if len(options) >= 21: f":octagonal_sign: Vous ne pouvez pas "
return await ctx.send(ctx.author.mention + "> :octagonal_sign: Vous ne pouvez pas mettre plus de 20 réponses !") f"mettre plus de 20 réponses !")
emoji = ['1⃣', if time:
'2⃣', time = int(time.strip("time="))
'3⃣', else:
'4⃣', time = 0
'5⃣', emoji = ['1⃣',
'6⃣', '2⃣',
'7⃣', '3⃣',
'8⃣', '4⃣',
'9⃣', '5⃣',
'🔟', '6⃣',
'0⃣', '7⃣',
'🇦', '8⃣',
'🇧', '9⃣',
'🇨', '🔟',
'🇩', '0⃣',
'🇪', '🇦',
'🇫', '🇧',
'🇬', '🇨',
'🇭', '🇩',
'🇮' '🇪',
] '🇫',
to_react = [] '🇬',
confirmation_msg = "**{}?**:\n\n".format(options[0].rstrip("?")) '🇭',
for idx, option in enumerate(options[1:]): '🇮'
confirmation_msg += "{} - {}\n".format(emoji[idx], option) ]
to_react.append(emoji[idx]) to_react = []
confirmation_msg += "*Sondage proposé par* " + \ confirmation_msg = f"**{options[0].rstrip('?')}?**:\n\n"
str(ctx.author.mention) for idx, option in enumerate(options[1:]):
if time == 0: confirmation_msg += "{} - {}\n".format(emoji[idx], option)
confirmation_msg += "" to_react.append(emoji[idx])
else: confirmation_msg += "*Sondage proposé par* " + \
confirmation_msg += "\n\nVous avez {} secondes pour voter!".\ str(ctx.message.author.mention)
format(time) if time == 0:
poll_msg = await ctx.send(confirmation_msg) confirmation_msg += ""
for emote in to_react: else:
await poll_msg.add_reaction(emote) confirmation_msg += "\n\nVous avez {} secondes pour voter!". \
format(time)
poll_msg = await ctx.send(confirmation_msg)
for emote in to_react:
await poll_msg.add_reaction(emote)
if time != 0: if time != 0:
await asyncio.sleep(time) await asyncio.sleep(time)
if time != 0: if time != 0:
async for message in ctx.message.channel.history(): async for message in ctx.message.channel.history():
if message.id == poll_msg.id: if message.id == poll_msg.id:
poll_msg = message poll_msg = message
results = {} results = {}
for reaction in poll_msg.reactions: for reaction in poll_msg.reactions:
if reaction.emoji in to_react: if reaction.emoji in to_react:
results[reaction.emoji] = reaction.count - 1 results[reaction.emoji] = reaction.count - 1
end_msg = "Le sondage est términé. Les résultats sont:\n\n" end_msg = "Le sondage est términé. Les résultats sont:\n\n"
for result in results: for result in results:
end_msg += "{} {} - {} votes\n".\ end_msg += "{} {} - {} votes\n". \
format(result, format(result,
options[emoji.index(result)+1], options[emoji.index(result)+1],
results[result]) results[result])
top_result = max(results, key=lambda key: results[key]) top_result = max(results, key=lambda key: results[key])
if len([x for x in results if len([x for x in results
if results[x] == results[top_result]]) > 1: if results[x] == results[top_result]]) > 1:
top_results = [] top_results = []
for key, value in results.items(): for key, value in results.items():
if value == results[top_result]: if value == results[top_result]:
top_results.append(options[emoji.index(key)+1]) top_results.append(options[emoji.index(key)+1])
end_msg += "\nLes gagnants sont : {}".\ end_msg += "\nLes gagnants sont : {}". \
format(", ".join(top_results)) format(", ".join(top_results))
else: else:
top_result = options[emoji.index(top_result)+1] top_result = options[emoji.index(top_result)+1]
end_msg += "\n\"{}\" est le gagnant!".format(top_result) end_msg += "\n\"{}\" est le gagnant!".format(top_result)
await ctx.send(end_msg) await ctx.send(end_msg)
else: else:
await ctx.message.delete() await ctx.message.delete()
text = open('texts/rpoll.md').read()
em = discord.Embed(title='Aide sur le sondage',
description=text,
colour=0xEEEEEE)
await ctx.send(embed=em)
text = open('texts/rpoll.md').read()
em = discord.Embed(title='Aide sur le sondage',
description=text,
colour=0xEEEEEE)
await ctx.send(embed=em)
def setup(bot): def setup(bot):
bot.add_cog(Sondage(bot)) bot.add_cog(Sondage(bot))

View file

@ -1,284 +1,323 @@
from discord.ext import commands import datetime
import discord
import random
import json import json
import datetime, pytz import pytz
import calendar import random
import requests
import urllib import urllib
import socket
import discord
import requests
from discord.ext import commands
class Utility: class Utility(commands.Cog):
"""Commandes utilitaires.""" """Commandes utilitaires."""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@commands.group(name="clock", pass_context=True, case_insensitive=True) @commands.group(name="clock", pass_context=True, case_insensitive=True)
async def clock(self, ctx): async def clock(self, ctx):
"""Display hour in a country""" """Display hour in a country"""
if ctx.invoked_subcommand is None: if ctx.invoked_subcommand is None:
text = open('texts/clocks.md').read() text = open('texts/clocks.md').read()
em = discord.Embed(title='Liste des Horloges', description=text, colour=0xEEEEEE) em = discord.Embed(title='Liste des Horloges', description=text, colour=0xEEEEEE)
await ctx.send(embed=em) await ctx.send(embed=em)
@clock.command(name="montréal", aliases=["mtl", "montreal"], pass_context=True) @clock.command(name="montréal", aliases=["mtl", "montreal"], pass_context=True)
async def clock_montreal(self, ctx): async def clock_montreal(self, ctx):
then = datetime.datetime.now(pytz.utc) then = datetime.datetime.now(pytz.utc)
utc = then.astimezone(pytz.timezone('America/Montreal')) utc = then.astimezone(pytz.timezone('America/Montreal'))
site = "http://ville.montreal.qc.ca/" site = "http://ville.montreal.qc.ca/"
img = "https://upload.wikimedia.org/wikipedia/commons/e/e0/Rentier_fws_1.jpg" img = "https://upload.wikimedia.org/wikipedia/commons/e/e0/Rentier_fws_1.jpg"
country = "au Canada, Québec" country = "au Canada, Québec"
description = "Montréal est la deuxième ville la plus peuplée du Canada. Elle se situe dans la région du Québec" description = "Montréal est la deuxième ville la plus peuplée du Canada. Elle se situe dans la région du Québec"
form = '%H heures %M' form = '%H heures %M'
tt = utc.strftime(form) tt = utc.strftime(form)
em = discord.Embed(title='Heure à Montréal', description=f"A [Montréal]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE) em = discord.Embed(title='Heure à Montréal', description=f"A [Montréal]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE)
em.set_thumbnail(url = img) em.set_thumbnail(url = img)
await ctx.send(embed=em) await ctx.send(embed=em)
@clock.command(name="vancouver", pass_context=True) @clock.command(name="vancouver", pass_context=True)
async def clock_vancouver(self, ctx): async def clock_vancouver(self, ctx):
then = datetime.datetime.now(pytz.utc) then = datetime.datetime.now(pytz.utc)
utc = then.astimezone(pytz.timezone('America/Vancouver')) utc = then.astimezone(pytz.timezone('America/Vancouver'))
site = "http://vancouver.ca/" site = "http://vancouver.ca/"
img = "https://upload.wikimedia.org/wikipedia/commons/f/fe/Dock_Vancouver.JPG" img = "https://upload.wikimedia.org/wikipedia/commons/f/fe/Dock_Vancouver.JPG"
country = "au Canada" country = "au Canada"
description = "Vancouver, officiellement City of Vancouver, est une cité portuaire au Canada" description = "Vancouver, officiellement City of Vancouver, est une cité portuaire au Canada"
form = '%H heures %M' form = '%H heures %M'
tt = utc.strftime(form) tt = utc.strftime(form)
em = discord.Embed(title='Heure à Vancouver', description=f"A [Vancouver]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE) em = discord.Embed(title='Heure à Vancouver', description=f"A [Vancouver]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE)
em.set_thumbnail(url = img) em.set_thumbnail(url = img)
await ctx.send(embed=em) await ctx.send(embed=em)
@clock.command(name="new-york",aliases=["ny", "n-y", "new york"], pass_context=True) @clock.command(name="new-york",aliases=["ny", "n-y", "new york"], pass_context=True)
async def clock_new_york(self, ctx): async def clock_new_york(self, ctx):
then = datetime.datetime.now(pytz.utc) then = datetime.datetime.now(pytz.utc)
utc = then.astimezone(pytz.timezone('America/New_York')) utc = then.astimezone(pytz.timezone('America/New_York'))
site = "http://www1.nyc.gov/" site = "http://www1.nyc.gov/"
img = "https://upload.wikimedia.org/wikipedia/commons/e/e3/NewYork_LibertyStatue.jpg" img = "https://upload.wikimedia.org/wikipedia/commons/e/e3/NewYork_LibertyStatue.jpg"
country = "aux U.S.A." country = "aux U.S.A."
description = "New York, est la plus grande ville des États-Unis en termes d'habitants et l'une des plus importantes du continent américain. " description = "New York, est la plus grande ville des États-Unis en termes d'habitants et l'une des plus importantes du continent américain. "
form = '%H heures %M' form = '%H heures %M'
tt = utc.strftime(form) tt = utc.strftime(form)
em = discord.Embed(title='Heure à New York', description=f"A [str(New York]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE) em = discord.Embed(title='Heure à New York', description=f"A [str(New York]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE)
em.set_thumbnail(url = img) em.set_thumbnail(url = img)
await ctx.send(embed=em) await ctx.send(embed=em)
@clock.command(name="la", aliases=["los-angeles", "losangeles", "l-a", "los angeles"], pass_context=True) @clock.command(name="la", aliases=["los-angeles", "losangeles", "l-a", "los angeles"], pass_context=True)
async def clock_la(self, ctx): async def clock_la(self, ctx):
then = datetime.datetime.now(pytz.utc) then = datetime.datetime.now(pytz.utc)
utc = then.astimezone(pytz.timezone('America/Los_Angeles')) utc = then.astimezone(pytz.timezone('America/Los_Angeles'))
site = "https://www.lacity.org/" site = "https://www.lacity.org/"
img = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/LA_Skyline_Mountains2.jpg/800px-LA_Skyline_Mountains2.jpg" img = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/LA_Skyline_Mountains2.jpg/800px-LA_Skyline_Mountains2.jpg"
country = "aux U.S.A." country = "aux U.S.A."
description = "Los Angeles est la deuxième ville la plus peuplée des États-Unis après New York. Elle est située dans le sud de l'État de Californie, sur la côte pacifique." description = "Los Angeles est la deuxième ville la plus peuplée des États-Unis après New York. Elle est située dans le sud de l'État de Californie, sur la côte pacifique."
form = '%H heures %M' form = '%H heures %M'
tt = utc.strftime(form) tt = utc.strftime(form)
em = discord.Embed(title='Heure à Los Angeles', description=f"A [Los Angeles]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE) em = discord.Embed(title='Heure à Los Angeles', description=f"A [Los Angeles]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE)
em.set_thumbnail(url = img) em.set_thumbnail(url = img)
await ctx.send(embed=em) await ctx.send(embed=em)
@clock.command(name="paris", aliases=["baguette"],pass_context=True) @clock.command(name="paris", aliases=["baguette"],pass_context=True)
async def clock_paris(self, ctx): async def clock_paris(self, ctx):
then = datetime.datetime.now(pytz.utc) then = datetime.datetime.now(pytz.utc)
utc = then.astimezone(pytz.timezone('Europe/Paris')) utc = then.astimezone(pytz.timezone('Europe/Paris'))
site = "http://www.paris.fr/" site = "http://www.paris.fr/"
img = "https://upload.wikimedia.org/wikipedia/commons/a/af/Tour_eiffel_at_sunrise_from_the_trocadero.jpg" img = "https://upload.wikimedia.org/wikipedia/commons/a/af/Tour_eiffel_at_sunrise_from_the_trocadero.jpg"
country = "en France" country = "en France"
description = "Paris est la capitale de la France. Elle se situe au cœur d'un vaste bassin sédimentaire aux sols fertiles et au climat tempéré, le bassin parisien." description = "Paris est la capitale de la France. Elle se situe au cœur d'un vaste bassin sédimentaire aux sols fertiles et au climat tempéré, le bassin parisien."
form = '%H heures %M' form = '%H heures %M'
tt = utc.strftime(form) tt = utc.strftime(form)
em = discord.Embed(title='Heure à Paris', description=f"A [Paris]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE) em = discord.Embed(title='Heure à Paris', description=f"A [Paris]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE)
em.set_thumbnail(url = img) em.set_thumbnail(url = img)
await ctx.send(embed=em) await ctx.send(embed=em)
@clock.command(name="berlin", pass_context=True) @clock.command(name="berlin", pass_context=True)
async def clock_berlin(self, ctx): async def clock_berlin(self, ctx):
then = datetime.datetime.now(pytz.utc) then = datetime.datetime.now(pytz.utc)
utc = then.astimezone(pytz.timezone('Europe/Berlin')) utc = then.astimezone(pytz.timezone('Europe/Berlin'))
site = "http://www.berlin.de/" site = "http://www.berlin.de/"
img = "https://upload.wikimedia.org/wikipedia/commons/9/91/Eduard_Gaertner_Schlossfreiheit.jpg" img = "https://upload.wikimedia.org/wikipedia/commons/9/91/Eduard_Gaertner_Schlossfreiheit.jpg"
country = "en Allemagne" country = "en Allemagne"
description = "Berlin est la capitale et la plus grande ville d'Allemagne. Située dans le nord-est du pays, elle compte environ 3,5 millions d'habitants. " description = "Berlin est la capitale et la plus grande ville d'Allemagne. Située dans le nord-est du pays, elle compte environ 3,5 millions d'habitants. "
form = '%H heures %M' form = '%H heures %M'
tt = utc.strftime(form) tt = utc.strftime(form)
em = discord.Embed(title='Heure à Berlin', description=f"A [Berlin]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE) em = discord.Embed(title='Heure à Berlin', description=f"A [Berlin]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE)
em.set_thumbnail(url = img) em.set_thumbnail(url = img)
await ctx.send(embed=em) await ctx.send(embed=em)
@clock.command(name="berne", aliases=["zurich", "bern"], pass_context=True) @clock.command(name="berne", aliases=["zurich", "bern"], pass_context=True)
async def clock_berne(self, ctx): async def clock_berne(self, ctx):
then = datetime.datetime.now(pytz.utc) then = datetime.datetime.now(pytz.utc)
utc = then.astimezone(pytz.timezone('Europe/Zurich')) utc = then.astimezone(pytz.timezone('Europe/Zurich'))
site = "http://www.berne.ch/" site = "http://www.berne.ch/"
img = "https://upload.wikimedia.org/wikipedia/commons/d/db/Justitia_Statue_02.jpg" img = "https://upload.wikimedia.org/wikipedia/commons/d/db/Justitia_Statue_02.jpg"
country = "en Suisse" country = "en Suisse"
description = "Berne est la cinquième plus grande ville de Suisse et la capitale du canton homonyme. Depuis 1848, Berne est la « ville fédérale »." description = "Berne est la cinquième plus grande ville de Suisse et la capitale du canton homonyme. Depuis 1848, Berne est la « ville fédérale »."
form = '%H heures %M' form = '%H heures %M'
tt = utc.strftime(form) tt = utc.strftime(form)
em = discord.Embed(title='Heure à Berne', description=f"A [Berne]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE) em = discord.Embed(title='Heure à Berne', description=f"A [Berne]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE)
em.set_thumbnail(url = img) em.set_thumbnail(url = img)
await ctx.send(embed=em) await ctx.send(embed=em)
@clock.command(name="tokyo", pass_context=True) @clock.command(name="tokyo", pass_context=True)
async def clock_tokyo(self, ctx): async def clock_tokyo(self, ctx):
then = datetime.datetime.now(pytz.utc) then = datetime.datetime.now(pytz.utc)
utc = then.astimezone(pytz.timezone('Asia/Tokyo')) utc = then.astimezone(pytz.timezone('Asia/Tokyo'))
site = "http://www.gotokyo.org/" site = "http://www.gotokyo.org/"
img = "https://upload.wikimedia.org/wikipedia/commons/3/37/TaroTokyo20110213-TokyoTower-01.jpg" img = "https://upload.wikimedia.org/wikipedia/commons/3/37/TaroTokyo20110213-TokyoTower-01.jpg"
country = "au Japon" country = "au Japon"
description = "Tokyo, anciennement Edo, officiellement la préfecture métropolitaine de Tokyo, est la capitale du Japon." description = "Tokyo, anciennement Edo, officiellement la préfecture métropolitaine de Tokyo, est la capitale du Japon."
form = '%H heures %M' form = '%H heures %M'
tt = utc.strftime(form) tt = utc.strftime(form)
em = discord.Embed(title='Heure à Tokyo', description=f"A [Tokyo]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE) em = discord.Embed(title='Heure à Tokyo', description=f"A [Tokyo]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE)
em.set_thumbnail(url = img) em.set_thumbnail(url = img)
await ctx.send(embed=em) await ctx.send(embed=em)
@clock.command(name="moscou", aliases=["moscow", "moskova"], pass_context=True) @clock.command(name="moscou", aliases=["moscow", "moskova"], pass_context=True)
async def clock_moscou(self, ctx): async def clock_moscou(self, ctx):
then = datetime.datetime.now(pytz.utc) then = datetime.datetime.now(pytz.utc)
utc = then.astimezone(pytz.timezone('Europe/Moscow')) utc = then.astimezone(pytz.timezone('Europe/Moscow'))
site = "https://www.mos.ru/" site = "https://www.mos.ru/"
img = "https://upload.wikimedia.org/wikipedia/commons/f/f7/Andreyevsky_Zal.jpg" img = "https://upload.wikimedia.org/wikipedia/commons/f/f7/Andreyevsky_Zal.jpg"
country = "en Russie" country = "en Russie"
description = "Moscou est la capitale de la Fédération de Russie et la plus grande ville d'Europe. Moscou est situé sur la rivière Moskova. " description = "Moscou est la capitale de la Fédération de Russie et la plus grande ville d'Europe. Moscou est situé sur la rivière Moskova. "
form = '%H heures %M' form = '%H heures %M'
tt = utc.strftime(form) tt = utc.strftime(form)
em = discord.Embed(title='Heure à Moscou', description=f"A [Moscou]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE) em = discord.Embed(title='Heure à Moscou', description=f"A [Moscou]({site}) {country}, Il est **{str(tt)}** ! \n {description} \n _source des images et du texte : [Wikimedia foundation](http://commons.wikimedia.org/)_", colour=0xEEEEEE)
em.set_thumbnail(url = img) em.set_thumbnail(url = img)
await ctx.send(embed=em) await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command() @commands.command()
async def ytdiscover(self, ctx): async def ytdiscover(self, ctx):
"""Random youtube channel""" """Random youtube channel"""
with open('texts/ytb.json') as js: with open('texts/ytb.json') as js:
ytb = json.load(js) ytb = json.load(js)
clef = str(random.randint(0,12)) clef = str(random.randint(0,12))
chaine = ytb["{}".format(clef)] chaine = ytb["{}".format(clef)]
embed = discord.Embed(title=chaine['name'], embed = discord.Embed(title=chaine['name'],
url=chaine['url'], url=chaine['url'],
description=f"**{chaine['name']}**, {chaine['desc']} \n[Je veux voir ça]({chaine['url']})") description=f"**{chaine['name']}**, {chaine['desc']} \n[Je veux voir ça]({chaine['url']})")
embed.set_thumbnail(url='https://outout.tech/tuxbot/yt.png') embed.set_thumbnail(url='https://outout.tech/tuxbot/yt.png')
await ctx.send(embed=embed) await ctx.send(embed=embed)
"""--------------------------------------------------------------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command(name='hastebin', pass_context=True) @commands.command(name='hastebin', pass_context=True)
async def _hastebin(self, ctx, *, data): async def _hastebin(self, ctx, *, data):
"""Poster sur Hastebin.""" """Poster sur Hastebin."""
await ctx.message.delete() await ctx.message.delete()
post = requests.post("https://hastebin.com/documents", data=data) post = requests.post("https://hastebin.com/documents", data=data)
try: try:
await ctx.send(f"{ctx.message.author.mention} message posté avec succès sur :\nhttps://hastebin.com/{post.json()['key']}.txt") await ctx.send(f"{ctx.author.mention} message posté avec succès sur :\nhttps://hastebin.com/{post.json()['key']}.txt")
except json.JSONDecodeError: except json.JSONDecodeError:
await ctx.send("Impossible de poster ce message. L'API doit être HS.") await ctx.send("Impossible de poster ce message. L'API doit être HS.")
"""---------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@commands.command(name='iplocalise', pass_context=True) @commands.command(name='iplocalise', pass_context=True)
async def _iplocalise(self, ctx, ipaddress): async def _iplocalise(self, ctx, ipaddress, iptype=""):
"""Recup headers.""" realipaddress = ipaddress
if ipaddress.startswith("http://"): """Recup headers."""
ipaddress = ipaddress.split("http://")[1] if ipaddress.startswith("http://"):
if ipaddress.startswith("https://"): if ipaddress[-1:] == '/':
ipaddress = ipaddress.split("https://")[1] ipaddress = ipaddress[:-1]
iploading = await ctx.send("_réfléchis..._") ipaddress = ipaddress.split("http://")[1]
ipapi = urllib.request.urlopen("http://ip-api.com/json/" + ipaddress) if ipaddress.startswith("https://"):
ipinfo = json.loads(ipapi.read().decode()) if ipaddress[-1:] == '/':
ipaddress = ipaddress[:-1]
ipaddress = ipaddress.split("https://")[1]
if(iptype=="ipv6" or iptype=="v6"):
try:
ipaddress = socket.getaddrinfo(ipaddress, None, socket.AF_INET6)[1][4][0]
except:
await ctx.send("Erreur, cette adresse n'est pas disponible en IPv6.")
return
if ipinfo["status"] != "fail": iploading = await ctx.send("_réfléchis..._")
await iploading.edit(content="L'adresse IP ``{query}`` appartient à ``{org}`` et se situe à ``{city}``, dans ``{regionName}``, ``{country}``.".format(**ipinfo)) ipapi = urllib.request.urlopen("http://ip-api.com/json/" + ipaddress)
else: ipinfo = json.loads(ipapi.read().decode())
await iploading.edit(content=f"Erreur, impossible d'avoir des informations sur l'adresse IP {ipinfo['query']}")
if ipinfo["status"] != "fail":
if ipinfo['query']:
embed = discord.Embed(title=f"Informations pour ``{realipaddress}`` *`({ipinfo['query']})`*", color=0x5858d7)
if ipinfo['org']:
embed.add_field(name="Appartient à :", value=ipinfo['org'], inline = False)
if ipinfo['city']:
embed.add_field(name="Se situe à :", value=ipinfo['city'], inline = True)
if ipinfo['country']:
if ipinfo['regionName']:
regionName = ipinfo['regionName']
else:
regionName = "N/A"
embed.add_field(name="Region :", value=f"{regionName} ({ipinfo['country']})", inline = True)
embed.set_thumbnail(url=f"https://www.countryflags.io/{ipinfo['countryCode']}/flat/64.png")
await ctx.send(embed=embed)
else:
await ctx.send(content=f"Erreur, impossible d'avoir des informations sur l'adresse IP ``{ipinfo['query']}``")
await iploading.delete()
"""---------------------------------------------------------------------"""
@commands.command(name='getheaders', pass_context=True)
async def _getheaders(self, ctx, *, adresse):
"""Recuperer les HEADERS :d"""
print("Loaded")
if adresse.startswith("http://") != True and adresse.startswith("https://") != True:
adresse = "http://" + adresse
if len(adresse) > 200:
await ctx.send("{0} Essaye d'entrer une adresse de moins de 200 caractères plutôt.".format(ctx.author.mention))
elif adresse.startswith("http://") or adresse.startswith("https://") or adresse.startswith("ftp://"):
try:
get = urllib.request.urlopen(adresse, timeout = 1)
embed = discord.Embed(title="Entêtes de {0}".format(adresse), color=0xd75858)
embed.add_field(name="Code Réponse", value=get.getcode(), inline = True)
embed.set_thumbnail(url="https://http.cat/{}".format(str(get.getcode())))
if get.getheader('location'):
embed.add_field(name="Redirection vers", value=get.getheader('location'), inline=True)
if get.getheader('server'):
embed.add_field(name="Serveur", value=get.getheader('server'), inline=True)
if get.getheader('content-type'):
embed.add_field(name="Type de contenu", value = get.getheader('content-type'), inline = True)
if get.getheader('x-content-type-options'):
embed.add_field(name="x-content-type", value= get.getheader('x-content-type-options'), inline=True)
if get.getheader('x-frame-options'):
embed.add_field(name="x-frame-options", value= get.getheader('x-frame-options'), inline=True)
if get.getheader('cache-control'):
embed.add_field(name="Controle du cache", value = get.getheader('cache-control'), inline = True)
await ctx.send(embed=embed)
except urllib.error.HTTPError as e:
embed = discord.Embed(title="Entêtes de {0}".format(adresse), color=0xd75858)
embed.add_field(name="Code Réponse", value=e.getcode(), inline = True)
embed.set_thumbnail(url="https://http.cat/{}".format(str(e.getcode())))
await ctx.send(embed=embed)
print('''An error occurred: {} The response code was {}'''.format(e, e.getcode()))
except urllib.error.URLError as e:
print("ERROR @ getheaders @ urlerror : {} - adress {}".format(e, adresse))
await ctx.send('[CONTACTER ADMIN] URLError: {}'.format(e.reason))
except Exception as e:
print("ERROR @ getheaders @ Exception : {} - adress {}".format(e, adresse))
await ctx.send("{0} Impossible d'accèder à {1}, es-tu sur que l'adresse {1} est correcte et que le serveur est allumé ?".format(ctx.author.mention, adresse))
else:
await ctx.send("{0} Merci de faire commencer {1} par ``https://``, ``http://`` ou ``ftp://``.".format(ctx.author.mention, adresse))
"""---------------------------------------------------------------------"""
@commands.command(name='git', pass_context=True)
async def _git(self, ctx):
"""Pour voir mon code"""
text = "How tu veux voir mon repos Gitea pour me disséquer ? " \
"Pas de soucis ! Je suis un Bot, je ne ressens pas la " \
"douleur !\n https://git.gnous.eu/gnous/tuxbot"
em = discord.Embed(title='Repos TuxBot-Bot', description=text, colour=0xE9D460)
em.set_author(name='Gnous', icon_url="https://cdn.discordapp.com/"
"icons/280805240977227776/"
"9ba1f756c9d9bfcf27989d0d0abb3862"
".png")
await ctx.send(embed=em)
"""--------------------------------------------------------------------------------------------------------------------------"""
@commands.command(name='getheaders', pass_context=True)
async def _getheaders(self, ctx, *, adresse):
"""Recuperer les HEADERS :d"""
print("Loaded")
if adresse.startswith("http://") != True and adresse.startswith("https://") != True:
adresse = "http://" + adresse
if len(adresse) > 200:
await ctx.send("{0} Essaye d'entrer une adresse de moins de 200 caractères plutôt.".format(ctx.author.mention))
elif adresse.startswith("http://") or adresse.startswith("https://") or adresse.startswith("ftp://"):
try:
get = urllib.request.urlopen(adresse, timeout = 1)
embed = discord.Embed(title="Entêtes de {0}".format(adresse), color=0xd75858)
embed.add_field(name="Code Réponse", value=get.getcode(), inline = True)
embed.set_thumbnail(url="https://http.cat/{}".format(str(get.getcode())))
if get.getheader('location'):
embed.add_field(name="Redirection vers", value=get.getheader('location'), inline=True)
if get.getheader('server'):
embed.add_field(name="Serveur", value=get.getheader('server'), inline=True)
if get.getheader('content-type'):
embed.add_field(name="Type de contenu", value = get.getheader('content-type'), inline = True)
if get.getheader('x-content-type-options'):
embed.add_field(name="x-content-type", value= get.getheader('x-content-type-options'), inline=True)
if get.getheader('x-frame-options'):
embed.add_field(name="x-frame-options", value= get.getheader('x-frame-options'), inline=True)
if get.getheader('cache-control'):
embed.add_field(name="Controle du cache", value = get.getheader('cache-control'), inline = True)
await ctx.send(embed=embed)
except urllib.error.HTTPError as e:
embed = discord.Embed(title="Entêtes de {0}".format(adresse), color=0xd75858)
embed.add_field(name="Code Réponse", value=e.getcode(), inline = True)
embed.set_thumbnail(url="https://http.cat/{}".format(str(e.getcode())))
await ctx.send(embed=embed)
print('''An error occurred: {} The response code was {}'''.format(e, e.getcode()))
except urllib.error.URLError as e:
print("ERROR @ getheaders @ urlerror : {} - adress {}".format(e, adresse))
await ctx.send('[CONTACTER ADMIN] URLError: {}'.format(e.reason))
except Exception as e:
print("ERROR @ getheaders @ Exception : {} - adress {}".format(e, adresse))
await ctx.send("{0} Impossible d'accèder à {1}, es-tu sur que l'adresse {1} est correcte et que le serveur est allumé ?".format(ctx.author.mention, adresse))
else:
await ctx.send("{0} Merci de faire commencer {1} par ``https://``, ``http://`` ou ``ftp://``.".format(ctx.message.author.mention, adresse))
"""--------------------------------------------------------------------------------------------------------------------------"""
@commands.command(name='github', pass_context=True)
async def _github(ctx):
"""Pour voir mon code"""
text = "How tu veux voir mon repos Github pour me disséquer ? Pas de soucis ! Je suis un Bot, je ne ressens pas la douleur !\n https://github.com/outout14/tuxbot-bot"
em = discord.Embed(title='Repos TuxBot-Bot', description=text, colour=0xE9D460)
em.set_author(name='Outout', icon_url="https://avatars0.githubusercontent.com/u/14958554?v=3&s=400")
await ctx.send(embed=em)
def setup(bot): def setup(bot):
bot.add_cog(Utility(bot)) bot.add_cog(Utility(bot))

0
cogs/utils/cli_colors.py Normal file → Executable file
View file

View file

@ -1,67 +0,0 @@
import json
import os
import uuid
import asyncio
class Config:
"""The "database" object. Internally based on ``json``."""
def __init__(self, name, **options):
self.name = name
self.object_hook = options.pop('object_hook', None)
self.encoder = options.pop('encoder', None)
self.loop = options.pop('loop', asyncio.get_event_loop())
self.lock = asyncio.Lock()
if options.pop('load_later', False):
self.loop.create_task(self.load())
else:
self.load_from_file()
def load_from_file(self):
try:
with open(self.name, 'r') as f:
self._db = json.load(f, object_hook=self.object_hook)
except FileNotFoundError:
self._db = {}
async def load(self):
with await self.lock:
await self.loop.run_in_executor(None, self.load_from_file)
def _dump(self):
temp = '%s-%s.tmp' % (uuid.uuid4(), self.name)
with open(temp, 'w', encoding='utf-8') as tmp:
json.dump(self._db.copy(), tmp, ensure_ascii=True, cls=self.encoder, separators=(',', ':'))
# atomically move the file
os.replace(temp, self.name)
async def save(self):
with await self.lock:
await self.loop.run_in_executor(None, self._dump)
def get(self, key, *args):
"""Retrieves a config entry."""
return self._db.get(key, *args)
async def put(self, key, value, *args):
"""Edits a config entry."""
self._db[key] = value
await self.save()
async def remove(self, key):
"""Removes a config entry."""
del self._db[key]
await self.save()
def __contains__(self, item):
return item in self._db
def __getitem__(self, item):
return self._db[item]
def __len__(self):
return len(self._db)
def all(self):
return self._db

View file

@ -1,24 +1,29 @@
import pymysql import pymysql
def connect_to_db(self):
mysqlHost = self.bot.config.mysql["host"]
mysqlUser = self.bot.config.mysql["username"]
mysqlPass = self.bot.config.mysql["password"]
mysqlDB = self.bot.config.mysql["dbname"]
try: def connect_to_db(self):
return pymysql.connect(host=mysqlHost, user=mysqlUser, passwd=mysqlPass, db=mysqlDB, charset='utf8') mysqlHost = self.bot.config.mysql["host"]
except KeyError: mysqlUser = self.bot.config.mysql["username"]
print("Rest in peperoni, Impossible de se connecter a la base de données.") mysqlPass = self.bot.config.mysql["password"]
print(str(KeyError)) mysqlDB = self.bot.config.mysql["dbname"]
return
try:
return pymysql.connect(host=mysqlHost, user=mysqlUser,
passwd=mysqlPass, db=mysqlDB, charset='utf8')
except KeyError:
print(
"Rest in peperoni, Impossible de se connecter a la base de données.")
print(str(KeyError))
return
def reconnect_to_db(self): def reconnect_to_db(self):
if not self.conn: if not self.conn:
mysqlHost = self.bot.config.mysql["host"] mysqlHost = self.bot.config.mysql["host"]
mysqlUser = self.bot.config.mysql["username"] mysqlUser = self.bot.config.mysql["username"]
mysqlPass = self.bot.config.mysql["password"] mysqlPass = self.bot.config.mysql["password"]
mysqlDB = self.bot.config.mysql["dbname"] mysqlDB = self.bot.config.mysql["dbname"]
return pymysql.connect(host=mysqlHost, user=mysqlUser, passwd=mysqlPass, db=mysqlDB, charset='utf8') return pymysql.connect(host=mysqlHost, user=mysqlUser,
return self.conn passwd=mysqlPass, db=mysqlDB, charset='utf8')
return self.conn

0
cogs/utils/menu.py Normal file → Executable file
View file

0
cogs/utils/passport_generator.py Normal file → Executable file
View file

113
cogs/vocal.py Executable file
View file

@ -0,0 +1,113 @@
import asyncio
import os
import re
import subprocess
import uuid
import discord
from discord.ext import commands
from gtts import gTTS
class Vocal(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.playing = False
self.author = None
self.voice = None
"""---------------------------------------------------------------------"""
@staticmethod
def get_duration(file):
popen = subprocess.Popen(("ffprobe",
"-show_entries",
"format=duration",
"-i", file),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, err = popen.communicate()
match = re.search(r"[-+]?\d*\.\d+|\d+", str(output))
return float(match.group())
@commands.command(name="voc", no_pm=True, pass_context=True)
async def _voc(self, ctx, *, message=""):
if message == "":
await ctx.send("Veuillez écrire un message...")
return
if message == "stop_playing" \
and (
ctx.author.id == self.author.id
or ctx.message.channel.permissions_for(
ctx.message.author
).administrator is True
) \
and self.playing is True:
await ctx.send('stop')
await self.voice.disconnect()
self.playing = False
return
if self.playing is True:
await ctx.send("Je suis déja en train de parler,"
" merci de réenvoyer ton message"
" quand j'aurais fini.")
return
user = ctx.author
self.author = user
if user.voice:
self.playing = True
filename = f"data/tmp/voc/{uuid.uuid1()}.mp3"
lang = [x for x in message.split(" ") if x.startswith("lang=")]
loading = await ctx.send("*Chargement du message en cours...*")
if lang:
choice_lang = (lang[0])[5:]
message = f"{user.display_name} à dit: {message.strip(lang[0])}" if len(ctx.author.voice.channel.members) >= 4 else message.strip(lang[0])
try:
tts = gTTS(
text=message,
lang=str(choice_lang))
except ValueError:
tts = gTTS(
text=message,
lang="fr")
await ctx.send("La langue n'est pas supportée,"
" le francais a donc été choisi")
else:
message = f"{user.display_name} à dit: {message}" if len(ctx.author.voice.channel.members) >= 4 else message
tts = gTTS(text=message,
lang="fr")
tts.save(filename)
self.voice = await user.voice.channel.connect()
self.voice.play(discord.FFmpegPCMAudio(filename))
counter = 0
duration = self.get_duration(filename)
while not counter >= duration:
if self.playing:
await loading.edit(
content=f"Lecture du message de {self.author.display_name} en cours : {counter}sec/{duration}sec")
await asyncio.sleep(1)
counter += 1
else:
break
await self.voice.disconnect()
await loading.edit(content="Lecture terminée")
self.voice = None
os.remove(filename)
self.playing = False
else:
await ctx.send('Veuillez aller dans un channel vocal.')
def setup(bot):
bot.add_cog(Vocal(bot))

0
config.py.example Executable file → Normal file
View file

0
data/.DS_Store vendored Normal file → Executable file
View file

0
data/images/.DS_Store vendored Normal file → Executable file
View file

0
data/images/roles/android.png Normal file → Executable file
View file

Before

Width:  |  Height:  |  Size: 1,012 B

After

Width:  |  Height:  |  Size: 1,012 B

BIN
data/images/roles/redhat.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

0
data/images/roles/small/android.png Normal file → Executable file
View file

Before

Width:  |  Height:  |  Size: 518 B

After

Width:  |  Height:  |  Size: 518 B

3
init.sh Executable file
View file

@ -0,0 +1,3 @@
#pip install -U "https://github.com/Rapptz/discord.py/archive/rewrite.zip#egg=discord.py[voice]"
python3 -m pip install -U discord.py[voice]
pip install -r requirements.txt

View file

@ -1,43 +0,0 @@
#! /usr/bin/env python3
import locale
from dialog import Dialog
from subprocess import call
import os
locale.setlocale(locale.LC_ALL, '')
d = Dialog(dialog="dialog")
d.set_background_title("Tuxbot Manager v0.5a")
while True:
mmenu, rmenu = d.menu("Que souhaitez vous faire ?", choices = [("(1)", "Lancer Tuxbot"), ("(2)", "Eteindre Tuxbot"), ("(3)", "Mettre à jour Tuxbot"), ("(4)", "Quitter")])
if rmenu == "(1)":
d.gauge_start("Lancement")
d.gauge_update(10)
# try:
# call(["screen", "-S", "tuxbot", "-X","quit"])
# except:
# d.gauge_update(35)
d.gauge_update(40)
call(["screen","-S","tuxbot", "-d", "-m", "python3", "bot.py"])
d.gauge_update(100)
d.gauge_stop()
d.msgbox("Tuxbot est correctement lancé ! Merci de faire .ping sur discord pour vérifier.")
if rmenu == "(2)":
d.gauge_start("Arrêt")
d.gauge_update(10)
call(["screen", "-S", "tuxbot", "-X","quit"])
d.gauge_update(100)
d.gauge_stop()
d.msgbox("Tuxbot s'est correctement arrêté. Faites vite ;-) !")
if rmenu == "(4)":
d.pause("A bientôt !\n(C) 2018 Gnous.EU Dev Team.", seconds=2)
call(["clear"])
exit()
if rmenu == "(3)":
d.msgbox("Fonctionnalité indisponible pour le moment du fait que le serveur GIT de tuxbot est hors service.")

View file

@ -1,9 +0,0 @@
{
"token": "bot token",
"bots_key": "not required",
"client_id": "client id (Pas obligatoire)",
"game": "Eating apples - .help",
"prefix": [
"."
]
}

View file

@ -6,7 +6,7 @@ Ici ce trouve le code source du bot provenant du serveur Discord ["Gnous.eu"](h
[Voir le guide d'installation](https://wiki.gnous.eu/wiki/Tuxbot/Install) [Voir le guide d'installation](https://wiki.gnous.eu/wiki/Tuxbot/Install)
## Fabriqué avec ## Fabriqué avec
* [PyCharm](https://www.jetbrains.com/pycharm/) - Editeur de texte payant :3 * [PyCharm](https://www.jetbrains.com/pycharm/) - IDE payant :3
* [discord.py](https://github.com/Rapptz/discord.py) - API Python pour discord * [discord.py](https://github.com/Rapptz/discord.py) - API Python pour discord
## Versions ## Versions
@ -14,7 +14,7 @@ Liste des versions : [Cliquer pour afficher](https://github.com/outout14/tuxbot-
## Auteurs ## Auteurs
* **Maël** _alias_ [@outout14](https://github.com/outout14) * **Maël** _alias_ [@outout14](https://github.com/outout14)
* **Romain** _alias_ [Romain](https://github.com/Rom194) * **Romain** _alias_ [Romain](https://git.gnous.eu/Romain)
## License ## License
Ce projet est sous licence ``Creative Commons BY-NC-SA 4.0`` - voir le fichier [LICENSE.md](LICENSE.md) pour plus d'informations Ce projet est sous licence ``Creative Commons BY-NC-SA 4.0`` - voir le fichier [LICENSE.md](LICENSE.md) pour plus d'informations

View file

@ -1,9 +1,9 @@
git+https://github.com/Rapptz/discord.py@rewrite pymysql
asyncio gtts
beautifulsoup4 beautifulsoup4
lxml==4.2.4
bs4 bs4
pytz pytz
requests requests
wikipedia wikipedia
pymysql
pillow pillow

View file

@ -11,16 +11,17 @@
-> .sondage : Affiche l'aide pour la commande sondage -> .sondage : Affiche l'aide pour la commande sondage
-> .role _nomdurole_ : Ajoute/Retire le rôle en question -> .role _nomdurole_ : Ajoute/Retire le rôle en question
-> .iplocalise _IP ou NDD_ : affiche la localisation et le propriétaire de l'ip (ou de l'IP lié a un nom de domaine) -> .iplocalise _IP ou NDD_ : affiche la localisation et le propriétaire de l'ip (ou de l'IP lié a un nom de domaine)
-> .iplocalise _IP ou NDD_ **ipv6**: affiche la localisation et le propriétaire de l'ip en forçant sur l'IPv6 (ou de l'IP lié a un nom de domaine)
-> .getheaders _IP ou NDD_ : affiche les en-têtes (headers) d'une IP/Nom de domaine via HTTP/HTTPS/FTP -> .getheaders _IP ou NDD_ : affiche les en-têtes (headers) d'une IP/Nom de domaine via HTTP/HTTPS/FTP
-> .btcprice : Affiche le prix du bitcoin -> .btcprice : Affiche le prix du bitcoin
[split]
**Commandes Funs** **Commandes Funs**
-> .joke : Affiche une blague aléatoire -> .joke : Affiche une blague aléatoire
-> .ethylotest : Simule un ethylotest détraqué -> .ethylotest : Simule un ethylotest détraqué
-> .pokemon : Lance un combat de pokémons -> .pokemon : Lance un combat de pokémons
-> .coin : Simule un pile ou face -> .coin : Simule un pile ou face
-> .randomcat : Affiche des image de chats :3 -> .randomcat : Affiche des image de chats :3
[split]
**Commandes Carte d'Identité** **Commandes Carte d'Identité**
-> .ci : Affiche l'aide sur les cartes d'identité -> .ci : Affiche l'aide sur les cartes d'identité
-> .ci show _pseudo_ : Affiche la carte d'identité de _pseudo_ -> .ci show _pseudo_ : Affiche la carte d'identité de _pseudo_
@ -30,10 +31,10 @@
-> .ci setcountry : Défini votre pays -> .ci setcountry : Défini votre pays
-> .ci update : Met à jour votre image si vous l'avez changé :wink: -> .ci update : Met à jour votre image si vous l'avez changé :wink:
-> .ci delete : Supprime votre carte d'identité **a tous jamais** -> .ci delete : Supprime votre carte d'identité **a tous jamais**
[split]
**Commandes diverses** : **Commandes diverses** :
-> .info : Affiche des informations sur le bot -> .info : Affiche des informations sur le bot
-> .help : Affiche ce message -> .help : Affiche ce message
-> .clock : Affiche la liste des horloges des villes -> .clock : Affiche la liste des horloges des villes
-> .ping : Ping le bot -> .ping : Ping le bot
-> .github : Affiche le repos Github du Bot :heart: -> .git : Affiche le repos Gitea du Bot :heart:

View file

@ -1,24 +1,24 @@
<:stafftools:314348604095594498> **Développement** : :tools: **Développement** :
└> Outout : [outout.xyz](https://outout.xyz/) └> Outout : [outout.xyz](https://outout.xyz/)
└> Romain : [son github](http://git.dyjix.eu/Romain) └> Romain : [son github](http://git.gnous.eu/Romain)
└> Langage : [Python3](http://www.python.org/) └> Langage : [Python3](http://www.python.org/)
└> Api : [discord.py {3}](https://github.com/Rapptz/discord.py) └> Api : [discord.py {3}](https://github.com/Rapptz/discord.py)
└> Discord Api : [{4}]({4})
└> En se basant sur : [RobotDanny](https://github.com/Rapptz/RoboDanny) └> En se basant sur : [RobotDanny](https://github.com/Rapptz/RoboDanny)
<:server:334347432835940352> **Hébergé sur "{2}"**: <:server:577916597239283742> **Hébergé sur "{2}"**:
└> <:tux:282212977627758593> OS : {0} └> <:tux:282212977627758593> OS : {0}
└> <:python:334346615366221825> Version : {1} └> Version : {1}
<:contact:334347787200233483> **Contact** : :telephone: **Contact** :
└> <:discord:314003252830011395> : Outout#8406 └> <:DiscordLogoColor:577915413573402624> : Outout#8406
└> <:twitter:314349922877046786> : [@outoutxyz](https://twitter.com/outouxyz) └> <:twitter:577915119032336387> : [@outoutxyz](https://twitter.com/outouxyz)
└> <:mail:334345653419245571> : [mael@gnous.eu](mailto:mael@gnous.eu) └> :mailbox: : [mael@gnous.eu](mailto:mael@gnous.eu)
└> <:discord:314003252830011395> : Romain#5117 └> <:DiscordLogoColor:577915413573402624> : Romain#5117
<:discord:314003252830011395> **Serveurs** : <:DiscordLogoColor:577915413573402624> **Serveur** :
└> :tux: Serveur de TuxBot : [rejoindre](https://discord.gg/5UZy8Pn) └> Serveur GnousEU : [rejoindre](https://discord.gg/NFW3EeS)
└> <:tux:514930485751971866> Serveur GNU/Linux-Fr : [rejoindre](https://discord.gg/B5TzW7x)

0
texts/rpoll.md Normal file → Executable file
View file