Exemplo n.º 1
0
async def custom_config(ctx):
    """
    Verifica as configurações customizaveis para este server.
    """
    server = make_hash('id', ctx.message.guild.id).decode('utf-8')
    payload = Query.get_custom_config(server)
    gql_client = get_gql_client(BACKEND_URL)

    try:
        response = gql_client.execute(payload)
    except Exception as err:
        log.error(f'Erro: {str(err)}\n\n')
        return await ctx.send('D-desculpa, não consegui...')

    data = response.get('custom_config')
    embed = discord.Embed(color=0x1E1E1E, type='rich')
    embed.add_field(name='Server', value=data.get('server_name'), inline=True)
    embed.add_field(name='Sys Channel',
                    value=data.get('main_channel'),
                    inline=True)
    embed.add_field(name='Allow auto send message',
                    value=data.get('allow_auto_send_messages'),
                    inline=False)
    embed.add_field(name='Allow chat learning',
                    value=data.get('allow_learning_from_chat'),
                    inline=False)
    embed.add_field(name='Filter offensive messages',
                    value=data.get('filter_offensive_messages'),
                    inline=False)

    return await ctx.send('Configurações do servidor:', embed=embed)
Exemplo n.º 2
0
    async def track(self):
        """ Tracking task """
        log.info('tracking...')
        gql_client = get_gql_client(BACKEND_URL)

        for guild in self.guilds:
            log.info(guild.name)

            server = make_hash('id', guild.id).decode('utf-8')
            # recupera a configuração do server
            query = Query.get_custom_config(server)
            try:
                response = gql_client.execute(query)
            except:
                log.error(f'Cant get server {guild.name} config. Skipping!')
                continue

            server_config = response.get('custom_config')
            main_channel = server_config.get('main_channel')

            if not main_channel:
                continue

            channel = client.get_channel(int(main_channel))

            # data da última mensagem enviada no server
            try:
                last_message_dt = parser.parse(self.short_memory.get(guild.id))
            except:
                last_message_dt = None

            if last_message_dt:
                now = datetime.now().astimezone(tz=timezone.utc)
                elapsed_time = now.replace(
                    tzinfo=None) - last_message_dt.replace(tzinfo=None)

                log.info('elapsed time: ')
                log.info(elapsed_time)
                log.info('total: ')
                log.info(elapsed_time.total_seconds() / 60 / 60)

                if (elapsed_time.total_seconds() / 60 / 60) > self.window:
                    if server_config.get('allow_auto_send_messages'):
                        # envia mensagem no canal principal se autorizado
                        log.info('Notifying channel %s', channel)
                        await channel.send(choice(bored_messages))

                    # Renova a data de última mensagem para a data atual
                    self.short_memory.set(guild.id,
                                          str(now.astimezone(tz=timezone.utc)))
                    log.info('Renewed datetime to %s', str(now))
                    payload = Mutation.update_emotion(server=server,
                                                      aptitude=-0.1)
                    try:
                        response = gql_client.execute(payload)
                        log.info('Updated aptitude')
                    except Exception as err:
                        log.error(f'Erro: {str(err)}\n\n')
Exemplo n.º 3
0
async def on_member_join(member):
    """
    Greets the new member.
    """
    # Gets an hello
    message = ResponseGenerator.get_greeting_response()
    server_reference = make_hash('id', int(member.guild.id))
    query = Query.get_custom_config(server_reference)
    try:
        response = gql_client.execute(query)
    except:
        log.error(f'Cant get server {server_reference} config. Skipping!')
        return None

    server_config = response.get('custom_config')
    channel = client.get_channel(int(server_config.get('main_channel')))
    if channel:
        await channel.send(f'{message} {member.mention}')
Exemplo n.º 4
0
async def on_member_join(member):
    """
    Greets the new member.
    """
    # Gets an hello
    message = ResponseGenerator.get_greeting_response()
    server_reference = make_hash('id', int(member.guild.id))
    query = Query.get_custom_config(server_reference)
    try:
        response = gql_client.execute(query)
    except:
        log.error(f'Cant get server {server_reference} config. Skipping!')
        return None

    server_config = response.get('custom_config')
    channel = client.get_channel(int(server_config.get('main_channel')))
    if channel:
        await channel.send(
            'https://media.discordapp.net/attachments/590678517407285251/865606198341926912/jerry.gif?width=979&height=466'
        )
        await channel.send(f'{message} bem vinde.')
Exemplo n.º 5
0
async def on_message(message):
    """
    Handler para mensagens do chat.
    """
    channel = message.channel
    if message.author.bot:
        return

    await client.process_commands(message)

    server = make_hash('id', message.guild.id).decode('utf-8')

    # guarda a data da mensagem como valor para o id da guilda
    short_memory = redis.Redis(REDIS_HOST, REDIS_PORT)
    short_memory.set(message.guild.id, str(message.created_at))

    text = message.content

    global_intention, specific_intention = get_intentions(text)
    is_offensive = validate_text_offense(text)
    text_pol = extract_sentiment(text)
    user_name = message.author.name
    new_humor = change_humor_values(text_pol, is_offensive)
    friendshipness = -0.5 + text_pol if is_offensive else text_pol
    msg = {
        'global_intention': global_intention,
        'specific_intention': specific_intention,
        'text': text
    }

    user_id = make_hash(server, message.author.id).decode('utf-8')
    gql_client = get_gql_client(BACKEND_URL)

    # Atualiza o humor da Luci
    payload = Mutation.update_emotion(server=server, **new_humor)
    try:
        gql_client.execute(payload)
    except Exception as err:
        log.error(f'Erro: {str(err)}\n\n')

    # Atualiza o humor status do usuario
    payload = Mutation.update_user(user_id, user_name, friendshipness,
                                   new_humor, msg)

    try:
        gql_client.execute(payload)
    except Exception as err:
        log.error(f'Erro: {str(err)}\n\n')

    # get server configuration
    query = Query.get_custom_config(server)
    try:
        response = gql_client.execute(query)
    except Exception as error:
        log.error(str(error))
        response = {}

    server_config = response.get('custom_config')

    # Atualiza reconhecimento de respostas, se for resposta à outra mensagem
    if message.reference:
        payload = Mutation.assign_response(
            text=message.reference.resolved.content, possible_response=msg)

        try:
            response = gql_client.execute(payload)
        except Exception as err:
            log.error(f'Erro: {str(err)}\n\n')

    # process @Luci mentions
    if str(channel.guild.me.id) in text:
        # busca possíveis respostas na memória de longo prazo
        payload = Query.get_possible_responses(text=remove_id(text))

        try:
            response = gql_client.execute(payload)
        except Exception as err:
            log.error(f'Erro: {str(err)}\n\n')
            response = {'messages': []}

        if response.get('messages'):
            possible_responses = []
            for msg in response['messages']:
                for possible_response in msg.get('possible_responses'):
                    possible_responses.append(possible_response.get('text'))

            if possible_responses:
                return await channel.send(choice(possible_responses))

        # Caso não conheça nenhuma resposta, use o classificador inocente
        return await channel.send(
            naive_response(remove_id(text), reference=server))

    # 10% chance to not answer if is offensive and lucis not mentioned
    is_allowed = server_config.get('allow_auto_send_messages')
    if not is_allowed:
        return

    if is_offensive and choice([1, 0]) and choice([1, 0]):
        return await channel.send(
            f'{message.author.mention} {choice(offended)}')