Exemple #1
0
    def test_session_manager(self):
        from chatbot.server.session import SessionManager
        session_manager = SessionManager(False)
        sid = session_manager.start_session(user='******', key='key', test=True)
        session = session_manager.get_session(sid)
        self.assertIsNotNone(session)
        self.assertIsNone(session.cache.last_time)

        self.assertTrue(session.add("hi", "hi there"))
        self.assertIsNotNone(session.cache.last_time)

        session_manager.reset_session(sid)
        self.assertIsNotNone(session)
        self.assertIsNone(session.cache.last_time)

        session_manager.remove_session(sid)
        self.assertFalse(session.add("hi", "hi there"))
        session = session_manager.get_session(sid)
        self.assertIsNone(session)
Exemple #2
0
    def test_session_manager(self):
        from chatbot.server.session import SessionManager
        session_manager = SessionManager(False)
        sid = session_manager.start_session(user='******', test=True)
        session = session_manager.get_session(sid)
        self.assertIsNotNone(session)
        self.assertIsNone(session.cache.last_time)

        self.assertTrue(session.add("hi", "hi there"))
        self.assertIsNotNone(session.cache.last_time)

        session_manager.reset_session(sid)
        self.assertIsNotNone(session)
        self.assertIsNone(session.cache.last_time)

        session_manager.remove_session(sid)
        self.assertFalse(session.add("hi", "hi there"))
        session = session_manager.get_session(sid)
        self.assertIsNone(session)
