private static async Task <GoogleCloudDialogflowV2DetectIntentResponse> ResponseAsync(string sessionId, string message) { ServiceAccountCredential credential; using (var stream = new FileStream(CREDENTIAL_PATH, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream) .CreateScoped(DialogflowService.Scope.CloudPlatform) .UnderlyingCredential as ServiceAccountCredential; } var service = new DialogflowService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = PROJECT_ID }); var response = service.Projects.Agent.Sessions.DetectIntent(new GoogleCloudDialogflowV2DetectIntentRequest { QueryInput = new GoogleCloudDialogflowV2QueryInput { Text = new GoogleCloudDialogflowV2TextInput { Text = message, LanguageCode = "en-US", }, }, }, $"projects/{PROJECT_ID}/agent/sessions/{sessionId}"); return(await response.ExecuteAsync()); }
public static IServiceCollection AddDialogflow(this IServiceCollection services) { var config = GetConfig(); var dialogflowSettings = config.GetSection(nameof(DialogflowSettings)).Get <DialogflowSettings>(); return(services.AddSingleton <INaturalLanguageUnderstandingClient, DialogflowClient>(_ => { var containerClient = new BlobContainerClient( dialogflowSettings.ApiCredentialsStorageConnectionString, dialogflowSettings.ApiCredentialsContainerName); var blobClient = containerClient.GetBlobClient(dialogflowSettings.ApiCredentialsJsonName); ServiceAccountCredential credential; using (var stream = new MemoryStream()) { blobClient.DownloadTo(stream); stream.Position = 0; credential = GoogleCredential.FromStream(stream) .CreateScoped(DialogflowService.Scope.CloudPlatform) .UnderlyingCredential as ServiceAccountCredential; } var service = new DialogflowService(new BaseClientService.Initializer { HttpClientInitializer = credential, }); return new DialogflowClient(service, dialogflowSettings.ProjectId); })); }
protected void Page_Load(object sender, EventArgs e) { var sessionId = Guid.NewGuid().ToString(); var message = "cc"; var creds = GoogleCredential.FromFile(CREDENTIAL_PATH); var scopedCreds = creds.CreateScoped(DialogflowService.Scope.CloudPlatform); var response = new DialogflowService(new BaseClientService.Initializer { HttpClientInitializer = scopedCreds, ApplicationName = PROJECT_ID }).Projects.Agent.Sessions.DetectIntent( new GoogleCloudDialogflowV2DetectIntentRequest { QueryInput = new GoogleCloudDialogflowV2QueryInput { Text = new GoogleCloudDialogflowV2TextInput { Text = message, LanguageCode = "en-US" } } }, $"projects/{PROJECT_ID}/agent/sessions/{sessionId}") .Execute(); var queryResult = response.QueryResult; Console.WriteLine(queryResult.FulfillmentText); }
static void Main(string[] args) { Console.WriteLine("== Testing DialogFlow api and service =="); Console.WriteLine("== Start speaking below: =="); // Authenticate with google OAuth2.0 servers UserCredential credential; AppSecrets settings; // Requires app secrets using (var reader = new JsonTextReader(new StreamReader("appSecrets.json"))) { settings = new JsonSerializer().Deserialize <AppSecrets>(reader); } credential = GoogleWebAuthorizationBroker.AuthorizeAsync( // Client secrets for DialogFlowTest app settings.Secrets, new[] { DialogflowService.ScopeConstants.CloudPlatform, DialogflowService.ScopeConstants.Dialogflow }, "user", CancellationToken.None) .Result; if (credential == null) { return; } // Initialize the dialog flow service using credential var dialogFlowService = new DialogflowService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "DialogFlowTest", }); // Assign HttpClient baseAddress dialogFlowService.HttpClient.BaseAddress = new Uri(dialogFlowService.BaseUri); // Main conversing loop while (Conversing) { var textInput = Console.ReadLine(); var request = DetectIntentRequestBuilder .NewRequest .QueryInput.TextInput .WithText(textInput) .WithLanguageCode(LanguageCodeConst.enUS) .Build(); var response = dialogFlowService.HttpClient.PostAsync($"/v2/projects/{settings.ProjectId}/agent/sessions/123456789:detectIntent", new StringContent(dialogFlowService.Serializer.Serialize(request), Encoding.UTF8, "application/json")) .Result; var dialogFlowResponse = dialogFlowService.Serializer.Deserialize <GoogleCloudDialogflowV2DetectIntentResponse>(response.Content.ReadAsStreamAsync().Result); Console.WriteLine($"Agent: {dialogFlowResponse?.QueryResult?.FulfillmentText ?? "You did not enter anything"}"); Conversing = textInput.ToUpper() == "GOODBYE" ? false : true; } Console.ReadKey(); }
public DialogflowClient(DialogflowService service, string projectId) { _service = service; _projectId = projectId; }
public async Task <HttpResponseMessage> Post(HttpRequestMessage request) { var jsonData = await request.Content.ReadAsStringAsync(); dynamic data = JObject.Parse(jsonData); var clientAccessKey = Request.Headers.GetValues("ClientAccessKey").First().ToString(); var action = (String)data.result.action; var sessionId = (String)data.sessionId; DialogflowService service = new DialogflowService(clientAccessKey); HttpResponseMessage resp = new HttpResponseMessage(); switch (action) { case "input.welcome": resp = service.GetGreetingMessage(); break; case "portfolio": resp = service.GetLandorWorkExample(); break; case "employees": var fullName = (String)data.result.parameters.fullName; resp = service.GetEmployeTitle(fullName); break; case "learn": var any = (String)data.result.parameters.any; var topic = (String)data.result.parameters.topic; var desc = (String)data.result.parameters.description; resp = service.Teach(topic, desc); break; case "email": var receiver = (String)data.result.parameters.fullName; var message = (String)data.result.parameters.message; resp = service.SendEmail(receiver, message); break; case "randomTopic": resp = service.GetRandomSubject(sessionId); break; case "ClearPreviousContexts": //var userSays = (String)data.result.resolvedQuery; resp = service.ClearPreviousContexts(sessionId); break; case "randomTopicPeople": resp = service.GetRandomSubjectPeople(sessionId); break; case "randomTopicAbout": resp = service.GetRandomSubjectAboutLandor(sessionId); break; case "getIntentByEvent": //Make sure that the context value is an event name on an intent var context = (String)data.result.contexts[0].name; //get the context that contain request keyword //that will be the name of the event to be executed if (data.result.contexts.Count > 0) { for (int i = 0; i < data.result.contexts.Count; i++) { context = (String)data.result.contexts[i].name; if (context.Contains("request")) { context = (String)data.result.contexts[i].name; break; } } } resp = service.GetIntentFromContext(sessionId, context); break; case "location": var city = (String)data.result.parameters.locationCity; var country = (String)data.result.parameters.locationCountry; if (country != null && country != "") { resp = service.GetOfficesByCountry(country); } else if (city != null && city != "") { resp = service.GetOfficesByCity(city); } else { var txt = "City or Country?"; var jsn = DialogFlowHelper.CreateJsonObjectResponse(txt); resp = new HttpResponseMessage() { Content = new StringContent(jsn.ToString()) }; } break; default: var text = "Action couldn't be found. Please talk to your developer."; var json = DialogFlowHelper.CreateJsonObjectResponse(text); resp = new HttpResponseMessage() { Content = new StringContent(json.ToString()) }; break; } resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return(resp); }