Exemple #1
0
def query_apiai(msg, log=True):
    request = ai.text_request()
    request.query = msg
    response = json.loads(request.getresponse().read())
    if log: print(response)
    result = response['result']
    action = result.get('action')  # check if chatbot had something to say
    reply = result['fulfillment']['speech'] if action else ''
    return (action, reply)
Exemple #2
0
def parse_user_text(user_text):
    '''
    Send the message to API AI which invokes an intent
    and sends the response accordingly
    '''
    request = ai.text_request()
    request.query = user_text
    response = json.loads(request.getresponse().read().decode('utf-8'))
    return response
Exemple #3
0
def parse_natural_event(event):
    e = apiai.events.Event(event)
    request = ai.event_request(e)
    #request.session_id = session_id  # unique for each user
    #request.contexts = contexts    # a list
    response = request.getresponse()
    #response = json.loads(request.getresponse().read().decode(‘utf-8’))
    print(response.read())
    return response
def speak_json(message):
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
    request = ai.text_request()
    request.session_id = "001"
    request.query = message
    response = request.getresponse()
    parsed = json.loads(response.read())
    #print(json.dumps(parsed, indent=4, sort_keys=True))
    return (parsed)
Exemple #5
0
def get_response(text, session_id):
    request = apia.text_request()
    request.lang = "ru"
    request.session_id = session_id
    request.query = text
    response = json.loads(request.getresponse().read().decode('utf-8'))
    try:
        return response['result']['fulfillment']['speech']
    except Exception:
        return "Произошла ошибка, попробуйте позже."
Exemple #6
0
def main(user_input):
    if user_input == 'exit':
        return ("Thank you and come again")

    request = ai.text_request()
    request.query = user_input
    response = json.loads(request.getresponse().read())
    result = response['result']
    fulfillment = result.get("fulfillment")
    return (fulfillment['speech'])
def apiai_route():
    ai = apiai.ApiAI("more secret")
    request = ai.text_request()
    request.lang = 'es'  # optional, default value equal 'en'
    request.session_id = "12"
    request.query = "Hello"
    response = request.getresponse()

    print(response.read())
    return "True"
Exemple #8
0
def main(query):
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.lang = 'en'  # optional, default value equal 'en'

    request.session_id = my_id
    request.query = query

    response = request.getresponse().read().decode('UTF-8');jsonobj = json.loads(response);return jsonobj;
Exemple #9
0
def parse_user_text(text):  #傳訊息給dialogflow並得到解析後的答案
    request = ai.text_request()
    request.query = text  #欲查詢的字串
    response = request.getresponse().read().decode(
        'utf-8')  #解讀API回傳的JSON檔案(用UTF8解碼)
    responseJson = json.loads(response)  #將json檔案轉為字典物件
    #字典結構:{'key':值}
    #印出dialogflow分析我傳過去的字串的結果的其中我所想要的項目和其內容
    #print(responseJson["result"]["parameters"]["action"])
    #print(type(responseJson["result"]["parameters"]["action"]))
    return responseJson
Exemple #10
0
def parse_natural_text(user_text):

    request = ai.text_request()
    request.query = user_text

    response = json.loads(request.getresponse().read().decode('utf-8'))
    responseStatus = response['status']['code']
    if (responseStatus == 200):
        return (response['result']['fulfillment']['speech'])

    else:
        return ("Sorry, I couldn't understand that question")
Exemple #11
0
def parse_user_text(user_text):
    '''
    Send the message to API AI which invokes an intent
    and sends the response accordingly
    '''
    request = ai.text_request()
    request.query = user_text
    #request.session_id = "123456789"
    response = request.getresponse().read().decode('utf-8')
    responseJson = json.loads(response)
    #print( json.dumps(responseJson["result"]["parameters"], indent=4) )
    return responseJson