Exemple #3
0
class HRSlackBot(object):
    def __init__(self, host, port, botname, **kwargs):
        self.sc = SlackClient(SLACKBOT_API_TOKEN)
        self.sc.rtm_connect()
        self.botname = botname
        self.host = host
        self.port = str(port)
        self.lang = 'en'
        self.icon_url = 'https://avatars.slack-edge.com/2016-05-30/46725216032_4983112db797f420c0b5_48.jpg'
        self.session_manager = SessionManager()
        self.weights = kwargs.get('weights')
        self.enable_trace = kwargs.get('enable_trace')

    def send_message(self, channel, attachments):
        self.sc.api_call("chat.postMessage",
                         channel=channel,
                         attachments=attachments,
                         username=self.botname.title(),
                         icon_url=self.icon_url)

    def error(self, channel, msg):
        attachments = [{'title': msg, 'color': 'danger', 'fallback': msg}]
        logger.error(msg)
        self.send_message(channel, attachments)

    def info(self, channel, msg):
        attachments = [{'title': msg, 'color': '#36a64f', 'fallback': msg}]
        logger.info(msg)
        self.send_message(channel, attachments)

    def run(self):
        while True:
            time.sleep(0.2)
            messages = self.sc.rtm_read()
            if not messages:
                continue
            for message in messages:
                if message['type'] != u'message':
                    continue
                if message.get('subtype') == u'bot_message':
                    continue
                usr_obj = self.sc.api_call('users.info',
                                           token=SLACKTEST_TOKEN,
                                           user=message['user'])
                if not usr_obj['ok']:
                    continue
                profile = usr_obj['user']['profile']
                name = profile.get('first_name') or profile.get('email')
                question = message.get('text')
                channel = message.get('channel')

                sid = self.session_manager.get_sid(name, self.botname)
                session = self.session_manager.get_session(sid)
                if session is not None:
                    assert hasattr(session.session_context, 'client')
                    client = session.session_context.client
                else:
                    client = Client(HR_CHATBOT_AUTHKEY,
                                    username=name,
                                    botname=self.botname,
                                    host=self.host,
                                    port=self.port,
                                    response_listener=self)
                    client.set_marker('Slack')
                    if self.weights:
                        client.set_weights(self.weights)
                    self.session_manager.add_session(name, self.botname,
                                                     client.session)
                    session = self.session_manager.get_session(client.session)
                    if session is not None:
                        session.session_context.client = client
                        session.session_context.channel = channel
                        self.info(
                            channel,
                            "Session <{url}/v2.0/session_history?session={sid}&Auth={auth}|{sid}>"
                            .format(url=CHATBOT_SERVER_URL,
                                    sid=session.sid,
                                    auth=HR_CHATBOT_AUTHKEY))
                    else:
                        self.error(channel, "Can't get session")
                        continue

                logger.info("Question {}".format(question))
                if question in [':+1:', ':slightly_smiling_face:', ':)', 'gd']:
                    ret, _ = client._rate('good')
                    if ret:
                        logger.info("Rate good")
                        answer = 'Thanks for rating'
                        color = 'good'
                    else:
                        logger.info("Rate failed")
                        answer = 'Rating failed'
                        color = 'danger'
                    attachments = [{
                        'title': answer,
                        'color': color,
                        'fallback': answer
                    }]
                    self.send_message(channel, attachments)
                    continue
                if question in [':-1:', ':disappointed:', ':(', 'bd']:
                    ret, _ = client._rate('bad')
                    if ret:
                        logger.info("Rate bad")
                        answer = 'Thanks for rating'
                        color = 'good'
                    else:
                        logger.info("Rate failed")
                        answer = 'Rating failed'
                        color = 'danger'
                    attachments = [{
                        'title': answer,
                        'color': color,
                        'fallback': answer
                    }]
                    self.send_message(channel, attachments)
                    continue

                try:
                    client.ask(question)
                except Exception as ex:
                    self.error(channel, ex.message)

                # session could change after ask
                if client.session != session.sid:
                    self.session_manager.remove_session(session.sid)
                    self.session_manager.add_session(name, self.botname,
                                                     client.session)
                    session = self.session_manager.get_session(client.session)
                    session.session_context.client = client
                    session.session_context.channel = channel
                    self.info(
                        channel,
                        "Session <{url}/v2.0/session_history?session={sid}&Auth={auth}|{sid}>"
                        .format(url=CHATBOT_SERVER_URL,
                                sid=session.sid,
                                auth=HR_CHATBOT_AUTHKEY))
                    logger.info("Session is updated")

    def on_response(self, sid, response):
        answer = ''
        title = ''
        session = self.session_manager.get_session(sid)
        if session is None:
            time.sleep(0.5)
            session = self.session_manager.get_session(sid)
            if session is None:
                logger.error("No such session {}".format(session))
                return
        channel = session.session_context.channel
        if response is None or not response.get('text'):
            answer = u"Sorry, I can't answer it right now"
        else:
            answer = response.get('text')
            trace = response.get('trace', '')
            botid = response.get('botid', '')
            if trace and self.enable_trace:
                formated_trace = format_trace(trace)
                if formated_trace:
                    title = 'answered by {}\n\ntrace:\n{}'.format(
                        botid, '\n'.join(formated_trace))
        attachments = [{
            'pretext': answer,
            'title': title,
            'color': '#3AA3E3',
            'fallback': answer,
        }]
        self.send_message(channel, attachments)
