Example #1
0
    async def handle(client: discord.Client, message: discord.Message, config):
        last_update = datetime.datetime.strptime(config['update']['last_update'], '%Y-%m-%dT%H:%M:%S')
        now = datetime.datetime.now()

        if last_update + datetime.timedelta(minutes=int(config['update']['time_between_update'])) > now:
            return

        config['update']['last_update'] = now.strftime('%Y-%m-%dT%H:%M:%S')

        with open('run/config/config.yml', 'w') as file:
            documents = yaml.dump(config, file, sort_keys=True)

        api_manager = APIManager(config['api']['url'], config['api']['token'])
        now = datetime.datetime.now()
        state, res = api_manager.get_data(
            'temp-bans',
            is_active=True,
            end_time__lte=now.strftime('%Y-%m-%dT%H:%M:%S')
        )

        if not state:
            return

        with open("src/_data/roles.yml", 'r') as stream:
            roles = yaml.safe_load(stream)

        role = [Role(data=x) for x in roles if x['slug'].startswith('ban')]

        for bt in res:
            await update_bantemp(client, message, TempBan(data=bt), role, config)
Example #2
0
async def banned_come_back(client: discord.Client, member: discord.Member, config):
    if member.guild.id != 278653494846685186:
        return

    api_manager = APIManager(config['api']['url'], config['api']['token'])

    state, res = api_manager.get_data(
        'temp-bans',
        user_id=str(member.id),
        is_active=True,
    )

    if not res:
        return

    with open("src/_data/roles.yml", 'r') as stream:
        roles = yaml.safe_load(stream)

    role = [Role(data=x) for x in roles if x['slug'].startswith('ban')]

    for r in role:
        await member.add_roles(member.guild.get_role(r.role_id),
                               reason=f"Bantemp")

    for channel in [config['channels']['moderator'], config['channels']['log_reactions']]:
        await client.get_channel(channel).send(
            embed=EmbedsManager.sanction_embed(
                f"{member.display_name} vient de contourner son bantemp",
                f"Il avait été bantemp pour : `{res[0]['reason']}`.")
                .set_footer(icon_url=client.user.avatar_url, text='Made By Gastbob40')
        )

    await client.get_channel( config['channels']['flood']).send(
        embed=EmbedsManager.secret_embed(
            f"je vous prie d'accueillir {member.display_name} qui vient d'essayer de contourner son ban temp.")
            .set_footer(icon_url=client.user.avatar_url, text='Made By Gastbob40')
    )

    await member.send(
        embed=EmbedsManager.sanction_embed(
            f"Bonjour {member.display_name} !",
            f"Vous nous avez fait peur en quittant {member.guild.name}, mais heureusement que vous êtes revenu.\n\n"
            f"Mais ne vous inquiétez pas, nous vous avons gardé votre bantemp rien que pour vous :wink:.")
            .set_footer(icon_url=client.user.avatar_url, text='Made By Gastbob40')
    )

    for channel in member.guild.channels:
        try:
            if isinstance(channel, discord.TextChannel):
                if member.permissions_in(channel).read_messages:
                    await channel.set_permissions(member,
                                                  send_messages=False)
            elif isinstance(channel, discord.VoiceChannel):
                if member.permissions_in(channel).connect:
                    await channel.set_permissions(member,
                                                  connect=False)
        except:
            pass
