Пример #1
0
def analyze_response(response_data):
    """
    Analyze LUIS response
    :param response_data: response data
    :return: response analyzed
    """
    try:
        # Retrieve intent
        intent = response_data['topScoringIntent']['intent']
        score = response_data['topScoringIntent']['score']
        log.info('|LUIS| Intent that we got [{}]'.format(intent))

        # Initialize answer array
        answer = list()

        # Check score
        if score < SCORE_THRESHOLD:
            answer.extend(error.get_message())
            return answer

        # Select intent
        if intent.startswith('Indication.Activity'):
            answer.extend(activities.get_message(response_data))
        elif intent.startswith('HackUPC'):
            answer.extend(hackupc.get_message(response_data))
        elif intent.startswith('HardwareLab'):
            answer.extend(hardware_lab.get_message(response_data))
        elif intent.startswith('Logistics'):
            answer.extend(logistics.get_message(response_data))
        elif intent.startswith('Meals'):
            answer.extend(meals.get_message(response_data))
        elif intent.startswith('Mentor'):
            answer.extend(mentor.get_message(response_data))
        elif intent.startswith('Indication.Place'):
            answer.extend(places.get_message(response_data))
        elif intent.startswith('Project'):
            answer.extend(projects.get_message(response_data))
        elif intent.startswith('Smalltalk'):
            answer.extend(smalltalk.get_message(response_data))
        elif intent.startswith('Sponsors'):
            answer.extend(sponsors.get_message(response_data))
        elif intent.startswith('Support'):
            answer.extend(support.get_message(response_data))
        else:
            if exists_biene(response_data):
                answer.extend(['BIENE'])
            else:
                answer.extend(error.get_message())
            return answer

        # Check for biene manually
        if exists_biene(response_data):
            answer.extend(['BIENE'])
        # Return array of answers
        return answer

    except Exception as e:
        # Log error and return default error message
        log.error(e)
        return error.get_message()
Пример #2
0
def run_bienebot():
    """
    Run Biene Bot
    :return: biene bot ran
    """
    slack = Slack()
    try:
        if slack.rtm_connect():
            log.info('|BIENE| Biene Bot connected and running!')
            slack.notify(':bee: Biene Bot connected and running!')
            while True:
                message, channel, user = slack.retrieve_message()
                if message:
                    process = mp.Process(target=worker,
                                         args=(
                                             message,
                                             channel,
                                             user,
                                             slack,
                                         ))
                    process.daemon = True
                    process.start()
                time.sleep(RTM_READ_DELAY)
        else:
            log.error('Connection failed. Exception traceback printed above.',
                      slack)
    except Exception as e:
        log.error(e, slack)
    finally:
        log.info('|BIENE| Biene Bot stopped!')
        slack.notify(':bee: Biene Bot stopped!')
        return
Пример #3
0
def get_message(response_type):
    """
    Return a message from a sponsor intent
    :param response_type luis response
    """
    with open(
            'hackupc/bienebot/responses/places/places_data.json') as json_data:
        data = json.load(json_data)

        intent = response_type['topScoringIntent']['intent']
        list_intent = intent.split('.')

        entities = response_type['entities']

        # Log stuff
        if entities:
            log_info = '|RESPONSE| About [{}] getting [{}]'.format(
                entities[0]['entity'], list_intent[1])
        else:
            log_info = '|RESPONSE| No entities about places'
        log.info(log_info)

        switcher = {'When': when, 'Where': where, 'Help': help_place}
        # Get the function from switcher dictionary
        func = switcher.get(list_intent[2], lambda: error.get_message())
        # Execute the function
        return func(data, entities)
Пример #4
0
def get_intent(query):
    """
    Get intent from LUIS
    :param query: query
    :return: LUIS answer
    """
    log.info('|LUIS| Get intent with query [{}]'.format(query))
    headers = {
        'Ocp-Apim-Subscription-Key': LUIS_SUBSCRIPTION_KEY,
    }
    params = {
        'q': query,
        'timezoneOffset': '0',
        'verbose': 'false',
        'spellCheck': 'false',
        'staging': 'false',
    }
    try:
        url = 'https://{}/luis/v2.0/apps/{}'.format(LUIS_SERVER, LUIS_ID)
        response_data = request.execute(method='GET',
                                        url=url,
                                        headers=headers,
                                        params=params)
        answers = analyze_response(response_data)
        for an in answers:
            log.info('|LUIS| After analyzing data, we got [{}]'.format(
                an.replace('\n', '')))
        return answers, response_data['topScoringIntent'][
            'intent'], response_data['topScoringIntent']['score']
    except Exception as e:
        log.error(e)
Пример #5
0
def get_message(response_type):
    """
    Return a message from a sponsor intent
    :param response_type luis response
    """
    with open('hackupc/bienebot/responses/sponsors/sponsors_data.json'
              ) as json_data:
        data = json.load(json_data)

        intent = response_type['topScoringIntent']['intent']
        list_intent = intent.split('.')
        entities = response_type['entities']

        # Log stuff
        if entities:
            log_info = '|RESPONSE| About [{}] getting [{}]'.format(
                entities[0]['entity'], list_intent[1])
        else:
            log_info = '|RESPONSE| Getting [{}] about all sponsors'.format(
                list_intent[1])
        log.info(log_info)

        switcher = {
            'Which': which_sponsor,
            'Help': help_sponsor,
            'AllChallenges': all_challenges_sponsor,
            'Where': where,
            'Challenge': challenge,
            'Contact': contact
        }
        # Get the function from switcher dictionary
        func = switcher.get(list_intent[1], lambda: error.get_message())
        # Execute the function
        return func(data, entities)