Exemple #4
0
class HRSlackBot(object):

    def __init__(self, host, port, botname, **kwargs):
        self.sc = SlackClient(SLACKBOT_API_TOKEN)
        self.sc.rtm_connect()
        self.botname = botname
        self.host = host
        self.port = str(port)
        self.lang = 'en'
        self.icon_url = 'https://avatars.slack-edge.com/2016-05-30/46725216032_4983112db797f420c0b5_48.jpg'
        self.session_manager = SessionManager()
        self.weights = kwargs.get('weights')

    def send_message(self, channel, attachments):
        self.sc.api_call(
            "chat.postMessage", channel=channel,
            attachments=attachments, username=self.botname.title(),
            icon_url=self.icon_url)

    def error(self, channel, msg):
        attachments = [{
            'title': msg,
            'color': 'danger',
            'fallback': msg
        }]
        logger.error(msg)
        self.send_message(channel, attachments)

    def info(self, channel, msg):
        attachments = [{
            'title': msg,
            'color': '#36a64f',
            'fallback': msg
        }]
        logger.info(msg)
        self.send_message(channel, attachments)

    def run(self):
        while True:
            time.sleep(0.2)
            messages = self.sc.rtm_read()
            if not messages:
                continue
            for message in messages:
                if message['type'] != u'message':
                    continue
                if message.get('subtype') == u'bot_message':
                    continue
                usr_obj = self.sc.api_call(
                    'users.info', token=SLACKTEST_TOKEN, user=message['user'])
                if not usr_obj['ok']:
                    continue
                profile = usr_obj['user']['profile']
                name = profile.get('first_name') or profile.get('email')
                question = message.get('text')
                channel = message.get('channel')

                sid = self.session_manager.get_sid(name, self.botname)
                session = self.session_manager.get_session(sid)
                if session is not None:
                    assert hasattr(session.sdata, 'client')
                    client = session.sdata.client
                else:
                    client = Client(HR_CHATBOT_AUTHKEY, username=name,
                        botname=self.botname, host=self.host, port=self.port,
                        response_listener=self)
                    client.set_marker('Slack')
                    if self.weights:
                        client.set_weights(self.weights)
                    self.session_manager.add_session(name, self.botname, client.session)
                    session = self.session_manager.get_session(client.session)
                    if session is not None:
                        session.sdata.client = client
                        session.sdata.channel = channel
                        self.info(channel, "Session <{url}/v1.1/session_history?session={sid}&Auth={auth}|{sid}>".format(
                            url=CHATBOT_SERVER_URL, sid=session.sid, auth=HR_CHATBOT_AUTHKEY))
                    else:
                        self.error(channel, "Can't get session")
                        continue

                logger.info("Question {}".format(question))
                if question in [':+1:', ':slightly_smiling_face:', ':)', 'gd']:
                    ret, _ = client._rate('good')
                    if ret:
                        logger.info("Rate good")
                        answer = 'Thanks for rating'
                        color = 'good'
                    else:
                        logger.info("Rate failed")
                        answer = 'Rating failed'
                        color = 'danger'
                    attachments = [{
                        'title': answer,
                        'color': color,
                        'fallback': answer
                    }]
                    self.send_message(channel, attachments)
                    continue
                if question in [':-1:', ':disappointed:', ':(', 'bd']:
                    ret, _ = client._rate('bad')
                    if ret:
                        logger.info("Rate bad")
                        answer = 'Thanks for rating'
                        color = 'good'
                    else:
                        logger.info("Rate failed")
                        answer = 'Rating failed'
                        color = 'danger'
                    attachments = [{
                        'title': answer,
                        'color': color,
                        'fallback': answer
                    }]
                    self.send_message(channel, attachments)
                    continue

                try:
                    client.ask(question)
                except Exception as ex:
                    self.error(channel, ex.message)

                # session could change after ask
                if client.session != session.sid:
                    self.session_manager.remove_session(session.sid)
                    self.session_manager.add_session(
                        name, self.botname, client.session)
                    session = self.session_manager.get_session(client.session)
                    session.sdata.client = client
                    session.sdata.channel = channel
                    self.info(channel, "Session <{url}/v1.1/session_history?session={sid}&Auth={auth}|{sid}>".format(
                        url=CHATBOT_SERVER_URL, sid=session.sid, auth=HR_CHATBOT_AUTHKEY))
                    logger.info("Session is updated")

    def on_response(self, sid, response):
        answer = ''
        title = ''
        session = self.session_manager.get_session(sid)
        if session is None:
            time.sleep(0.5)
            session = self.session_manager.get_session(sid)
            if session is None:
                logger.error("No such session {}".format(session))
                return
        channel = session.sdata.channel
        if response is None or not response.get('text'):
            answer = u"Sorry, I can't answer it right now"
        else:
            answer = response.get('text')
            trace = response.get('trace', '')
            botid = response.get('botid', '')
            if trace:
                formated_trace = format_trace(trace)
                if formated_trace:
                    title = 'answered by {}\n\ntrace:\n{}'.format(botid, '\n'.join(formated_trace))
        attachments = [{
            'pretext': answer,
            'title': title,
            'color': '#3AA3E3',
            'fallback': answer,
        }]
        self.send_message(channel, attachments)