Example #3
0
async def warn_member(client: discord.Client, message: discord.Message,
                      args: List[str], config):
    api_manager = APIManager(config['api']['url'], config['api']['token'])

    if not PermissionChecker.is_moderator(message.author):
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "You don't have the necessary permissions."))

    # Display help
    if args and args[0] == '-h':
        return await message.channel.send(
            embed=EmbedsManager.information_embed(
                "**Warning command reminder:**\n\n"
                "`!av <@user> <reason>`."))

    # Check if target exist
    target: discord.Member = message.mentions[0] if len(
        message.mentions) == 1 else False

    if not target:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Error in the command. You must mention an user."))

    args = args[1:]

    if len(args) == 0:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Error in the command. You must add a reason."))

    warn = Warn()
    warn.user_id = target.id
    warn.moderator_id = message.author.id
    warn.reason = ' '.join(args)
    warn.save()

    _, res = api_manager.get_data('warns', user_id=target.id)
    nb_warns = len(res)

    await message.channel.send(embed=EmbedsManager.sanction_embed(
        f"Avertissement du membre {target.display_name}.",
        f"Vous venez de l'avertir pour : `{warn.reason}`.").add_field(
            name="Nombre :", value=nb_warns, inline=False).set_footer(
                icon_url=client.user.avatar_url, text='Made By Gastbob40'))

    await client.get_channel(
        config['channels']['log_reactions']
    ).send(embed=EmbedsManager.sanction_embed(
        f"Avertissement du membre {target.display_name}.",
        f"Il a été averti pour : `{warn.reason}`.").set_footer(
            icon_url=client.user.avatar_url, text='Made By Gastbob40').
           add_field(name="Auteur :", value=message.author.display_name))

    await target.send(embed=EmbedsManager.sanction_embed(
        f"Vous venez de subir un avertissement.",
        f"Vous venez d'être averti pour : `{warn.reason}`.").set_footer(
            icon_url=client.user.avatar_url, text='Made By Gastbob40'
        ).add_field(name="Auteur :", value=message.author.display_name))
Example #4
0
async def load_custom_commands(client: discord.Client,
                               message: discord.Message, args: List[str],
                               config):

    api_manager = APIManager(config['api']['url'], config['api']['token'])

    if not PermissionChecker.is_owner(message.author):
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "You don't have the necessary permissions."))

    state, res = api_manager.get_data('custom-commands')

    if not state:
        return await message.channel.send(embed=EmbedsManager.error_embed(res))

    with open('src/_data/custom_commands.yml', 'w') as file:
        documents = yaml.dump(res, file, sort_keys=True)

    return await message.channel.send(embed=EmbedsManager.complete_embed(
        "The command was successful.",
        f'{len(res)} custom commands have been loaded.'))
import datetime
import yaml
from src.utils.api_manager import APIManager

with open("run/config/config.yml", 'r') as stream:
    data = yaml.safe_load(stream)
    api_manager = APIManager(data['api']['url'], data['api']['token'])


class PostRestriction:
    id: int
    user_id: int
    channel_id: int
    start_time: datetime.date
    end_time: datetime.date

    def __init__(self, **kwargs):
        """
        Init of the class
        :param kwargs: a warn from the api
        """
        if 'data' in kwargs:
            self.id = int(kwargs['data']['id'])
            self.user_id = int(kwargs['data']['user_id'])
            self.channel_id = int(kwargs['data']['channel_id'])
            self.start_time = datetime.datetime.strptime(
                kwargs['data']['start_time'], '%Y-%m-%dT%H:%M:%S')
            self.end_time = datetime.datetime.strptime(
                kwargs['data']['end_time'], '%Y-%m-%dT%H:%M:%S')
        else:
            self.id = -1
Example #6
0
import discord

from src.utils.api_manager import APIManager
from src.utils.embeds_manager import EmbedsManager

api_manager = APIManager()


class LogManager:
    @staticmethod
    async def complete_log(client: discord.Client,
                           sanction_type: str,
                           author: discord.Member or discord.User,
                           guild: discord.Guild,
                           reason: str,
                           image_url: str = ''):
        state, results = api_manager.get_data('servers', discord_id=guild.id)

        if not state:
            return

        log_channel_id = results[0]['discord_log_channel_id']
        log_channel: discord.TextChannel = client.get_channel(log_channel_id)
        embed = EmbedsManager.sanction_embed(sanction_type, guild, reason,
                                             image_url)
        embed.description = f"Sanction by {author.display_name}"

        if log_channel:
            await log_channel.send(embed=embed)

        main_channel_log = client.get_channel(553974648258166800)
Example #7
0
import discord
import yaml

from src.eventsHandler.eventsHandler import EventsHandler
from src.utils.embeds_manager import EmbedsManager
# Get configuration
from src.utils.permissions_manager import PermissionsManager
from src.utils.api_manager import APIManager

sanctions_manager = APIManager()
permissions_manager = PermissionsManager()

with open('run/config/tokens.yml', 'r') as file:
    tokens = yaml.safe_load(file)

client = discord.Client()


@client.event
async def on_ready():
    await EventsHandler.on_ready(client)


