2017-12-05 1 views
1

Ich versuche, eine direkte Textantwort von Dialogflow zu bekommen. Ich bekomme eine Antwort vom Beispielcode auf github, aber das ist überhaupt nicht benutzerfreundlich. Wie bekomme ich die "Speech-Only" -Antwort?Wie bekomme ich eine Textantwort direkt in Dialogflow?

import os.path 
import sys 

try: 
    import apiai 
except ImportError: 
    sys.path.append(
     os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir) 
    ) 
    import apiai 

CLIENT_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN' 


def main(): 
    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()) 


if __name__ == '__main__': 
    main() 

Ich erwarte, dass ein nur ein einfaches Ergebnis. Ein einfacher Hallo-Text.

Was ich stattdessen bekommen = b'{\n "id": "306fd06a-d9e6-4c2e-8c05-98ff7fc0ecd5",\n "timestamp": "2017-12-05T22:18:15.563Z",\n "lang": "en",\n "result": {\n "source": "agent",\n "resolvedQuery": "hi",\n "action": "input.welcome",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {\n "intentId": "8406ea3a-a0c9-4470-829f-aba0ce2da2e5",\n "webhookUsed": "false",\n "webhookForSlotFillingUsed": "false",\n "intentName": "Default Welcome Intent"\n },\n "fulfillment": {\n "speech": "Hi there!",\n "messages": [\n {\n "type": 0,\n "speech": "Hi there!"\n }\n ]\n },\n "score": 1.0\n },\n "alternateResult": {\n "source": "domains",\n "resolvedQuery": "hi",\n "action": "smalltalk.greetings.hello",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {},\n "fulfillment": {\n "speech": "Hey!",\n "source": "agent"\n },\n "score": 1.0\n },\n "status": {\n "code": 200,\n "errorType": "success",\n "webhookTimedOut": false\n },\n "sessionId": "mr.9000"\n}'

Antwort

1

Genau wie diese versuchen, die Nachricht zu erhalten:

response = json.loads(request.getresponse().read().decode('utf-8')) 
message = response['result']['fulfillment']['speech'] 
print (message) 

nicht

import json 

am Anfang hinzuzufügen Vergessen. Wenn Sie es noch nicht installiert haben, installieren Sie es. Sie müssen, wenn Sie mit Json in Python beschäftigen wollen. Sagen Sie es mir, wenn es funktioniert

+0

TypeError: Das Objekt 'HTTPResponse' ist nicht einfügbar. Ich wünschte, es hätte funktioniert. – Furky

+0

Hey ich habe den Code ein bisschen geändert. Kannst du es jetzt versuchen? –

+0

Name 'Json' ist nicht definiert. Ich fühle, dass wir uns irgendwie nah sind. – Furky

0

Sieht aus, als ob Sie Dialogflow's query API verwenden. Das Format der Antwort ist dokumentiert here. Sie müssen den JSON analysieren. Der häufigste Weg, dies zu tun wäre ...

  1. Verwenden Sie das json-Modul, das Sie importieren müssen (das heißt import json an der Spitze Sie Datei).
  2. Als nächstes werden Sie die JSON-String laden müssen Sie mit dem Load-Methode empfangen sind (dh eine Zeile hinzufügen, nachdem Sie response definieren: response_dict = json.loads(response.read())
  3. Schließlich müssen Sie die richtige Zeichenfolge aus dem response_dict Objekt abzurufen: print(response_dict.['result']['resolvedQuery'])
+0

Das funktioniert auch! Vielen Dank ! – Furky

0

ich glaube, Sie nur für die Textantworten fragen.

Sie den folgenden Code verwenden können, wie es ist.

Just don't forget to update your access token in the code.

<html> 
<head> 
    <title>API Example</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
    <script type="text/javascript"> 
     var accessToken = "update your access token here"; 
     var baseUrl = "https://api.api.ai/v1/"; 
     $(document).ready(function() { 
      $("#input").keypress(function(event) { 
       if (event.which == 13) { 
        event.preventDefault(); 
        send(); 
       } 
      }); 
      $("#rec").click(function(event) { 
       switchRecognition(); 
      }); 
     }); 
     var recognition; 
     function startRecognition() { 
      recognition = new webkitSpeechRecognition(); 
      recognition.onstart = function(event) { 
       updateRec(); 
      }; 
      recognition.onresult = function(event) { 
       var text = ""; 
       for (var i = event.resultIndex; i < event.results.length; ++i) { 
        text += event.results[i][0].transcript; 
       } 
       setInput(text); 
       stopRecognition(); 
      }; 
      recognition.onend = function() { 
       stopRecognition(); 
      }; 
      recognition.lang = "en-US"; 
      recognition.start(); 
     } 

     function stopRecognition() { 
      if (recognition) { 
       recognition.stop(); 
       recognition = null; 
      } 
      updateRec(); 
     } 
     function switchRecognition() { 
      if (recognition) { 
       stopRecognition(); 
      } else { 
       startRecognition(); 
      } 
     } 
     function setInput(text) { 
      $("#input").val(text); 
      send(); 
     } 
     function updateRec() { 
      $("#rec").text(recognition ? "Stop" : "Speak"); 
     } 
//  function send() { 
//   var text = $("#input").val(); 
//   $.ajax({ 
//    type: "POST", 
//    url: baseUrl + "query?v=20150910", 
//    contentType: "application/json; charset=utf-8", 
//    dataType: "json", 
//    headers: { 
//     "Authorization": "Bearer " + accessToken 
//    }, 
//    data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }), 
//    success: function(data) { 
//     setResponse(JSON.stringify(data, undefined, 2)); 
//    }, 
//    error: function() { 
//     setResponse("Internal Server Error"); 
//    } 
//   }); 
//   setResponse("Loading..."); 
//  } 
     function send() { 
      var text = $("#input").val(); 
      $.ajax({ 
       type: "POST", 
       url: baseUrl + "query?v=20150910", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       headers: { 
        "Authorization": "Bearer " + accessToken 
       }, 
       data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }), 
       success: function(data) { 
        var respText = data.result.fulfillment.speech; 
        console.log("Respuesta: " + respText); 
        setResponse(respText); 
       }, 
       error: function() { 
        setResponse("Internal Server Error"); 
       } 
      }); 
      setResponse("Thinking..."); 
     } 
     function setResponse(val) { 
      $("#response").text(val); 
     } 

    </script> 
    <style type="text/css"> 
     body { width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; } 
     div { position: absolute; } 
     input { width: 400px; } 
     button { width: 50px; } 
     textarea { width: 100%; } 
    </style> 
</head> 
<body> 
<div> 
    <input id="input" type="text"> <button id="rec">Speak</button> 
    <br>Response<br> <textarea id="response" cols="40" rows="20"></textarea> 
</div> 
</body> 
</html> 
Verwandte Themen