private string Conversation(SessionsClient clientSessions, string authFilter, string joyUserId, Guid joyGuid, bool isReInit)
        {
            EventInput evnt = new EventInput
            {
                Name         = isReInit ? ConstDialogFlow.DialogFlowReinitializeConversationEvent : ConstDialogFlow.DialogFlowInitConversationEvent,
                LanguageCode = ConstDialogFlow.Language
            };

            evnt.Parameters = new Google.Protobuf.WellKnownTypes.Struct();

            Google.Protobuf.WellKnownTypes.Value v1 = new Google.Protobuf.WellKnownTypes.Value();
            v1.StringValue = joyUserId;
            Google.Protobuf.WellKnownTypes.Value v2 = new Google.Protobuf.WellKnownTypes.Value();
            v2.StringValue = authFilter;

            evnt.Parameters.Fields.Add(ConstDialogFlow.DialogFlowUserName, v1);
            evnt.Parameters.Fields.Add(ConstDialogFlow.DialogFlowToken, v2);

            var response = clientSessions.DetectIntent(
                session: new SessionName("hr-joy", joyGuid.ToString("N", CultureInfo.CurrentCulture)),
                queryInput: new QueryInput
            {
                Event = evnt
            }
                );

            var queryResult = response.QueryResult;

            //   var joyUserDetails = _subscribeModuleService.GetIdentifier();
            return(string.IsNullOrEmpty(queryResult.FulfillmentText) ?
                   ConstDialogFlowResponseMessage.WelcomeExceptionMessage
            : string.Format(CultureInfo.CurrentCulture, ConstDialogFlowResponseMessage.WelcomeMessage, "Raju Singh"));
        }
Example #2
0
        public IActionResult Index(string userSay)
        {
            //由 google api console 建立服務帳號, 並匯出存取token
            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"D:\temp\worldmap-1357-c80b706e2fa6.json");

            var input = new TextInput
            {
                Text = userSay, LanguageCode = "zh-TW"
            };

            // Create client
            SessionsClient sessionsClient = SessionsClient.Create();

            // Initialize request argument(s)
            DetectIntentRequest request = new DetectIntentRequest
            {
                SessionAsSessionName = SessionName.FromProjectSession("worldmap-1357", "[SESSION]"),
                QueryParams          = new QueryParameters(),
                QueryInput           = new QueryInput()
                {
                    Text = input
                },
                OutputAudioConfig     = new OutputAudioConfig(),
                InputAudio            = ByteString.Empty,
                OutputAudioConfigMask = new FieldMask(),
            };

            // Make the request
            DetectIntentResponse response = sessionsClient.DetectIntent(request);

            //將訊息傳送給 View 做顯示
            ViewData["response"] = response.QueryResult.FulfillmentText;
            return(View());
        }