@client.event
async def on_message(message: discord.Message):
    await EventsHandler.on_message(client, message)


@client.event
async def on_reaction_add(reaction, user):
    await EventsHandler.on_reaction_add(client, reaction, user)
async def bantemp_member(client: discord.Client, message: discord.Message,
                         args: List[str], config):
    api_manager = APIManager(config['api']['url'], config['api']['token'])

    if not PermissionChecker.is_moderator(message.author):
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Vous n'avez pas les permissions nécessaires."))

    # Display help
    if args and args[0] == '-h':
        return await message.channel.send(
            embed=EmbedsManager.information_embed(
                "**Rappel de la commande de bannissement temporaire :**\n\n"
                "`!bt <@user> <durée> <reason>`."))

    # Check if target exist
    target: discord.Member = message.mentions[0] if len(
        message.mentions) == 1 else False

    if not target:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans la commande. Vous devez mentionner un utilisateur."))

    args = args[1:]

    if len(args) == 0:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans la commande. Vous devez spécifié une durée."))

    bantemp = TempBan()
    bantemp.user_id = target.id
    bantemp.moderator_id = message.author.id

    if args[0].isdigit():
        if int(args[0]) < 24:
            delta = f'{int(args[0])} heure(s)'
        elif int(args[0]) % 24 == 0:
            delta = f'{int(args[0]) / 24} jour(s)'
        else:
            delta = f'{math.floor(int(args[0]) / 24)} jour(s) et {int(args[0]) % 24} heure(s)'

        bantemp.end_time += timedelta(hours=int(args[0]))

    elif args[0] and args[0][-1] == 'd' and args[0][:-1].isdigit():
        delta = f'{int(args[0][:-1])} jour(s)'
        bantemp.end_time += timedelta(days=int(args[0][:-1]))

    else:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            f"Erreur dans la commande. La date spécifiée est incorrecte (`{args[0]}`)."
        ))

    args = args[1:]

    if len(args) == 0:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans la commande. Vous devez spécifié une raison."))

    bantemp.reason = ' '.join(args)
    bantemp.save()

    _, res = api_manager.get_data('temp-bans', user_id=target.id)
    nb_bt = len(res)

    await message.channel.send(embed=EmbedsManager.sanction_embed(
        f"Bannissement temporaire du membre {target.display_name} pour une durée de {delta}.",
        f"Ce joueur ne respecte toujours pas les règles malgré un rappel d'un Modérateur, il prend donc un BanTemp"
    ).set_footer(
        icon_url=client.user.avatar_url, text='Made By Gastbob40'
    ).add_field(
        name="Rappel :",
        value=
        "Sachez que plusieurs BanTemp peuvent conduire à un Bannissement définitif du serveur!\n\n"
        f"Pour évitez cela, prenez connaissance des {client.get_channel(280735672527224842).mention} qui ne"
        f" sont pas nombreuses mais importantes pour le bon fonctionnement du serveur.",
        inline=False
    ).add_field(name="Raison :", value=bantemp.reason, inline=True).add_field(
        name="Durée :", value=delta, inline=True
    ).add_field(name="Nombre :", value=nb_bt, inline=True).set_image(
        url=
        'https://cdn.discordapp.com/attachments/377179445640822784/663478346763599872'
        '/photostudio_15295854416791.png'))

    await client.get_channel(
        config['channels']['log_reactions']
    ).send(embed=EmbedsManager.sanction_embed(
        f"Bannissement temporaire du membre {target.display_name} pour une durée de {delta}.",
        f"Il a été bantemp pour : `{bantemp.reason}`.").set_footer(
            icon_url=client.user.avatar_url, text='Made By Gastbob40'
        ).add_field(name="Durée :", value=delta, inline=True).add_field(
            name="Auteur :", value=message.author.display_name, inline=True))

    try:
        await target.send(embed=EmbedsManager.sanction_embed(
            f"Vous venez de subir un bannissement temporaire de {delta}.",
            f"Vous venez d'être bantemp pour : `{bantemp.reason}`.\n\n"
            f"Sachez que plusieurs bans temporaires conduisent à un ban définitif."
        ).set_footer(
            icon_url=client.user.avatar_url, text='Made By Gastbob40'
        ).add_field(name="Durée :", value=delta, inline=True).add_field(
            name="Auteur :", value=message.author.display_name, inline=True))
    except:
        pass

    # Add roles

    with open("src/_data/roles.yml", 'r') as stream:
        roles = yaml.safe_load(stream)

    role = [Role(data=x) for x in roles if x['slug'].startswith('ban')]

    for r in role:
        await target.add_roles(
            message.guild.get_role(r.role_id),
            reason=f"Bantemp pour {bantemp.reason} pour une durée de {delta}")

    for channel in message.guild.channels:
        try:
            if isinstance(channel, discord.TextChannel):
                if target.permissions_in(channel).read_messages:
                    await channel.set_permissions(target, send_messages=False)
            elif isinstance(channel, discord.VoiceChannel):
                if target.permissions_in(channel).connect:
                    await channel.set_permissions(target, connect=False)
        except:
            print("Cannot do magic in " + channel.name)
