def facebookBot(request):
    try:
        if 'hub.verify_token' in request.GET:
            if request.GET['hub.verify_token'] == models.Config.get('FacebookVerifyToken'):
                if 'hub.challenge' in request.GET:
                    return HttpResponse(request.GET['hub.challenge'])
                return HttpResponse("KO")
        body = json.loads(request.body)
        for entry in body['entry']:
            for message in entry['messaging']:
                if 'is_echo' not in message and 'message' in message:
                    senderId = message['sender']['id']
                    client = Wit(access_token=models.Config.get('WitToken'), actions=actions)
                    client.run_actions("session_%s" % senderId, message['message']['text'], {'senderId': senderId})
    except Exception, e:
        traceback.print_exc()
Example #2
0
class WitBot():
    def __init__(self, witai_key, say_func):
        actions = {
            'say': say_func,
            'merge': self.merge,
            'error': self.error,
            'get_trip': self.get_trip,
            'clear_context': self.clear_context,
        }
        self._wit_client = Wit(witai_key, actions)
        self._caldb = CalDbInterface()

    def chat(self, username, timezone, input_msg, session_id, context={}):
        if 'messenger_id' not in context:
            context['messenger_id'] = username

        if 'timezone' not in context:
            context['timezone'] = 'America/Los_Angeles'

        context = self._wit_client.run_actions(session_id, input_msg, context)
        return context

    def merge(self, session_id, cxt, entities, msg):
        logger.info(json.dumps(cxt, indent=4))
        for name, vals in entities.items():
            if name == 'caltrain_station_start':
                cxt['start_stop'] = vals[0]
            elif name == 'caltrain_station_end':
                cxt['end_stop'] = vals[0]
            elif name == 'datetime':
                cxt['stated_time'] = vals[0]

        return cxt

    def error(self, session_id, cxt, e):
        logger.error('Wit.ai error occurred.')
        raise e

    def clear_context(self, session_id, cxt):
        new_cxt = {
            'messenger_id': cxt['messenger_id'],
            'timezone': cxt['timezone'],
        }
        return new_cxt

    def get_trip(self, session_id, cxt):
        stated_time = cxt.get('stated_time')['value']
        start_stop = cxt.get('start_stop')['value']
        end_stop = cxt.get('end_stop')['value']
        bullet = cxt.get('bullet')

        start_stop = station_mapping.get(start_stop)
        end_stop = station_mapping.get(end_stop)

        trip = self._caldb.get_trip(start_stop, end_stop, stated_time, bullet)

        cxt['train_time'] = trip['min_time']
        return cxt
Example #3
0
def main(arg1):
    query = arg1
    #query=raw_input("Query:")
    client = Wit(access_token=access_token, actions=actions)

    #client.interactive()

    msg = client.run_actions('session1', query, {})
    #pprint(msg)

    #if 'msg' in msg:
    #   print msg['msg']
    if 'type' in msg:
        while msg['type'] != 'stop':
            if 'msg' not in msg:
                pass
            else:
                print msg['msg']
            msg = client.run_actions('test_session', query, {})
Example #4
0
def send_message(recipient, text):

    client = Wit(WITAI_TOKEN, actions)

    session_id = 'my-user-id-42'
    context0 = client.run_actions(session_id, text, {})
    print(context0)

    data = {
        "recipient": {"id": recipient},
        "message": {"text": WitAi_returnMessage}
    }
    resp = requests.post("https://graph.facebook.com/v2.6/me/messages?access_token=" + ACCESS_TOKEN, json=data)
    print(resp.content)
Example #5
0
class WitAi(object):

    __ENTITIES_TAG = 'entities'
    __DEFAULT = None

    def __init__(self, access_token, actions):
        self.__wit_client = Wit(access_token, actions)

    def analyze(self, msg):
        return self.__wit_client.message(msg)

    def get_entities(self, msg):
        return self.__wit_client.message(msg).get(self.__ENTITIES_TAG,
                                                  self.__DEFAULT)

    def talk(self, session_id, msg, context):
        return self.__wit_client.run_actions(session_id, msg, context)