Exemple #12
0
def textMessage(bot, update):
    request = apiai.ApiAI('05fbecb26f1349e0892e2f61f5970a52').text_request()
    request.lang = 'ru'
    request.session_id = 'The_Bobby_bot'
    request.query = update.message.text

    responseJson = json.loads(request.getresponse().read().decode('utf-8'))
    response = responseJson['result']['fulfillment']['speech']
    if response:
        bot.send_message(chat_id=update.message.chat_id, text=response)
    else:
        bot.send_message(chat_id=update.message.chat_id, text='Я Вас не совсем понял!')
Exemple #13
0
def parse_user_text(message_text):
	'''
	Send the message to API AI which invokes an intent
	and sends the response accordingly
	The bot response is appened with weaher data fetched from
	namaz client
	'''
	request = ai.text_request()
	request.query = message_text

	r = request.getresponse()
	response = json.loads(r.read().decode('utf-8'))
	response_status = response['status']['code']

	if response_status == 200:
		print ('Bot response '+ response['result']['fulfillment']['speech'])

		timings_namaz = ''

		input_city = response['result']['parameters'].get("geo-city")
		input_country = response['result']['parameters'].get("geo-country")

		if input_country and input_city:

			params = {'city' : input_city, 'country' : input_country}

			#extracting data from aladhan api
			resp = requests.get('http://api.aladhan.com/v1/timingsByCity', params=params)
			data = resp.json()

			fajr = str(data['data']['timings']['Fajr'])
			sunrise = str(data['data']['timings']['Sunrise'])
			dhuhr = str(data['data']['timings']['Dhuhr'])
			asr = str(data['data']['timings']['Asr'])
			maghrib = str(data['data']['timings']['Maghrib'])
			sunset = str(data['data']['timings']['Sunset'])
			isha = str(data['data']['timings']['Isha'])
			imsak = str(data['data']['timings']['Imsak'])
			midnight = str(data['data']['timings']['Midnight'])
			method = str(data['data']['meta']['method']['name'])

			timings_namaz = '\n Fajr : ' + fajr + '\n Sunrise : ' + sunrise + '\n Dhuhr : ' + dhuhr + '\n Asr : ' + asr + '\n Maghrib : ' + maghrib + '\n Sunset : ' + sunset + '\n Isha : ' + isha + '\n Imsak : ' + imsak + '\n Midnight : ' + midnight + '\n according to the calculation report of ' + method + '. '
			return (response['result']['fulfillment']['speech'] + timings_namaz)

		else:

			return response['result']['fulfillment']['speech']

	else:
		return 'Please try again'

	return 'Processed'
Exemple #14
0
def get_ai_rep(message):
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.session_id = "chatbot"

    request.query = message

    response = request.getresponse()
    response = json.loads(response.read())

    return response["result"]["fulfillment"]["messages"][0]["speech"]
def dialogflow_api(query=DEFAULT_QUERY):
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
    request = ai.text_request()
    request.lang = 'en'
    request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
    request.query = query
    response = json.loads(request.getresponse().read().decode('utf-8'))
    log.info("printing response from dialogflow")
    log.debug(pprint.pformat(response))
    pprint.pprint(response)
    message1 = response['result']['parameters']['Restaurant'][0]
    message2 = response['result']['parameters']['location'][0]['city']
    confidence = response['result']['score']
    return message1, message2, confidence
Exemple #16
0
def send_apiapi_request(message):

    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.session_id = "test"

    request.query = message

    response = json.loads(request.getresponse().read())

    print(response)
    return response
Exemple #17
0
def main3():
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.lang = 'de'  # optional, default value equal 'en'

    request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

    request.query = "Hello"

    response = request.getresponse()

    print(response.read())
Exemple #18
0
def APIAI_rec(texto):
    request = ai.text_request()
    request.lang = 'es'  # Lenguaje
    request.session_id = "_HOlaMundo_"
    request.query = texto
    response = request.getresponse()
    res = response.read()
    res = json.loads(res)
    datares = {
        'action': res['result']['action'],
        'message': res['result']['fulfillment']['messages'][0]['speech'],
        'parameters': res['result']['parameters']
    }
    return datares