async def view_warns(client: discord.Client, message: discord.Message,
                     args: List[str], config):
    api_manager = APIManager(config['api']['url'], config['api']['token'])

    if not PermissionChecker.is_moderator(message.author) and len(
            message.mentions):
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Vous n'avez pas les permissions nécessaires."))

    channel = 289476916044627978
    if not PermissionChecker.is_moderator(
            message.author) and message.channel.id != channel:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Hum, vous n'êtes pas dans le bon salon.\n\n"
            f"Merci de réessayer dans {message.guild.get_channel(channel).mention}."
        ))

    # Display help
    if args and args[0] == '-h':
        return await message.channel.send(embed=EmbedsManager.information_embed(
            "**Rappel de la commande de visualisation des avertissements :**\n\n"
            "`!ia <?@user>`."))

    # Check if target exist
    target: discord.Member = message.mentions[0] if len(
        message.mentions) == 1 else message.author

    state, res = api_manager.get_data('warns', user_id=target.id)

    if not state:
        return

    if not res:
        return await message.channel.send(embed=EmbedsManager.sanction_embed(
            f"Le membre {target.name}#{target.discriminator} n'a aucun avertissement:",
        ).set_thumbnail(url=target.avatar_url).set_footer(
            icon_url=client.user.avatar_url, text='Made By Gastbob40'))

    if len(res) > 20:
        return await message.channel.send(
            EmbedsManager.error_embed(
                f"Hum, on dirait que {target.name}#{target.discriminator} a trop d'avertissements :(\n"
                f"Je vous conseille d'aller sur le site web afin de pouvoir voir la liste detaillée."
            ))

    warns = [Warn(data=x) for x in res]
    embed = EmbedsManager.sanction_embed(
        f"Voici les informations concernants {target.name}#{target.discriminator} :"
    ) \
        .set_thumbnail(url=target.avatar_url) \
        .set_footer(icon_url=client.user.avatar_url, text='Made By Gastbob40')

    for warn in warns:
        moderator = message.guild.get_member(warn.moderator_id) if \
            message.guild.get_member(warn.moderator_id) else \
            'Un ancien modérateur'

        embed.add_field(
            name=
            f"Avertissement de {moderator}, le {warn.time.strftime('%d/%m/%Y à %H:%M')}",
            value=f"Avertissement pour `{warn.reason}`",
            inline=False)

    await message.channel.send(embed=embed)
