<commit_before>import asyncio
import re
import datetime
from datetime import datetime as dt

import discord
import peewee

from modules.base.command import Command
from modules.base.database import BaseModel


class Mute(Command):
    muted_role = 'Muted'
    rx_timediff_all = re.compile('^([0-9]+[smhdSMDH]?)+$')
    rx_timediff = re.compile('([0-9]+[smhdSMDH]?)')

    cant_manage_msg = 'no tengo permiso pa manejar roles D:'

    def __init__(self, bot):
        super().__init__(bot)
        self.name = 'mute'
        self.help = 'Mutea usuarios'
        self.owner_only = True
        self.db_models = [MutedUser]
        self.run_task = True
        self.allow_pm = False

    async def handle(self, message, cmd):
        if len(cmd.args) < 1 or len(message.mentions) != 1:
            await cmd.answer('Formato: !mute <@mención> [duración] [razón]')
            return

        member = message.mentions[0]
        server = message.server
        await cmd.typing()

        if member.id == self.bot.user.id:
            await cmd.answer('como me vas a mutear a mi! owo')
            return

        if member.id == cmd.author.id:
            await cmd.answer('no podi mutearte a ti mismo jaj')
            return

        # Verificar si se pueden manejar roles
        if not self.can_manage_roles(server):
            self.log.warning(Mute.cant_manage_msg + ' (server: %s)', str(server))
            await cmd.answer(Mute.cant_manage_msg)
            return

        # Obtener tiempo del mute
        until = None
        deltatime = None
        if len(cmd.args) > 1:
            if Mute.rx_timediff_all.match(cmd.args[1]) is None:
                await cmd.answer('Tiempo de mute no válido')
                return

            deltatime = Mute.timediff_parse(cmd.args[1])
            until = dt.now() + deltatime

        str_deltatime = '' if deltatime is None else ' por ' + Mute.deltatime_to_str(deltatime)
        if deltatime is not None and str_deltatime == '':
            await cmd.answer('Si quieres desmutear a alguien, utiliza !unmute <user>')
            return

        # Quitar mute de la db si ya está muteado
        MutedUser.delete().where(MutedUser.userid == member.id).execute()

        # Revisar si el usuario ya tiene el rol
        mutedrole = None
        for role in member.roles:
            if role.name == Mute.muted_role:
                mutedrole = role
                break

        # Si el usuario ya tiene el rol, no es necesario agregarlo
        if mutedrole is None:
            mutedrole = Command.get_server_role(server, Mute.muted_role)
            # if mutedrole is still None
            if mutedrole is None:
                self.log.warning('El rol "%s" no existe (server: %s)', Mute.muted_role, server)
                await cmd.answer('El rol "{}" no existe!'.format(Mute.muted_role))
                return

            await self.bot.add_roles(member, mutedrole)

        reason = ' '.join(cmd.args[2:]).strip()
        str_reason = ' debido a: **{}**'.format(reason) if reason != '' else ''
        MutedUser.insert(userid=member.id, serverid=server.id, until=until, reason=reason,
                         author_name=str(cmd.author), author_id=cmd.author.id).execute()

        # Enviar PM con el aviso del mute
        try:
            await self.bot.send_message(member, 'Hola! Lamentablemente has sido muteado en el servidor **{}**{}{}.'
                                        .format(server.name, str_deltatime, str_reason))
        except discord.errors.Forbidden as e:
            self.log.exception(e)

        # Avisar por el canal donde se envió el comando
        await cmd.answer('**{}** ha sido mutead@{}{}!'.format(member.display_name, str_deltatime, str_reason))

    # Restaurar el rol de muteado una vez que el usuario ha reingresado
    async def on_member_join(self, member):
        server = member.server
        if not self.can_manage_roles(server):
            self.log.warning(Mute.cant_manage_msg)
            return

        role = Command.get_server_role(server, Mute.muted_role)
        if role is None:
            self.log.warning('El rol "%s" no existe (server: %s)', Mute.muted_role, server)
            return

        try:
            muted = MutedUser.get((MutedUser.until > dt.now()) | MutedUser.until.is_null(),
                                  MutedUser.userid == member.id)
            self.bot.add_role(member, role)
            self.log.info('Rol de muteado agregado a %s server %s', member.display_name, server)
            return
        except MutedUser.DoesNotExist:
            pass

    # Elimina los roles de muteado una vez que ha terminado
    async def task(self):
        muted = MutedUser.select().where((MutedUser.until <= dt.now()) & MutedUser.until.is_null(False))<commit_msg>Fix agregar mute nuevamente<commit_after>import asyncio
import re
import datetime
from datetime import datetime as dt

import discord
import peewee