Exemple #19
0
def parse_user_message(user_text):
    '''
    Send the message to API AI which invokes an intent
    and sends the response accordingly
    The bot response is appened with weaher data fetched from
    open weather map client
    '''

    request = ai.text_request()
    request.query = user_text

    response = json.loads(request.getresponse().read().decode('utf-8'))
    responseStatus = response['status']['code']
    if (responseStatus == 200):

        print("API AI response", response['result']['fulfillment']['speech'])
        try:
            #Using open weather map client to fetch the weather report
            weather_report = ''

            input_city = response['result']['parameters']['geo-city']
            print("City ", input_city)

            owm = pyowm.OWM('edd197717da7951b85f8f6936fc27b13'
                            )  # You MUST provide a valid API key

            forecast = owm.daily_forecast(input_city)

            observation = owm.weather_at_place(input_city)
            w = observation.get_weather()
            print(w)
            print(w.get_wind())
            print(w.get_humidity())
            max_temp = str(w.get_temperature('celsius')['temp_max'])
            min_temp = str(w.get_temperature('celsius')['temp_min'])
            current_temp = str(w.get_temperature('celsius')['temp'])
            wind_speed = str(w.get_wind()['speed'])
            humidity = str(w.get_humidity())

            weather_report = ' max temp: ' + max_temp + ' min temp: ' + min_temp + ' current temp: ' + current_temp + ' wind speed :' + wind_speed + ' humidity ' + humidity + '%'
            print("Weather report ", weather_report)

            return (response['result']['fulfillment']['speech'] +
                    weather_report)
        except:
            return (response['result']['fulfillment']['speech'])

    else:
        return ("Sorry, I couldn't understand that question")
Exemple #20
0
def api_ai_analysis(message):

    CLIENT_ACCESS_TOKEN = '20d6608f15444e52a123a644959f157a'
    ai = apiai.ApiAI('4db4733e1a1e4f8d882ba4e274178aa0')
    request = ai.text_request()
    request.lang = 'en'  # optional, default value equal 'en'
    request.query = message
    response = request.getresponse()
    data = json.loads(response.read())
    #print data
    response = str(data["result"]["fulfillment"]["speech"])
    symptom = str(data["result"]["parameters"]["symptoms"])
    age = str(data["result"]["parameters"]["age"]["unit"])
    gender = str(data["result"]["parameters"]["sex"])
    return response, symptom, gender, age
Exemple #21
0
def parse_natural_text(user_text):
    print('hi there!')
    # Sending a text query to our bot with text sent by the user.
    request = ai.text_request()
    request.query = user_text

    # Receiving the response.
    response = json.loads(request.getresponse().read().decode('utf-8'))
    responseStatus = response['status']['code']
    if (responseStatus == 200):
        # Sending the textual response of the bot.
        return (response['result']['fulfillment']['speech'])

    else:
        return ("Sorry, I couldn't understand that question")
Exemple #22
0
def bot(text):

    request = apiai.ApiAI('095918504b2548468d783679235c10e0').text_request(
    )  # Токен API к Dialogflow
    request.lang = 'ru'  # На каком языке будет послан запрос
    request.session_id = 'BatlabAIBot'  # ID Сессии диалога (нужно, чтобы потом учить бота)
    request.query = text  # Посылаем запрос к ИИ с сообщением от юзера
    responseJson = json.loads(request.getresponse().read().decode('utf-8'))
    response = responseJson['result']['fulfillment'][
        'speech']  # Разбираем JSON и вытаскиваем ответ
    # Если есть ответ от бота - присылаем юзеру, если нет - бот его не понял
    if response:
        return response
    else:
        return 'Нет ответа'