Example #6
0
class WitMiddleware(MiddlewareMixin):
    WIT_DATA_KEY = "_wit"
    WIT_CONTEXT_KEY = "_context"

    def __init__(self, *args, **kwargs):
        from wit import Wit
        self.access_token = kwargs.pop("access_token", None)
        self.actions = kwargs.pop("actions", {})
        self.client = Wit(access_token=self.access_token, actions=self.actions)
        super().__init__(*args, **kwargs)

    def process_request(self, request: BotRequest):
        if request.text:
            user_data = request.user_storage.get(request.user_id)
            wit_data = user_data.get(self.WIT_DATA_KEY, {})
            context = wit_data.get(self.WIT_CONTEXT_KEY, {})

            result_context = self.client.run_actions(str(request.user_id), request.text, context)
            wit_data[self.WIT_CONTEXT_KEY] = result_context
Example #7
0
def processText(token, text, sessionId, funcs=None, context=None):
    out = []
    
    def say(session_id, context, msg):
        out.append(msg)

    def error(session_id, context, msg):
        print(u"aiwitutils.processText.error: [{msg}]".format(msg=msg))
        pass
    
    actions = dict(funcs) if isinstance(funcs, dict) else {}
    actions["say"] = say
    actions["error"] = error
    
    if "merge" not in actions:
        actions["merge"] = _mergeDefault
    
    client = Wit(token, actions)
    
    inCtx = context if context else {}
    
    outerCtx = client.run_actions(sessionId, text, inCtx)

    return (out, outerCtx)
Example #8
0
class WitSystem():
    def __init__(self):
        self.owm = OWM(OWM_API, language='ru')
        actions = {
            'send': self.send,
            'getForecast': self.get_forecast,
            'getExtraForecast': self.get_extra_forecast,
            'clearStory': self.clear_story
        }
        self.client = Wit(access_token=WIT_TOKEN, actions=actions)
        self.contexts = {}
        self.context_answer = {}

    def first_entity_value(self, entities, entity):
        if entity not in entities:
            return None
        val = entities[entity][0]['value']
        if not val:
            return None
        return val['value'] if isinstance(val, dict) else val

    def send(self, request, response):
        print(response['text'].decode('utf-8'))
        logger.info('Info "%s" "%s" "%s"' % (response['text'].decode('utf-8'), str(request), str(response)))
        self.context_answer[request['session_id']] = response

    def recive(self, chat_id, message, max_steps=DEFAULT_MAX_STEPS):
        if chat_id not in self.contexts:
            self.contexts[chat_id] = {}
        self.contexts[chat_id] = self.client.run_actions(chat_id, message, self.contexts[chat_id], max_steps)
        return self.context_answer[chat_id]

    def get_forecast(self, request):
        context = request['context']
        entities = request['entities']

        loc = self.first_entity_value(entities, 'location')
        if loc:
            observation = self.owm.weather_at_place(loc)
            w = observation.get_weather()
            context['forecast'] = w.get_status() 
            context['location'] = loc

            if context.get('missingLocation') is not None:
                del context['missingLocation']
        else:
            context['missingLocation'] = True
            if context.get('forecast') is not None:
                del context['forecast']

        return context

    def get_extra_forecast(self, request):
        context = request['context']
        entities = request['entities']
        location = context['location']

        observation = self.owm.weather_at_place(location)
        w = observation.get_weather()
        temperature = w.get_temperature(unit='celsius')
        weather_temp = ' '.join(map(str, (temperature['temp_min'],temperature['temp'],temperature['temp_max'])))
        humidity = str(w.get_humidity())

        context['extraForecast'] = 'В '+ location + ' температура:' +weather_temp + ' влажность:' + humidity
        return context

    def clear_story(self, request):
        context = request['context']
        entities = request['entities']

        if context.get('missingLocation') is not None:
            del context['missingLocation']
        if context.get('forecast') is not None:
            del context['forecast']
        if context.get('extraForecast') is not None:
            del context['extraForecast']
        return context
Example #9
0
from wit import Wit

access_token = 'YOUR_ACCESS_TOKEN'