Example #10
0
async def change_nick(client: discord.Client, message: discord.Message,
                      args: List[str], config):
    api_manager = APIManager(config['api']['url'], config['api']['token'])

    # Display help
    if args and args[0] == '-h':
        return await message.channel.send(
            embed=EmbedsManager.information_embed(
                "**Rappel de la commande de changement de pseudo :**\n\n"
                "`!change_nick <pseudo>`."))

    if not args:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans la commande. Vous devez spécifé un pseudo"))

    nickname = Nickname()
    nickname.nickname = ' '.join(args)
    nickname.user_id = message.author.id

    for letter in nickname.nickname:
        if ord(letter) > 255:
            return await message.channel.send(embed=EmbedsManager.error_embed(
                "Erreur dans la commande. Seul les caractères *simples* sont autorisés"
                " (code ASCII entre 0 et 255).").set_footer(
                    icon_url=client.user.avatar_url, text='Made By Gastbob40'))

    state, res = api_manager.get_data('nicknames',
                                      user_id=str(message.author.id))

    if not state:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans l'api. Merci de contacter gast.").set_footer(
                icon_url=client.user.avatar_url, text='Made By Gastbob40'))

    nicknames = [Nickname(data=x) for x in res]

    nicknames = sorted(nicknames, key=lambda x: x.time, reverse=True)
    now = datetime.datetime.now()

    # He can't change
    if nicknames and nicknames[0].time + datetime.timedelta(days=7) > now:
        new_date = nicknames[0].time + datetime.timedelta(days=7)
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Vous avez changé votre pseudo il y a moins de 1 semaine.\n\n"
            f"Vous pourrez le changer le {new_date.day}/{new_date.month}/{new_date.year}"
            f" à {new_date.hour}:{new_date.minute}.").set_footer(
                icon_url=client.user.avatar_url, text='Made By Gastbob40'))

    try:

        old_nickname = message.author.display_name

        await message.author.edit(nick=nickname.nickname)

        nickname.save()

        await message.channel.send(embed=EmbedsManager.complete_embed(
            "Vous venez de changer de pseudo avec succès.",
            f"Vos êtes dorénavant `{nickname.nickname}`.").set_footer(
                icon_url=client.user.avatar_url, text='Made By Gastbob40'))

        await client.get_channel(
            config['channels']['log_reactions']
        ).send(embed=EmbedsManager.complete_embed(
            f"{message.author.name}#{message.author.discriminator} vient de changer de pseudo."
        ).add_field(
            name='Ancien pseudo', value=old_nickname, inline=True).add_field(
                name='Nouveau pseudo', value=nickname.nickname,
                inline=True).set_footer(icon_url=client.user.avatar_url,
                                        text='Made By Gastbob40'))

    except:
        await message.channel.send(embed=EmbedsManager.error_embed(
            "Hum, je n'ai pas reussi a changer votre pseudo.").set_footer(
                icon_url=client.user.avatar_url, text='Made By Gastbob40'))
async def verify_post(client: discord.Client, message: discord.Message,
                      config):
    api_manager = APIManager(config['api']['url'], config['api']['token'])

    if PermissionChecker.is_moderator(message.author):
        return

    state, res = api_manager.get_data('post-restrictions',
                                      user_id=str(message.author.id),
                                      channel_id=str(message.channel.id))

    if not state:
        return

    now = datetime.datetime.now()
    restrictions = [PostRestriction(data=x) for x in res]

    # This is him first message => ok
    # He can post (After end time)
    if not restrictions or restrictions[
            0].end_time < now or now < restrictions[0].start_time:
        if not restrictions or now > restrictions[0].start_time:
            if not restrictions:
                restriction = PostRestriction()
                restriction.user_id = message.author.id
                restriction.channel_id = message.channel.id
                restriction.start_time = now + datetime.timedelta(minutes=2)
                restriction.end_time = now + datetime.timedelta(
                    hours=config['time_between_restricted_post'])
                restriction.save()

            else:
                restrictions[0].start_time = now + datetime.timedelta(
                    minutes=2)
                restrictions[0].end_time = now + datetime.timedelta(
                    hours=config['time_between_restricted_post'])
                restrictions[0].update()

    else:
        # Message is not authorize
        await message.delete()
        next_post = restrictions[0].end_time

        await client.get_channel(
            config['channels']['log_reactions']
        ).send(embed=EmbedsManager.sanction_embed(
            f"Message de {message.author.name}#{message.author.discriminator} refusé pour cause de restriction.",
            "Le joueur à été averti en message privé et le message a été supprimé."
        ).add_field(
            name='Salon', value=message.channel.mention,
            inline=True).add_field(
                name='Prochain post',
                value=f"le {next_post.day}/{next_post.month}/{next_post.year}"
                f" à {next_post.hour}:{next_post.minute}.",
                inline=True).set_footer(icon_url=client.user.avatar_url,
                                        text='Made By Gastbob40'))

        await message.author.send(embed=EmbedsManager.sanction_embed(
            f"Votre message a été refusé pour cause de restriction.",
            "Pour des raisons d'équités entre les joueurs, vous ne pouvez envoyer de message sur ce salon"
            " qu'une fois toutes les 22 heures.").add_field(
                name='Salon', value=message.channel.mention, inline=True
            ).add_field(
                name='Prochain post',
                value=f"Le {next_post.day}/{next_post.month}/{next_post.year}"
                f" à {next_post.hour}:{next_post.minute}.",
                inline=True).set_footer(icon_url=client.user.avatar_url,
                                        text='Made By Gastbob40'))