from modules.base.command import Command
from modules.base.database import BaseModel


class Mute(Command):
    muted_role = 'Muted'
    rx_timediff_all = re.compile('^([0-9]+[smhdSMDH]?)+$')
    rx_timediff = re.compile('([0-9]+[smhdSMDH]?)')

    cant_manage_msg = 'no tengo permiso pa manejar roles D:'

    def __init__(self, bot):
        super().__init__(bot)
        self.name = 'mute'
        self.help = 'Mutea usuarios'
        self.owner_only = True
        self.db_models = [MutedUser]
        self.run_task = True
        self.allow_pm = False

    async def handle(self, message, cmd):
        if len(cmd.args) < 1 or len(message.mentions) != 1:
            await cmd.answer('Formato: !mute <@mención> [duración] [razón]')
            return

        member = message.mentions[0]
        server = message.server
        await cmd.typing()

        if member.id == self.bot.user.id:
            await cmd.answer('como me vas a mutear a mi! owo')
            return

        if member.id == cmd.author.id:
            await cmd.answer('no podi mutearte a ti mismo jaj')
            return

        # Verificar si se pueden manejar roles
        if not self.can_manage_roles(server):
            self.log.warning(Mute.cant_manage_msg + ' (server: %s)', str(server))
            await cmd.answer(Mute.cant_manage_msg)
            return

        # Obtener tiempo del mute
        until = None
        deltatime = None
        if len(cmd.args) > 1:
            if Mute.rx_timediff_all.match(cmd.args[1]) is None:
                await cmd.answer('Tiempo de mute no válido')
                return

            deltatime = Mute.timediff_parse(cmd.args[1])
            until = dt.now() + deltatime

        str_deltatime = '' if deltatime is None else ' por ' + Mute.deltatime_to_str(deltatime)
        if deltatime is not None and str_deltatime == '':
            await cmd.answer('Si quieres desmutear a alguien, utiliza !unmute <user>')
            return

        # Quitar mute de la db si ya está muteado
        MutedUser.delete().where(MutedUser.userid == member.id).execute()

        # Revisar si el usuario ya tiene el rol
        mutedrole = None
        for role in member.roles:
            if role.name == Mute.muted_role:
                mutedrole = role
                break

        # Si el usuario ya tiene el rol, no es necesario agregarlo
        if mutedrole is None:
            mutedrole = Command.get_server_role(server, Mute.muted_role)
            # if mutedrole is still None
            if mutedrole is None:
                self.log.warning('El rol "%s" no existe (server: %s)', Mute.muted_role, server)
                await cmd.answer('El rol "{}" no existe!'.format(Mute.muted_role))
                return

            await self.bot.add_roles(member, mutedrole)

        reason = ' '.join(cmd.args[2:]).strip()
        str_reason = ' debido a: **{}**'.format(reason) if reason != '' else ''
        MutedUser.insert(userid=member.id, serverid=server.id, until=until, reason=reason,
                         author_name=str(cmd.author), author_id=cmd.author.id).execute()

        # Enviar PM con el aviso del mute
        try:
            await self.bot.send_message(member, 'Hola! Lamentablemente has sido muteado en el servidor **{}**{}{}.'
                                        .format(server.name, str_deltatime, str_reason))
        except discord.errors.Forbidden as e:
            self.log.exception(e)

        # Avisar por el canal donde se envió el comando
        await cmd.answer('**{}** ha sido mutead@{}{}!'.format(member.display_name, str_deltatime, str_reason))

    # Restaurar el rol de muteado una vez que el usuario ha reingresado
    async def on_member_join(self, member):
        server = member.server
        if not self.can_manage_roles(server):
            self.log.warning(Mute.cant_manage_msg)
            return

        role = Command.get_server_role(server, Mute.muted_role)
        if role is None:
            self.log.warning('El rol "%s" no existe (server: %s)', Mute.muted_role, server)
            return

        try:
            muted = MutedUser.get((MutedUser.until > dt.now()) | MutedUser.until.is_null(),
                                  MutedUser.userid == member.id)
            self.bot.add_roles(member, role)
            self.log.info('Rol de muteado agregado a %s server %s', member.display_name, server)
            return
        except MutedUser.DoesNotExist:
            pass

    # Elimina los roles de muteado una vez que ha terminado
    async def task(self):
        muted = MutedUser.select().where((MutedUser.until <= dt.now()) & MutedUser.until.is_null(False))
{'fraction_non_alphanumeric': 0.10525221008840353, 'fraction_numerical': 0.0022880915236609465, 'mean_word_length': 2.1059431524547803, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1969864', 'n_tokens_mistral': 3080, 'n_tokens_neox': 3006, 'n_words': 776}