def say(session_id, msg):
    print(msg)


def merge(context, entities):
    return context


def error(session_id, msg):
    print('Oops, I don\'t know what to do.')

actions = {
    'say': say,
    'merge': merge,
    'error': error,
}
client = Wit(access_token, actions)

session_id = 'my-user-id-42'
client.run_actions(session_id, 'your message', {})
        return None
    val = entities[entity][0]['value']
    if not val:
        return None
    return val['value'] if isinstance(val, dict) else val

def say(session_id, context, msg):
    print(msg)

def merge(session_id, context, entities, msg):
    # print entities
    print entities
    dest = first_entity_value(entities, 'dest')
    if dest:
        context['dest'] = dest
    return context

def error(session_id, context, e):
    print(str(e))

actions = {
    'say': say,
    'merge': merge,
    'error': error
}

client = Wit(access_token, actions)
response = client.run_actions(session_id="xyz",message="I'm planning to go to usa", max_steps=3, context={})

print response
def say(session_id, context, msg):
    print(msg)

def merge(session_id, context, entities, msg):
    loc = first_entity_value(entities, 'location')
    if loc:
        context['loc'] = loc
    return context

def error(session_id, context, e):
    print(str(e))

def fetch_weather(session_id, context):
    location = context['loc']
    location_id = pywapi.get_loc_id_from_weather_com(location)[0][0]
    weather_com_result = pywapi.get_weather_from_weather_com(location_id)
    context['forecast'] = weather_com_result["current_conditions"]["text"]
    return context

actions = {
    'say': say,
    'merge': merge,
    'error': error,
    'fetch-weather': fetch_weather,
}
client = Wit(access_token, actions)

session_id = 'YOUR_WIT_USERNAME_HERE'
place = raw_input("Enter City Name:")
client.run_actions(session_id, 'weather in %s'%place, {})
Example #12
0
        return None
    return val['value'] if isinstance(val, dict) else val


def say(session_id, context, msg):
    print(msg)


def merge(session_id, context, entities, msg):
    # print entities
    print entities
    dest = first_entity_value(entities, 'dest')
    if dest:
        context['dest'] = dest
    return context


def error(session_id, context, e):
    print(str(e))


actions = {'say': say, 'merge': merge, 'error': error}

client = Wit(access_token, actions)
response = client.run_actions(session_id="xyz",
                              message="I'm planning to go to usa",
                              max_steps=3,
                              context={})

print response
Example #13
0
from wit import Wit

# Weather example
# See https://wit.ai/patapizza/example-weather

access_token = 'YOUR_ACCESS_TOKEN'

def say(session_id, msg):
  print(msg)

def merge(context, entities):
  return context

def error(session_id, msg):
  print('Oops, I don\'t know what to do.')

def fetch_forecast(context):
  context['forecast'] = 'cloudy'
  return context

actions = {
    'say': say,
    'merge': merge,
    'error': error,
    'fetch-forecast': fetch_forecast,
    }
client = Wit(access_token, actions)

session_id = 'my-user-id-42'
client.run_actions(session_id, 'weather in London', {})
Example #14
0
        del context['joke']
    category = first_entity_value(entities, 'category')
    if category:
        context['cat'] = category
    sentiment = first_entity_value(entities, 'sentiment')
    if sentiment:
        context['ack'] = 'Glad you liked it.' if sentiment == 'positive' else 'Hmm.'
    elif 'ack' in context:
        del context['ack']
    return context

def error(session_id, context, e):
    print(str(e))

def select_joke(session_id, context):
    jokes = all_jokes[context['cat'] or 'default']
    shuffle(jokes)
    context['joke'] = jokes[0]
    return context

actions = {
    'say': say,
    'merge': merge,
    'error': error,
    'select-joke': select_joke,
}
client = Wit(access_token, actions)

session_id = 'my-user-id-42'
client.run_actions(session_id, 'tell me a joke about tech', {})
Example #15
0
        new_context['cat'] = category
    sentiment = first_entity_value(entities, 'sentiment')
    if sentiment:
        new_context['ack'] = 'Glad you liked it.' if sentiment == 'positive' else 'Hmm.'
    elif 'ack' in new_context:
        del new_context['ack']
    return new_context