async def unbantemp_member(client: discord.Client, message: discord.Message,
                           args: List[str], config):
    api_manager = APIManager(config['api']['url'], config['api']['token'])

    if not PermissionChecker.is_moderator(message.author):
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Vous n'avez pas les permissions nécessaires."))

    # Display help
    if args and args[0] == '-h':
        return await message.channel.send(
            embed=EmbedsManager.information_embed(
                "**Rappel de la commande de bannissement temporaire :**\n\n"
                "`!eb <@user>`."))

    # Check if target exist
    target: discord.Member = message.mentions[0] if len(
        message.mentions) == 1 else False

    if not target:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans la commande. Vous devez mentionner un utilisateur."))

    state, res = api_manager.get_data(
        'temp-bans',
        user_id=str(target.id),
        is_active=True,
    )

    if not state:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans l'api. Merci de contacter gast."))

    if len(res) == 0:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            f"Erreur dans la commande. {target.display_name} n'a pas de bantemp actif"
        ))

    # Remove roles

    with open("src/_data/roles.yml", 'r') as stream:
        roles = yaml.safe_load(stream)

    role = [Role(data=x) for x in roles if x['slug'].startswith('ban')]

    for r in role:
        await target.remove_roles(message.guild.get_role(r.role_id))

    # Send message

    await message.channel.send(embed=EmbedsManager.sanction_embed(
        f"Vous venez de retirer le bantemp de {target.display_name}"
    ).set_footer(icon_url=client.user.avatar_url, text='Made By Gastbob40'))

    await client.get_channel(
        config['channels']['log_reactions']
    ).send(embed=EmbedsManager.sanction_embed(
        f"Le bantemp de {target.display_name} vient d'être retiré.",
        f"Auteur : {message.author.display_name}").set_footer(
            icon_url=client.user.avatar_url, text='Made By Gastbob40'))

    try:
        await target.send(embed=EmbedsManager.sanction_embed(
            f"{message.author.display_name} vient de retirer votre bantemp."
        ).set_footer(icon_url=client.user.avatar_url, text='Made By Gastbob40')
                          )
    except:
        pass

    # Update data

    temp_bans = [TempBan(data=x) for x in res]

    for bt in temp_bans:
        bt.is_active = False
        bt.update()

    # Reset permission

    for channel in message.guild.channels:

        try:
            if isinstance(channel, discord.TextChannel):
                if not target.permissions_in(channel).send_messages:
                    await channel.set_permissions(target, overwrite=None)
            elif isinstance(channel, discord.VoiceChannel):
                if not target.permissions_in(channel).connect:
                    await channel.set_permissions(target, overwrite=None)
        except:
            pass
Example #13
0
async def get_top(client: discord.Client, message: discord.Message,
                  args: List[str], config):
    api_manager = APIManager(config['api']['url'], config['api']['token'])

    if not PermissionChecker.is_moderator(message.author):
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Vous n'avez pas les permissions nécessaires."))

    # Display help
    if args and args[0] == '-h':
        return await message.channel.send(embed=EmbedsManager.information_embed(
            "**Rappel de la commande de récupération des meilleurs messages :**\n\n"
            "`!top`."))

    # Get channel and messages
    channel: discord.TextChannel = message.guild.get_channel(
        config['channels']['top'])

    john_message: discord.Message = await channel.fetch_message(
        id=683660205250183198)

    messages: List[discord.Message] = await channel.history(
        limit=None, after=john_message.edited_at).flatten()

    # Get cleaned data
    emoji = '👍'
    records = []
    for msg in messages:
        if not msg.author.bot:
            for reaction in msg.reactions:
                if reaction.emoji == emoji:
                    records.append({
                        'author': msg.author,
                        'content': msg.content,
                        'date': msg.created_at,
                        'link': msg.jump_url,
                        'count': reaction.count
                    })

    # Sort data
    records = sorted(records, key=lambda x: x['count'], reverse=True)

    # Get just the 10 best records
    records = records[:10]

    for index, record in enumerate(records):
        content = record['content']
        if len(content) > 1024:
            content = record['content'][:1020] + '...'

        embed = discord.Embed(color=0xff0000) \
            .set_author(
            name=f"Message {index + 1}."
        ) \
            .add_field(
            name="Contenu du message",
            value=content,
            inline=False
        ) \
            .add_field(
            name="Nombre de vote (👍) :",
            value=record['count'],
            inline=True
        ) \
            .add_field(
            name="Lien du message",
            value=record['link'],
            inline=True
        ) \
            .set_thumbnail(url=record['author'].avatar_url)

        embed.description = f"Proposition de {record['author'].name}#{record['author'].discriminator} " \
                            f"({record['author'].id})"

        await message.channel.send(embed=embed)