Example #3
0
        /// <summary>
        /// 呼叫 Dialogflow 識別出意圖
        /// </summary>
        /// <param name="userSay"></param>
        /// <returns></returns>
        public DetectIntentResponse CallDialogFlow(string userSay)
        {
            //由 google api console 建立服務帳號, 並匯出存取token
            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"認證檔.json");

            var input = new TextInput
            {
                Text         = userSay,
                LanguageCode = "zh-TW"
            };

            // Create client
            SessionsClient sessionsClient = SessionsClient.Create();

            // Initialize request argument(s)
            DetectIntentRequest request = new DetectIntentRequest
            {
                SessionAsSessionName = SessionName.FromProjectSession("worldmap-1357", "[SESSION]"),
                QueryParams          = new QueryParameters(),
                QueryInput           = new QueryInput()
                {
                    Text = input
                },
                OutputAudioConfig     = new OutputAudioConfig(),
                InputAudio            = ByteString.Empty,
                OutputAudioConfigMask = new FieldMask(),
            };

            // Make the request
            DetectIntentResponse response = sessionsClient.DetectIntent(request);

            return(response);
        }
        private string Conversation(SessionsClient clientSessions, string authFilter, string joyUserId, Guid joyGuid, bool isReInit, BaseEntityModel model)
        {
            EventInput evnt = new EventInput
            {
                Name         = isReInit ? "reinit_conversation_event" : "custom_welcome_event",
                LanguageCode = Language
            };

            evnt.Parameters = new Google.Protobuf.WellKnownTypes.Struct();

            Google.Protobuf.WellKnownTypes.Value v1 = new Google.Protobuf.WellKnownTypes.Value();
            v1.StringValue = joyUserId;
            Google.Protobuf.WellKnownTypes.Value v2 = new Google.Protobuf.WellKnownTypes.Value();
            v2.StringValue = authFilter;

            evnt.Parameters.Fields.Add("user_name", v1);
            evnt.Parameters.Fields.Add("token", v2);

            var response = clientSessions.DetectIntent(
                session: new SessionName(ConfigurationManager.AppSettings["DialogFlowAgentId"], joyGuid.ToString("N", CultureInfo.CurrentCulture)),
                queryInput: new QueryInput
            {
                Event = evnt
            }
                );

            var queryResult = response.QueryResult;

            return(string.IsNullOrEmpty(queryResult.FulfillmentText) ? WelcomeExceptionMessage
                                                                      : string.Format(CultureInfo.CurrentCulture, WelcomeMessage, "Raju Singh"));
        }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntent()
 {
     // Snippet: DetectIntent(string, QueryInput, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     string     session    = "projects/[PROJECT]/locations/[LOCATION]/agent/sessions/[SESSION]";
     QueryInput queryInput = new QueryInput();
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(session, queryInput);
     // End snippet
 }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntentResourceNames()
 {
     // Snippet: DetectIntent(SessionName, QueryInput, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     SessionName session    = SessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]");
     QueryInput  queryInput = new QueryInput();
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(session, queryInput);
     // End snippet
 }
        public string Query(string Question)
        {
            if (channel != null)
            {
                if(channel.State == Grpc.Core.ChannelState.Shutdown ||
                    channel.State == Grpc.Core.ChannelState.TransientFailure)
                {
                    channel = null;                   
                }
            }
            if (channel == null) Init();

            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text = Question,
                    LanguageCode = "en-us"
                }
            };

            DetectIntentResponse dialogFlow =null;
            try
            {
                dialogFlow = client.DetectIntent(
                               new SessionName(AgentID, sessionId),
                               query
                           );
            }
            catch (Exception ex)
            {
                NetworkError.Message = ex.Message;
                NetworkError.StackTrace = ex.ToString();
                return "I am unable to access the internet network. Can you please make sure your network is online?";
            }
           

            dialogFlowString = dialogFlow.ToString();
            Response.CreateResponseObject(dialogFlowString);
             
            QueryResult = dialogFlow.QueryResult.ToString();
            FulfillmentText = dialogFlow.QueryResult.FulfillmentText;

            if (FulfillmentText.Trim() == "") FulfillmentText = "I am sorry, I do not have a comment at this moment. Can you try again?";

            if (IsChannelKeepAlive == false)
            {
                channel.ShutdownAsync();                
            }

            return FulfillmentText;

        }
        private string GetAgentResponse(SessionsClient clientSessions, string joyText, string joyUserId, string authFilter, Guid joyGuid)
        {
            string result = string.Empty;

            var response = clientSessions.DetectIntent(
                session: new SessionName("hr-joy", joyGuid.ToString("N", CultureInfo.CurrentCulture)),
                queryInput: new QueryInput
            {
                Text = new TextInput
                {
                    Text         = joyText,
                    LanguageCode = ConstDialogFlow.Language
                }
            }
                );

            if (response.WebhookStatus == null) // retry
            {
#pragma warning disable S1481                   // Unused local variables should be removed
                var reinitializeConversation = ReInitConversation(clientSessions, authFilter, joyUserId, joyGuid);
#pragma warning restore S1481                   // Unused local variables should be removed
                response = clientSessions.DetectIntent(
                    session: new SessionName("hr-joy", joyGuid.ToString("N", CultureInfo.CurrentCulture)),
                    queryInput: new QueryInput
                {
                    Text = new TextInput
                    {
                        Text         = joyText,
                        LanguageCode = ConstDialogFlow.Language
                    }
                }
                    );
            }

            var queryResult = response.QueryResult;
            result = queryResult.FulfillmentText;
            return(result);
        }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntent_RequestObject()
 {
     // Snippet: DetectIntent(DetectIntentRequest,CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     DetectIntentRequest request = new DetectIntentRequest
     {
         SessionAsSessionName = new SessionName("[PROJECT]", "[SESSION]"),
         QueryInput           = new QueryInput(),
     };
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(request);
     // End snippet
 }
    DetectIntentResponse GetResponse(byte[] array)
    {
        var byteString = ByteString.CopyFrom(array);

        Debug.Log("Getting requst and making request");
        var request = new DetectIntentRequest()
        {
            InputAudio        = byteString,
            QueryInput        = query,
            OutputAudioConfig = outputAudioConfig,
            Session           = session
        };

        return(client.DetectIntent(request));
    }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntentRequestObject()
 {
     // Snippet: DetectIntent(DetectIntentRequest, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     DetectIntentRequest request = new DetectIntentRequest
     {
         SessionAsSessionName = SessionName.FromProjectLocationAgentSession("[PROJECT]", "[LOCATION]", "[AGENT]", "[SESSION]"),
         QueryParams          = new QueryParameters(),
         QueryInput           = new QueryInput(),
         OutputAudioConfig    = new OutputAudioConfig(),
     };
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(request);
     // End snippet
 }