def error(session_id, msg):
    print('Oops, I don\'t know what to do.')


def select_joke(context):
    new_context = dict(context)
    jokes = all_jokes[new_context['cat'] or 'default']
    shuffle(jokes)
    new_context['joke'] = jokes[0]
    return new_context

actions = {
    'say': say,
    'merge': merge,
    'error': error,
    'select-joke': select_joke,
}
client = Wit(access_token, actions)

session_id = 'my-user-id-42'
client.run_actions(session_id, 'tell me a joke about tech', {})
Example #16
0
                                 (loc['value'], (date['from'] + datetime.timedelta(days=d)).date().strftime('%B %d, %Y')
                                  , weather2string(weather[d]))))
                if len(weather) < (date['to'].date() - date['from'].date()).days + 1:
                    if len(weather) > 1:
                        say('', {}, 'Sorry, I can only get forecast up to %d days now' % len(weather))
                    else:
                        say('', {}, 'Sorry, I can only get forecast up to 1 day now')
            else:
                say('', {}, ('I cannot get forecast for %s' % loc['value']))
    context = {}
    say(None, None, 'Would you like the forecast for other location?')
    return context

actions = {
    'say': say,
    'merge': merge,
    'error': error,
    'get_weather_info': get_weather_info,
    }

if __name__ == '__main__':
    bot = Wit(access_token, actions)
    msg = ''
    context = {}
    print 'Tip: enter \'end\' to exit..ahihi'
    while True:
        msg = raw_input(">> You: ")
        if msg == 'end':
            break
        context = bot.run_actions(session_id, msg, context)
Example #17
0
    'MyFileOpen': get_fileopen,
    'MyFileExecBool': get_fileexecBool,
    'MyFileExecList': get_fileexeclist,
}

client = Wit(access_token="UBTCYTFGDP3K3DJIGRV462NLNG2MM4I7", actions=actions)
# # client.interactive()
client.logger.setLevel(logging.WARNING)
# #resp = client.message('play katy')
# print('Yay, got Wit.ai response: ' + str(resp))
# f = open('file.txt')

session_id = 'f0607fe6-aa6f-11e6-b121-3417eb627e2d'
context = pickle.load(open('context.pkl', "r"))
# print context, "in run action"
file = open('file.txt', 'r')
query = file.read()
file.close()
context = client.run_actions(session_id, query, context)
# context = client.run_actions(session_id, 'yes', context)
# print('The session state is now: ' + str(context))
pickle.dump(context, open('context.pkl', 'w'))
# print context , "final"

#resp = client.converse('my-user-session-42', 'play katy', {})
#print('Yay, got Wit.ai response: ' + str(resp))
#resp = client.converse('my-user-session-42', 'play panjaa', {})
#print('Yay, got Wit.ai response: ' + str(resp))
# def chat_bot( client, context, session_id, query):
# context = client.run_actions(session_id, query, context)
Example #18
0
    if not val:
        return None
    return val['value'] if isinstance(val, dict) else val

def say(session_id, msg):
    print(msg)

def merge(session_id, context, entities, msg):
    loc = first_entity_value(entities, 'location')
    if loc:
        context['loc'] = loc
    return context

def error(session_id, context, e):
    print(str(e))

def fetch_weather(session_id, context):
    context['forecast'] = 'sunny'
    return context

actions = {
    'say': say,
    'merge': merge,
    'error': error,
    'fetch-weather': fetch_weather,
}
client = Wit(access_token, actions)

session_id = 'my-user-id-42'
client.run_actions(session_id, 'weather in London', {})
Example #19
0
from wit import Wit

access_token = 'YOUR_ACCESS_TOKEN'


def say(session_id, msg):
    print(msg)


def merge(context, entities):
    return context


def error(session_id, msg):
    print('Oops, I don\'t know what to do.')


actions = {
    'say': say,
    'merge': merge,
    'error': error,
}
client = Wit(access_token, actions)