Exemple #23
0
def api_ai_analysis(message):

    CLIENT_ACCESS_TOKEN = 'f2c3166a316843ca95e399a19333c873'
    ai = apiai.ApiAI('31df623f4c1846209c287dc9e8f36a2e')
    request = ai.text_request()
    request.lang = 'en'  # optional, default value equal 'en'
    request.query = message
    response = request.getresponse()
    data = json.loads(response.read())
    #print data
    response = str(data["result"]["fulfillment"]["speech"])
    symptom = str(data["result"]["parameters"]["symptoms"])
    age = str(data["result"]["parameters"]["age"]["unit"])
    gender = str(data["result"]["parameters"]["sex"])
    return response, symptom, gender, age
def say_welcome():
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
    request = ai.event_request(apiai.events.Event("welcome"))
    response = request.getresponse()
    parsed = json.loads(response.read())
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit(
        'bot_response', {
            'data': parsed['result']['fulfillment']['speech'],
            'count': session['receive_count']
        })
    emit('bot_request', {
        'data': 'User asked for a hifive',
        'count': session['receive_count']
    })
Exemple #25
0
def api_ai_query(text, comment_id):
    logging.info("Api AI entered")
    request = ai.text_request()
    request.query = text
    response = json.loads(request.getresponse().read().decode('utf-8'))
    responseStatus = response['status']['code']
    if (responseStatus == 200):
        response = response['result']['fulfillment']['speech']
        query(update_query_apiai, (response, comment_id))
        logging.info("api ai returning")
        return response
    else:
        response = "Sorry, I couldn't understand that question"
        query(update_query_apiai, (response, comment_id))
        logging.info("api ai returning")
        return response
Exemple #26
0
def get_response(message, session_id):
    """ Get response from AI

    :param message:
    :param session_id:
    :rtype tuple:
    """
    ai = AI.ApiAI(CLIENT_ACCESS_TOKEN)
    request = ai.text_request()
    request.session_id = session_id
    request.query = message
    response = json.loads(request.getresponse().read())
    action = response['result']['action']
    speech = response['result']['fulfillment']['speech']

    return action, speech
Exemple #27
0
    def request_analyze(self, session_id, msg):
        """Request text analysis by Chatbot API.

        Args:
            session_id: Chatbot Session ID. Made of sender_id + app start time.
            msg: Text to analyze.

        Returns:
            str or HTTP Stream: Analyzed result in JSON format.
        """
        request = self.ai.text_request()
        request.lang = 'en'
        request.session_id = session_id
        request.query = msg
        response = request.getresponse()
        return response
Exemple #28
0
    def trigger_event(self, session_id, event_name):
        """Trigger Chatbot event to proceed next intent.

        Args:
            session_id: Chatbot Session ID. Made of sender_id + app start time.
            event_name: Name of event.

        Returns:
            str or HTTP Stream: Analyzed result in JSON format.
        """
        event = events.Event(event_name)
        request = self.ai.event_request(event)
        request.lang = 'en'
        request.session_id = session_id
        response = request.getresponse()
        return response
Exemple #29
0
def process_text_message(msg):
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
    request = ai.text_request()
    request.lang = 'en'  # optional, default value equal 'en'
    request.session_id = "Ajf54Trh"
    request.query = msg

    response = json.loads(request.getresponse().read().decode('utf-8'))
    log(response)
    responseStatus = response['status']['code']
    if (responseStatus == 200):
        # Sending the textual response of the bot.
        return (response['result']['fulfillment']['speech'])

    else:
        return ("Sorry, I couldn't understand that question")
Exemple #30
0
def main(query, sessionid):
    ai = apiai.ApiAI('13537e5537c543b78b713852b76ff0f3 ')

    request = ai.text_request()

    request.lang = 'en'  # optional, default value equal 'en'

    request.session_id = sessionid

    request.query = query

    response = request.getresponse()
    response = json.loads(response.read())
    print(response)

    send_message(sessionid, response['result']['fulfillment']['speech'])