Dialog flow chat bot token expires every 5 minutes

Viewed 177

I have been working on a project with unity about chat bots using dialog flow, the problem I am facing is as follows: I have to run some commands in order to retrieve the token from google in terminal then a C# script uses this token to run some functions but the problem is that the token expires every 5 minutes since I m consuming the API so is there a way to automate the process in a bash script file where It can run the commands and get the token then it is directly used in the C# script.

DialogflowAPIScript

using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Networking;
using JsonData;


public class DialogflowAPIScript : MonoBehaviour
{

    
    void Start()
    {
        i0tBjGc2WlRT9GePIqe1_j5Xq9flXHMGJWnn5sEjNHyG1VfMFqtt3WapHAVo2-RwvPNKRTHI0BkF9OVUzZJ5OWJEILr64_ge1tgcbS7AA"));

        
        StartCoroutine(PostRequest("https://dialogflow.googleapis.com/v2/projects/newagent-taqyfj/agent/sessions/34563:detectIntent",
                              "ya29.c.Ko4B0AeMSB_eB-0DumT7ubxKoJc47TMOKhgls589I-F8whsTbnZvAgFn6Ft-sqwcFPI1n_-CQIp4zk-e3Ip9lVvXvrJFOfPmoejayJhjHR9Gu36XsulR71_iHGnvb8m4aYbkBF9tnkA05cJahNyVZoK5SWR3EgAb4XofkMfp7Qt8vtnMa6J-Q89YZevUk3VfaA"));
    }


    void Update()
    {

    }

    IEnumerator PostRequest(String url, String AccessToken)
    {
        UnityWebRequest postRequest = new UnityWebRequest(url, "POST");
        RequestBody requestBody = new RequestBody();
        requestBody.queryInput = new QueryInput();
        requestBody.queryInput.text = new TextInput();
        requestBody.queryInput.text.text = "hello";
        requestBody.queryInput.text.languageCode = "en";

        string jsonRequestBody = JsonUtility.ToJson(requestBody, true);
        Debug.Log(jsonRequestBody);

        byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonRequestBody);
    
        postRequest.SetRequestHeader("Authorization", "Bearer " + AccessToken);
        postRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
        postRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        //postRequest.SetRequestHeader("Content-Type", "application/json");

        yield return postRequest.SendWebRequest();

        if (postRequest.isNetworkError || postRequest.isHttpError)
        {
            Debug.Log(postRequest.responseCode);
            Debug.Log(postRequest.error);
        }
        else
        {

            Debug.Log("Response: " + postRequest.downloadHandler.text);

        
            byte[] resultbyte = postRequest.downloadHandler.data;
            string result = System.Text.Encoding.UTF8.GetString(resultbyte);
            ResponseBody content = (ResponseBody)JsonUtility.FromJson<ResponseBody>(result);
            Debug.Log(content.queryResult.fulfillmentText);
        }
    }

    IEnumerator GetAgent(String AccessToken)
    {
        UnityWebRequest www = UnityWebRequest.Get("https://dialogflow.googleapis.com/v2/projects/newagent-taqyfj/agent");

        www.SetRequestHeader("Authorization", "Bearer " + AccessToken);

        yield return www.SendWebRequest();
        

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
        
            Debug.Log(www.downloadHandler.text);

                    byte[] results = www.downloadHandler.data;
        }
    }
}

request RequestBody

using System.Collections.Generic;
namespace JsonData
{
    v2/rest/v2/projects.agent.sessions/detectIntent#QueryParameters

    public class RequestBody
    {
        public QueryInput queryInput;
        
        public string inputAudio;
    }


    public class QueryInput
    {
        public TextInput text;
        //public InputAudioConfig audioConfig;
    }
    

    public class InputAudioConfig
    {
        public AudioEncoding audioEncoding;
        public int sampleRateHertz;
        public String languageCode;
        public String[] phraseHints;
    }

    public enum AudioEncoding
    {
        AUDIO_ENCODING_UNSPECIFIED,
        AUDIO_ENCODING_LINEAR_16,
        AUDIO_ENCODING_FLAC,
        AUDIO_ENCODING_MULAW,
        AUDIO_ENCODING_AMR,
        AUDIO_ENCODING_AMR_WB,
        AUDIO_ENCODING_OGG_OPUS,
        AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE
    }

public enum WebhookState
    {
        STATE_UNSPECIFIED,
        WEBHOOK_STATE_ENABLED,
        WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING
    }

    
    public class ResponseBody
    {
        public string responseId;
        public QueryResult queryResult;
        public Status webhookStatus;
    }

    public class QueryResult
    {
        public string queryText;
        public string languageCode;
        public int speechRecognitionConfidence;
        public string action;
        public Struct parameters;
        public bool allRequiredParamsPresent;
        public string fulfillmentText;
        public Message[] fulfillmentMessages;
        public string webhookSource;
        public Struct webhookPayload;
        public Context[] outputContexts;
        public Intent intent;
        public int intentDetectionConfidence;
        public Struct diagnosticInfo;
    }
    
    [Serializable]
    public class Status
    {
        public int code;
        public string message;
        public Object[] details;
    }

    
    [Serializable]
    public class Intent
    {
        public string name;
        public string displayName;
        public WebhookState webhookState;
        public int priority;
        public bool isFallback;
    }

    

    public class Context
    {
        public string name;
    }


    public class Struct
    {
        public Dictionary<string, Value> fields;
    }


    public class Value
    {
        public NullValue null_value;
        public double number_value;
        public string string_value;
        public bool bool_value;
        public Struct struct_value;
        public ListValue list_value;

        public void ForBool(bool value){
            this.bool_value = value;
        }

        public void ForString(string value)
        {
            this.string_value = value;
        }

        public void ForNumber(double number){
            this.number_value = number;
        }

        public void ForNull()
        {
            this.null_value = NullValue.null_vaule;
        }

        public void ForStruct(Struct value){
            this.struct_value = value;
        }

        public void ForList(ListValue value){
            this.list_value = value;
        }
    }

    public enum NullValue
    {
        null_vaule
    }

    
    public class ListValue{
        public Value values;

    }

    
    public class Text{
        public string[] text;
    }

    [Serializable]
    public class Message{
        public Text text;
    }




}```
0 Answers
Related