session_id = 'my-user-id-42'
client.run_actions(session_id, 'your message', {})
Example #20
0
def zero_context(session_id, context):
    context = {}
    return context


def dave_here(session_id, context):
    say(session_id, context, 'Reached dave_here()')


actions = {
    'say': say,
    'merge': merge,
    'error': error,
    'fetch-weather': fetch_weather,
    'zero_context': zero_context,
    'dave_here': dave_here,
}

client = Wit(access_token, actions)

session_id = 'my-user-session-42'
context0 = {}
context1 = client.run_actions(session_id, 'what is the weather in London?',
                              context0)
print('The session state is now: ' + str(context1))
context2 = client.run_actions(session_id, 'and in Brussels?', context1)
print('The session state is now: ' + str(context2))

#client.interactive()
Example #21
0
class BillyBob:
    @classmethod
    def wit_send(cls, request, response):
        print 'Getting from user... {0}'.format(request)
        print 'Sending to user... {0}'.format(response['text'])

    def _post_simple(self, channel, msg):
        self.slack_client.api_call("chat.postMessage",
                                   channel=channel,
                                   text=msg,
                                   as_user=True)

    def _post_fmt(self, channel, text, attachments):
        self.slack_client.api_call("chat.postMessage",
                                   channel=channel,
                                   text=text,
                                   attachments=attachments,
                                   as_user=True)

    @classmethod
    def _check_intent(cls, intent, key_intent):
        return intent['entities'] and intent['entities'][key_intent]

    @classmethod
    def _fmt_prs(cls, prs, repo):
        return [{
            'text':
            '<{0}|{1}>: <{2}|{3}>'.format(p['url'], p['repo_name'],
                                          p['pr_url'], p['title']),
            'fallback':
            '{0}: {1}'.format(p['repo_name'], p['title']),
            'color':
            'warning'
        } for p in prs[repo]]

    def wit_get_prs(self, params):
        chan = params['context']['chan'].encode("ascii", "ignore")
        print 'requested get_prs ! {0}'.format(params)
        if self._check_intent(params, 'pull_request'):
            entities = params['entities']['pull_request']
            if len(entities) == 1 and entities[0]['value']:
                repo = entities[0]['value']
                if repo == 'github':
                    prs = fetch_pr.get_prs('github')
                    prs_fmt = self._fmt_prs(prs, 'github')
                    self._post_fmt(
                        chan, 'Here are the open pull requests on Github !',
                        prs_fmt)
                elif repo == 'bitbucket':
                    prs = fetch_pr.get_prs('bitbucket')
                    prs_fmt = self._fmt_prs(prs, 'bitbucket')
                    self._post_simple(
                        chan, "Sorry bruh I don't know how to do that yet :(")
                elif repo == 'everywhere':
                    prs = fetch_pr.get_prs('everywhere')
                    prs_fmt_bitbucket = self._fmt_prs(prs, 'bitbucket')
                    prs_fmt_github = self._fmt_prs(prs, 'github')
                    self._post_simple(
                        chan,
                        "You asked for the pull requests on github and bitbucket..."
                    )
                    if len(prs_fmt_bitbucket) > 0:
                        self._post_fmt(chan, '', prs_fmt_bitbucket)
                    if len(prs_fmt_github) > 0:
                        self._post_fmt(chan, '', prs_fmt_github)
                else:
                    self._post_simple(chan, 'WTF is that ?')
        return {}

    def wit_get_bus_tt(self, params):
        red_color = "#ff0000"
        green_color = "#36a64f"
        chan = params['context']['chan'].encode("ascii", "ignore")
        buses = sophiabus230.get_next_buses()
        attachments = []
        tz = gettz('Europe/Paris')
        time_now = datetime.datetime.now(tz=tz)
        for passage in buses:
            attachment = {}
            bus_time = passage['bus_time']
            dest = passage['dest']
            diff_t = bus_time.replace(tzinfo=tz) - time_now
            minutes = int(diff_t.total_seconds() / 60)
            att_str = 'In {0} min (at {1}) towards {2}'.format(
                minutes, bus_time.strftime("%H:%M"), dest)
            if passage['is_real_time']:
                attachment['color'] = red_color
            else:
                attachment['color'] = green_color
            attachment['text'] = att_str
            attachment['fallback'] = att_str
            attachments.append(attachment)
        self._post_fmt(chan, "Here are the next bus passages cowboy !",
                       attachments)
        return {}

    def __init__(self, slack_token=None, wit_token=None, **kargs):
        self.BOT_NAME = 'BillyBob'
        # TODO: get the BOT_ID at runtime
        self.BOT_ID = 'U1ZUKEDT4'
        if slack_token is None:
            self.slack_token = os.environ['SLACK_API_TOKEN']
        else:
            self.slack_token = slack_token
        if wit_token is None:
            self.wit_token = os.environ['WIT_API_TOKEN']
        else:
            self.wit_token = wit_token
        self._params = kargs
        if 'wit_actions' in kargs:
            actions = kargs['wit_actions']
        else:
            actions = {
                'send': self.wit_send,
                'get_prs': self.wit_get_prs,
                'get_bus_tt': self.wit_get_bus_tt
            }
        logging.basicConfig(format='%(asctime)s %(levelname)s '
                            '[%(filename)s:%(lineno)d] %(message)s')
        self.slack_client = SlackClient(self.slack_token)
        self.wit_client = Wit(access_token=self.wit_token, actions=actions)

    def _parse_slack_output(self, slack_rtm_output):
        at_bot = "<@{0}>".format(self.BOT_ID)
        output_list = slack_rtm_output
        if output_list and len(output_list) > 0:
            for output in output_list:
                print 'command: {0}'.format(output)
                if output and 'text' in output and at_bot in output['text']:
                    cmd = output['text'].split(at_bot)[1].strip().lower()
                    chan = output['channel']
                    print 'detected cmd: {0}'.format(cmd)
                    return cmd, chan
        return None, None

    def handle_command(self, command, chan):
        self.wit_client.run_actions('titoi', command, {'chan': chan})

    def start_service(self):
        print 'Waking up {0}...'.format(self.BOT_NAME)
        if self.slack_client.rtm_connect():
            print '{0} is connected !'.format(self.BOT_NAME)
            while True:
                read_payload = self.slack_client.rtm_read()
                command, chan = self._parse_slack_output(read_payload)
                if command:
                    self.handle_command(command, chan)
                time.sleep(1)
        else:
            print "Connection failed. Invalid tokens ?"