Example #14
0
async def reinit_restriction(client: discord.Client, message: discord.Message,
                             args: List[str], config):
    api_manager = APIManager(config['api']['url'], config['api']['token'])

    if not PermissionChecker.is_moderator(message.author):
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Vous n'avez pas les permissions nécessaires."))

    # Display help
    if args and args[0] == '-h':
        return await message.channel.send(embed=EmbedsManager.information_embed(
            "**Rappel de la commande de rénitialistion de restriction :**\n\n"
            "`!bt <@user> <durée> <reason>`.\n\n"
            "Attention, vous devez être dans le salon restreint."))

    if not message.channel.id in config['restricted_channels']:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans la commande. Vous n'êtes pas dans un salon restreint."
        ))

    # Check if target exist
    target: discord.Member = message.mentions[0] if len(
        message.mentions) == 1 else False

    if not target:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans la commande. Vous devez mentionner un utilisateur."))

    state, res = api_manager.get_data('post-restrictions',
                                      user_id=str(target.id),
                                      channel_id=str(message.channel.id))

    if not state:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            "Erreur dans l'api. Merci de contacter gast."))

    restriction = None if not res else PostRestriction(data=res[0])

    if not restriction:
        return await message.channel.send(embed=EmbedsManager.error_embed(
            f"Erreur dans la commande. {target.name}#{target.discriminator} n'a pas de restriction"
            f" active dans {message.channel.mention}"))

    else:
        restriction.delete()

        await client.get_channel(
            config['channels']['log_reactions']
        ).send(embed=EmbedsManager.sanction_embed(
            f"{message.author.name}#{message.author.discriminator} vient de retirer une restriction de "
            f"{target.name}#{target.discriminator}.", ).add_field(
                name='Salon', value=message.channel.mention, inline=True
            ).add_field(
                name='Membre', value=target.mention, inline=True).set_footer(
                    icon_url=client.user.avatar_url, text='Made By Gastbob40'))

        await message.channel.send(embed=EmbedsManager.sanction_embed(
            f"Vous venez de retirer une restriction de "
            f"{target.name}#{target.discriminator}.", ).add_field(
                name='Salon', value=message.channel.mention, inline=True
            ).add_field(
                name='Membre', value=target.mention, inline=True).set_footer(
                    icon_url=client.user.avatar_url, text='Made By Gastbob40'))

        await target.send(embed=EmbedsManager.sanction_embed(
            f"{message.author.name}#{message.author.discriminator} vient de vous retirer une restriction.",
        ).add_field(
            name='Salon', value=message.channel.mention,
            inline=True).add_field(
                name='Membre', value=target.mention, inline=True).set_footer(
                    icon_url=client.user.avatar_url, text='Made By Gastbob40'))
Example #15
0
 def __init__(self, client: discord.Client):
     self.client = client
     self.get_config()
     self.api_manager = APIManager()