Example #12
0
        public string Query(string Question)
        {
            if (channel != null)
            {
                if (channel.State == Grpc.Core.ChannelState.Shutdown ||
                    channel.State == Grpc.Core.ChannelState.TransientFailure)
                {
                    channel = null;
                }
            }
            if (channel == null)
            {
                Init();
            }

            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = Question,
                    LanguageCode = "en-us"
                }
            };

            var dialogFlow = client.DetectIntent(
                new SessionName(AgentID, sessionId),
                query
                );

            dialogFlowString = dialogFlow.ToString();

            QueryResult     = dialogFlow.QueryResult.ToString();
            FulfillmentText = dialogFlow.QueryResult.FulfillmentText;

            if (IsChannelKeepAlive == false)
            {
                channel.ShutdownAsync();
            }

            return(FulfillmentText);
        }
        private string GetAgentResponse(SessionsClient clientSessions, string joyText, string joyUserId, string authFilter, Guid joyGuid, BaseEntityModel model)
        {
            string result = string.Empty;

            var response = clientSessions.DetectIntent(
                session: new SessionName(ConfigurationManager.AppSettings["DialogFlowAgentId"], joyGuid.ToString("N", CultureInfo.CurrentCulture)),
                queryInput: new QueryInput
            {
                Text = new TextInput
                {
                    Text         = joyText,
                    LanguageCode = Language
                }
            }
                );

            var queryResult = response.QueryResult;

            result = queryResult.FulfillmentText;
            return(result);
        }
Example #14
0
        public static async void GetDialogFlowAnswer(TelegramBotClient Bot, Message message)
        {
            SessionsClient client    = SessionsClient.Create();
            long           id        = message.From.Id;
            string         text      = message.Text;
            string         sessionId = id.ToString();

            DetectIntentResponse response = client.DetectIntent(
                session: SessionName.FromProjectSession(projectId, sessionId),
                queryInput: new QueryInput()
            {
                Text = new TextInput()
                {
                    Text         = text,
                    LanguageCode = languageCode
                }
            }
                );
            QueryResult queryResult = response.QueryResult;

            MongoDB.WriteUserBotMessages(queryResult, message);
            await Bot.SendTextMessageAsync(id, queryResult.FulfillmentText);
        }
Example #15
0
        public async Task <Result> GetSpeechAsync(Activity message, Sesion sesion, IDialogContext context)
        {
            Result result = new Result();

            try
            {
                string fileSavePath = System.Web.HttpContext.Current.Server.MapPath("~/Dialogflow/") + AppConstant.DialogFlow.FilePrivateKeyIdJson;

                if (System.IO.File.Exists(fileSavePath))
                {
                    GoogleCredential cred    = GoogleCredential.FromFile(fileSavePath);
                    Channel          channel = new Channel(SessionsClient.DefaultEndpoint.Host, SessionsClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
                    SessionsClient   client  = SessionsClient.Create(channel);

                    QueryInput query = new QueryInput
                    {
                        Text = new TextInput
                        {
                            Text         = message.Text,
                            LanguageCode = "es-es"
                        }
                    };

                    //string sessionId = Guid.NewGuid().ToString();
                    //string projectId = "upc-chatbot"; //TODO: Move to AppSettings

                    string sessionId = sesion.IdSesion.ToString();
                    string projectId = ConfigurationManager.AppSettings["ApiAiProjectId"].ToString();

                    SessionName sessionName = new SessionName(projectId, sessionId);

                    RepeatedField <Context> outputContexts = new RepeatedField <Context>();

                    List <DialogFlowContext> dialogFlowContexts = new List <DialogFlowContext>();

                    if (context.UserData.ContainsKey("OutputContexts"))
                    {
                        string outputContextsGetValue = context.UserData.GetValue <string>("OutputContexts");

                        if (!string.IsNullOrEmpty(outputContextsGetValue))
                        {
                            dialogFlowContexts = JsonConvert.DeserializeObject <List <DialogFlowContext> >(outputContextsGetValue);

                            foreach (var item in dialogFlowContexts)
                            {
                                Struct s = new Struct();

                                foreach (var p in item.Parameters)
                                {
                                    Value v = new Value
                                    {
                                        StructValue = null,
                                        ListValue   = null,
                                        NumberValue = 0D,
                                        StringValue = p.Value //This order position matters!!!
                                    };

                                    s.Fields.Add(p.Key, v);
                                }

                                outputContexts.Add(new Context {
                                    Name = item.Name, LifespanCount = item.LifespanCount, Parameters = s
                                });
                            }
                        }
                    }

                    DetectIntentRequest detectIntentRequest = new DetectIntentRequest
                    {
                        SessionAsSessionName = sessionName,
                        QueryInput           = query,
                        QueryParams          = new QueryParameters()
                    };

                    if (outputContexts.Count > 0)
                    {
                        detectIntentRequest.QueryParams.Contexts.AddRange(outputContexts);
                    }

                    DetectIntentResponse dialogFlow = client.DetectIntent(detectIntentRequest);

                    QueryResult response = dialogFlow.QueryResult;

                    string outputContextsSetValue = response.OutputContexts.ToString();

                    context.UserData.SetValue("OutputContexts", outputContextsSetValue);

                    await EvaluateDialogFlowResponse(response, result, message, sesion);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                BaseData.LogError(ex);
            }

            return(result);
        }