Пример #6
0
def send_message(message, channel=SLACK_API_ORGANIZERS, web_client=None):
    """
    Send message.
    :param message: Text to send.
    :param channel: Channel where send.
    :param web_client: Slack web client.
    :return: Message sent.
    """
    if not web_client:
        web_client = slack.WebClient(token=SLACK_API_TOKEN, timeout=30)
    log.info('|Slack| Sent the following message in channel [{}]: [{}]'.format(channel, message.replace('\n', '')))
    return web_client.chat_postMessage(channel=channel, text=message)
Пример #7
0
def get_message():
    """
    Return a message from a non understood question or error
    :return error response
    """
    with open('hackupc/bienebot/responses/error/error_data.json') as json_data:
        data = json.load(json_data)

        # Log stuff
        log.info('|RESPONSE| Looking for [error] from JSON element')

        array = [random.choice(data['No response'])]
        return array
Пример #8
0
 def send_message(self, message, channel):
     """
     Send message
     :param message: text to send
     :param channel: channel where send
     :return: message sent
     """
     log.info(
         '|Slack| Sent the following message in channel [{}]: [{}]'.format(
             channel, message.replace('\n', '')))
     return self.client.api_call(SLACK_API_METHOD,
                                 channel=channel,
                                 text=message)
Пример #9
0
def when(data, entities):
    """
    Retrieve response for `when` question given a list of entities
    :param data: data
    :param entities: entities
    :return: array of responses
    """
    array = []
    if entities:
        place = entities[0]['resolution']['values'][0].lower()
        log.info('|RESPONSE|: About [{}] getting WHEN'.format(place))
        array.append(data['places'][place]['when'])
    else:
        array.append(data['default']['when'])
    return array
Пример #10
0
def what(data, entities):
    """
    Retrieve response for `what` question given a list of entities
    :param data: data
    :param entities: entities
    :return: array of responses
    """
    array = []
    if entities:
        activity = entities[0]['resolution']['values'][0].lower()
        log.info('|RESPONSE|: About [{}] getting WHAT'.format(activity))
        array.append(data['activities'][activity]['what'])
    else:
        array.append(data['default']['what'])
    return array
Пример #11
0
def how(data, entities):
    """
    Retrieve response for `how` question given a list of entities
    :param data: data
    :param entities: entities
    :return: array of responses
    """
    array = []
    if entities:
        logistic = entities[0]['resolution']['values'][0].lower()
        log.info('|RESPONSE|: About [{}] getting HOW'.format(logistic))
        array.append(data['logistic'][logistic]['how'])
    else:
        array.append(data['default']['how'])
    return array
Пример #12
0
def challenge(data, entities):
    """
    Retrieve response for `challenge` question given a list of entities
    :param data: data
    :param entities: entities
    :return: array of responses
    """
    array = []
    if entities:
        sponsor = entities[0]['entity'].lower()
        log.info('|RESPONSE|: About [{}] getting CHALLENGE'.format(sponsor))
        array.append(data['sponsors'][sponsor]['challenge'])
    else:
        array.append(data['default']['challenge'])
    return array
Пример #13
0
def get_message(response_type):
    """
    Return a message from a smalltalk intent
    :param response_type luis response
    """
    with open('hackupc/bienebot/responses/smalltalk/smalltalk_data.json') as json_data:
        data = json.load(json_data)

        intent = response_type['topScoringIntent']['intent']
        list_intent = intent.split('.')

        # Log stuff
        log.info('|RESPONSE| Looking for [{}] from JSON element'.format(list_intent[1]))

        array = [random.choice(data[list_intent[1]])]
        return array
Пример #14
0
 def retrieve_message(self):
     """
     Retrieve messages
     :return: text and channel message
     """
     for event in self.client.rtm_read():
         if event[
                 'type'] == 'message' and 'subtype' not in event and 'thread_ts' not in event:
             text = event['text']
             channel = event['channel']
             user = event['user']
             log.info(
                 '|Slack| Retrieved the following message from user [{}] in channel [{}]: [{}]'
                 .format(user, channel, text.replace('\n', '')))
             return text, channel, user
     return None, None, None
Пример #15
0
def run():
    """
    Run Biene Bot.
    :return: Biene bot ran
    """
    rtm_client = slack.get_rtm_client()
    try:
        slack.send_message(':bee: Biene Bot starting!')
        rtm_client.start()
    except Exception as e:
        log.exception(e)
        log.error(f'General error: {e}', notify=True)
    finally:
        log.info('|BIENE| Biene Bot stopped!')
        slack.send_message(':bee: Biene Bot stopped!')
        return
Пример #16
0
def exists_biene(response_data):
    """
    Check if there's any biene in the response
    :param response_data: response data
    :return: true if there is, false otherwise
    """
    try:
        query_input = response_data['query']
        if 'biene' in query_input.lower():
            log.info('|LUIS| BIENE detected')
            return True
        else:
            return False
    except Exception as e:
        # Log error and return default error message
        log.error(e)
        return False
Пример #17
0
def get_message(response_type):
    """
    Return a message from a meals intent
    :param response_type luis response
    """
    with open('hackupc/bienebot/responses/meals/meals_data.json') as json_data:
        data = json.load(json_data)

        intent = response_type['topScoringIntent']['intent']
        list_intent = intent.split('.')

        # Log stuff
        log.info('|RESPONSE| Looking for [{}] from JSON element'.format(
            list_intent[1]))

        if list_intent[1] == 'Help' or list_intent[1] == 'Schedule':
            array = ['\n'.join(data[list_intent[1]])]
        else:
            array = [random.choice(data[list_intent[1]])]

        return array