Example #22
0
def converse(msg):
    client = Wit(WIT_AI_KEY, actions)
    client.run_actions(session_id, msg)
def merge(session_id, context, entities, msg):
    loc = first_entity_value(entities, 'location')
    if loc:
        context['loc'] = loc
    return context


def error(session_id, context, e):
    print(str(e))


def fetch_weather(session_id, context):
    location = context['loc']
    location_id = pywapi.get_loc_id_from_weather_com(location)[0][0]
    weather_com_result = pywapi.get_weather_from_weather_com(location_id)
    context['forecast'] = weather_com_result["current_conditions"]["text"]
    return context


actions = {
    'say': say,
    'merge': merge,
    'error': error,
    'fetch-weather': fetch_weather,
}
client = Wit(access_token, actions)

session_id = 'YOUR_WIT_USERNAME_HERE'
place = raw_input("Enter City Name:")
client.run_actions(session_id, 'weather in %s' % place, {})
Example #24
0
    credential = credentials.get("witai", "ServerAccessToken")
    client = Wit(credential, actions)

    session_id = 'my-user-id-42'

    while True:

        luxes = light.value()
        luxes = int(luxes)    
        display.setColor(luxes, luxes, luxes)

        if button.value() is 1:
            isay("english", "Hi! This is GiekIe! How can I help?")
            message = recognizeSpeech()
            display.clear()
            display.setCursor(0,0)
            display.write(str(message))
            client.run_actions(session_id, message, {})

    #updater.idle()

'''
        luxes = light.value()
        display.setColor(255, 0, 0)
        display.setCursor(0,0)
        display.write('Light ' + str(luxes))
        print 'Light ' + str(luxes)
        time.sleep(1)
'''