Example #16
0
class NewsGroupManager:
    NNTP: nntplib.NNTP = None
    address: str = None
    groups: Dict = None
    encoding: str = None
    config: Dict = None
    delta_time: str = None
    client: discord.Client
    api_manager: APIManager
    stop_on_error: bool = None
    date_format: str = None
    assistants: List = None

    def __init__(self, client: discord.Client):
        self.client = client
        self.get_config()
        self.api_manager = APIManager()

    def open_connection(self):
        try:
            self.NNTP = nntplib.NNTP(self.address)
        except Exception as e:
            print("Error when opening nntp connection")
            raise e

    def close_connection(self):
        try:
            self.NNTP.quit()
        except Exception as e:
            print("Error when closing nntp connection")
            raise e

    def get_config(self):
        with open('run/config/config_newsgroups.yml', 'r') as file:
            self.config = yaml.safe_load(file)
        self.address = self.config["address"]
        self.encoding = self.config["encoding"]
        self.date_format = self.config["date_format"]
        self.stop_on_error = self.config["stop_on_error"]
        self.delta_time = self.config["delta_time"]
        self.assistants = self.config["assistants"]

    def get_info_from_news(self, news_id: str) -> Dict:
        info = dict()
        _, head = self.NNTP.head(news_id)
        last = "NULL"
        for l in head.lines:
            s = l.decode(self.encoding).split(": ", 1)
            if len(s) != 2:
                info[last] = info[last] + nntplib.decode_header(s[0])
                continue
            last = s[0]
            info[s[0]] = nntplib.decode_header(s[1])
        return info

    async def print_news(self, group: Dict, news_id: str):
        info = self.get_info_from_news(news_id)
        author = info["From"]
        ref = None if "References" not in info else info["References"]
        match = re.search('.*<(.*)>', author)
        mail = match.group(1) if match else ""
        subject = info["Subject"]
        date = get_date(info["Date"])

        _, body = self.NNTP.body(news_id)
        content = ""
        for l in body.lines:
            content += l.decode(self.encoding) + "\n"

        is_assistant = mail in self.assistants
        # get the tags
        tags = []
        if subject[:4] != "Re: ":
            subject = subject[4:]
        s = subject.split("]", 1)
        while len(s) != 1:
            tags.append((s[0])[1:])
            s = s[1].split("]", 1)
        subject = s[0]

        # slice the msg in chunk of 5120 char
        msg = [content[i:i + 5117] for i in range(0, len(content), 5117)]

        # print msg in every channel newsgroup_filler_embed
        if is_assistant:
            embed = EmbedsManager.newsgroup_embed_assistant(
                subject, tags, msg[0], author, date, group["name"], ref
                is not None)
        else:
            embed = EmbedsManager.newsgroup_embed(subject, tags, author, date,
                                                  group["name"], ref
                                                  is not None)

        for guild in group['channels']:
            await self.client.get_channel(int(guild['channel_id'])
                                          ).send(embed=embed)

        if not is_assistant:
            return

        for i in range(1, len(msg)):
            embed = EmbedsManager.newsgroup_filler_embed(
                "..." + msg[i], author, date, group["name"], ref is not None)
            for guild in group['channels']:
                await self.client.get_channel(int(guild['channel_id'])
                                              ).send(embed=embed)

    async def print_news_from_group(self, group: Dict):
        last_update: datetime = datetime.strptime(group["last_update"], self.date_format) \
            .astimezone(pytz.timezone("Europe/Paris"))

        _, news = self.NNTP.newnews(group['slug'], last_update)

        for news_id in list(dict.fromkeys(news)):
            try:
                await self.print_news(group.copy(), news_id)
            except Exception as exe:
                print("err for news {}".format(news_id))
                if self.stop_on_error:
                    raise exe
                await LogManager.error_log(
                    self.client,
                    "Newsgroup error for news : {}\n{}".format(news_id, exe))

        if len(news) == 0:
            return
        group["last_update"] = (datetime.now() + timedelta(seconds=1)) \
            .astimezone(pytz.timezone("Europe/Paris")) \
            .strftime(self.date_format)

        b, reason = self.api_manager.edit_data(
            "news-groups", id=group["id"], last_update=group["last_update"])

        if not b:
            raise Exception(
                "cannot send information to server, reason: {}".format(reason))

    async def get_news(self):
        try:

            # Load data from API
            state, res = self.api_manager.get_data('news-groups')

            # Check if we get a response from the API
            if not state:
                return

            # Start the connection
            self.open_connection()

            # For each news group, do magic
            for group in res:
                await self.print_news_from_group(group)

            self.close_connection()
        except Exception as exe:
            if self.stop_on_error:
                raise exe
            await LogManager.error_log(
                self.client, "Newsgroup error while updating\n{}".format(exe))

        await asyncio.sleep(int(self.delta_time))