public async Task <GoogleCloudDialogflowV2WebhookResponse> SetWeight(GoogleCloudDialogflowV2WebhookRequest request) { var unitWeight = (JObject)request.QueryResult.Parameters["unit-weight"]; await _userHandler.SetWeight((decimal)unitWeight["amount"]); return(new GoogleCloudDialogflowV2WebhookResponse()); }
public async Task <string> DeviceRequestCommandDialogFlow(GoogleCloudDialogflowV2WebhookRequest dialogflowRequest) { //identify device object deviceRequested = ConvertDialogflowResquestToObject_GoogleObj(dialogflowRequest); if (deviceRequested == null) { return(FormatterSpeechResponse_GoogleObj(dialogflowRequest, $"I'm sorry, {dialogflowRequest.QueryResult.Parameters["idDevice"].ToString()} was not found", false)); } string jsonReturn = string.Empty; if (deviceRequested is SonoffDualR2) { //TODO: use pattern matching SonoffDualR2 sonoffRequest = ((SonoffDualR2)deviceRequested); if (ValidIdDeviceRequested(sonoffRequest.IdDevice)) { switch (sonoffRequest.SonoffModelEnum) { case DeviceEnum.SonoffDualR2: jsonReturn = await SonoffDualR2ExecuteCommand(sonoffRequest); return(FormatterSpeechResponse_GoogleObj(dialogflowRequest, jsonReturn, true)); default: break; } } } return(FormatterSpeechResponse_GoogleObj(dialogflowRequest, $"I'm sorry, {dialogflowRequest.QueryResult.Parameters["idDevice"].ToString()} was not found", false)); }
public async Task <WebhookResponse> GetExternalNews(GoogleCloudDialogflowV2WebhookRequest intent) { var newsSourceRequested = intent.QueryResult.Parameters[newsParameter].ToString(); string urlToUse = ""; urlToUse = BuildUrlToUse(newsSourceRequested, out string readableParameter); NewsExtract extracts = await ObtainNewAPIDta(urlToUse); if (extracts == null) { return(new WebhookResponse { FulfillmentText = Utilities.ErrorReturnMsg() }); } string returnString = ExtractHeadlines(extracts); var returnValue = new WebhookResponse { FulfillmentText = returnString }; // returnValue = ExtractHeadlines(extracts, returnValue); return(returnValue); }
private object ConvertDialogflowResquestToObject_GoogleObj(GoogleCloudDialogflowV2WebhookRequest dialogflowRequest) { var device = GetInformationDeviceById_GoogleObj(dialogflowRequest); if (device == null || device.Count() <= 0) { return(null); } var objectType = device.Where(x => x.Key.Equals("ModelDevice")).Select(y => y.Value).FirstOrDefault(); //TODO: valid objectType (!=null) //VALID DEVICE AND OBJECTTYPE switch ((DeviceEnum)Enum.Parse(typeof(DeviceEnum), objectType, true)) { case DeviceEnum.SonoffDualR2: { int _channel = 1; //by default we use channel 1 (if is not mentioned in the object in appsettings.json int.TryParse(device.Where(x => x.Key.Equals("Channel")).Select(y => y.Value).FirstOrDefault(), out _channel); return(new SonoffDualR2() { IdDevice = device.Where(x => x.Key.Equals("IP_Address")).Select(y => y.Value).FirstOrDefault(), SonoffChannel = _channel, SonoffRequestCommandEnum = ConvertStringCmdToSonoffRequestCommandEnum(dialogflowRequest.QueryResult.Parameters["Command"].ToString()) }); } default: return(null); } }
public async Task <IActionResult> Post([FromBody] GoogleCloudDialogflowV2WebhookRequest intent) { WebhookResponse returnValue = await obtainStockQuote.GetMarketData(intent); if (returnValue == null) { returnValue = new WebhookResponse { FulfillmentText = Utilities.ErrorReturnMsg() + Utilities.EndOfCurrentRequest() }; } else if (returnValue.FulfillmentMessages.Count == 0 && !returnValue.FulfillmentText.Contains(Utilities.EndOfCurrentRequest())) { returnValue.FulfillmentText = returnValue.FulfillmentText + "\n" + Utilities.EndOfCurrentRequest(); } var responseString = returnValue.ToString(); _log.LogTrace("Completed processing request"); return(new ContentResult { Content = responseString, ContentType = "application/json", StatusCode = 200 }); }
public async Task <JsonResult> DeviceRequestCommandDialogFlow([FromBody] GoogleCloudDialogflowV2WebhookRequest dialogflowRequest) { if (dialogflowRequest == null || string.IsNullOrEmpty(dialogflowRequest.QueryResult.Parameters["idDevice"].ToString())) { return(await FormatResposeDialogFlow("I'm sorry, but I didn't find the device")); } return(await FormatResposeDialogFlow(await service.DeviceRequestCommandDialogFlow(dialogflowRequest))); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> GetTopSpeed(GoogleCloudDialogflowV2WebhookRequest request) { double maxSpeed = _trackingHandler.GetMaxSpeed(request.ToFilteredBinding(true)); return(new GoogleCloudDialogflowV2WebhookResponse() { FulfillmentText = $"Your top speed was {(int)(maxSpeed * 3.6)} km/h." }); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> GetDistance(GoogleCloudDialogflowV2WebhookRequest request) { int distance = _trackingHandler.GetDistance(request.ToFilteredBinding(true)); return(new GoogleCloudDialogflowV2WebhookResponse() { FulfillmentText = $"You covered {FormatDistance(distance)}" }); }
public static FilteredBinding ToFilteredBinding(this GoogleCloudDialogflowV2WebhookRequest request, bool includeTime = false) { var datePeriod = request.QueryResult.Parameters.ContainsKey("date-period") ? request.QueryResult.Parameters["date-period"] : null; var dateTime = request.QueryResult.Parameters.ContainsKey("date-time") ? request.QueryResult.Parameters["date-time"] : null; return(new FilteredBinding() { From = dateTime is DateTime fromDate ? fromDate.Date : datePeriod is JObject datePeriodStart ? (DateTime)datePeriodStart["startDate"] : (DateTime?)null, To = dateTime is DateTime toDate ? (includeTime ? toDate.Date.AddDays(1) : toDate.Date) : datePeriod is JObject datePeriodEnd ? (DateTime)datePeriodEnd["endDate"] : (DateTime?)null });
private string FormatterSpeechResponse_GoogleObj(GoogleCloudDialogflowV2WebhookRequest dialogflowRequest, string response, bool trimResponse) { if (!trimResponse) { return(response); } response = response.Replace("\"", "").Replace("\\", "").Replace("}", "").Split(":")[1].ToLower(); return($"{dialogflowRequest.QueryResult.Parameters["idDevice"].ToString()} was turned {response}"); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> GetConsumationSum(GoogleCloudDialogflowV2WebhookRequest request) { var binding = new ConsumationGetBinding(request.ToFilteredBinding()); int sum = _consumationHandler.SumVolume(binding); return(new GoogleCloudDialogflowV2WebhookResponse() { FulfillmentText = $"You've drank {sum / 1000} liters." }); }
public GoogleCloudDialogflowV2WebhookResponse Post(GoogleCloudDialogflowV2WebhookRequest obj) { var botModel = ModelMapper.DialogFlowToModel(obj); if (botModel == null) { return(null); } botModel = IntentRouter.Process(botModel); return(ModelMapper.ModelToDialogFlow(botModel)); }
public ActionResult <GoogleCloudDialogflowV2WebhookResponse> Post([FromBody] GoogleCloudDialogflowV2WebhookRequest request) { //request.QueryResult.Parameters //DialogflowBaseServiceRequest req = new var response = new GoogleCloudDialogflowV2WebhookResponse() { FulfillmentText = "Hello from " + request.QueryResult.Intent.DisplayName }; return(response); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> SetLatestOdometer(GoogleCloudDialogflowV2WebhookRequest request) { var odometer = (JObject)request.QueryResult.Parameters.FirstOrDefault().Value; var carLog = new CarLogBinding() { Odometer = (int)odometer["amount"] }; _carHandler.CreateLog(carLog); return(new GoogleCloudDialogflowV2WebhookResponse()); }
internal static BotModel DialogFlowToModel(GoogleCloudDialogflowV2WebhookRequest dFlowResponse) { var botModel = new BotModel() { Id = dFlowResponse.ResponseId }; botModel.Session.Id = dFlowResponse.Session; botModel.Request.Intent = dFlowResponse.QueryResult.Intent.DisplayName; botModel.Request.Parameters = dFlowResponse.QueryResult.Parameters.ToList() .ConvertAll(p => new KeyValuePair <string, string>(p.Key, p.Value.ToString())); return(botModel); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> GetMovieCount(GoogleCloudDialogflowV2WebhookRequest request) { var filteredBinding = request.ToFilteredBinding(); var movieGetBinding = new MovieGetBinding() { From = filteredBinding.From, To = filteredBinding.To }; int movieCount = _movieHandler.Count(movieGetBinding); return(new GoogleCloudDialogflowV2WebhookResponse() { FulfillmentText = $"You've watched {movieCount} movies." }); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> GetExpenseSum(GoogleCloudDialogflowV2WebhookRequest request) { var binding = new ExpenseSumGetBinding(request.ToFilteredBinding()); binding.TypeId = request.QueryResult.Parameters.ContainsKey("ExpenseType") ? ((JArray)request.QueryResult.Parameters["ExpenseType"]).Select(x => ((string)x).Replace(" ", "-")) : null; decimal sum = await _expenseHandler.SumAmount(binding); var user = _userHandler.Get(UserId); return(new GoogleCloudDialogflowV2WebhookResponse() { FulfillmentText = $"You've spent {sum} {user.DefaultCurrency.Code}" }); }
internal async Task <IActionResult> ProcessValuesFromIntents(GoogleCloudDialogflowV2WebhookRequest value) { _log.LogTrace("Starting to process request"); var response = await ProcessIntent(value); var responseString = response.ToString(); _log.LogTrace("Completed processing request"); return(new ContentResult { Content = responseString, ContentType = "application/json", StatusCode = 200 }); }
private IActionResult ExecuteKnownValues(GoogleCloudDialogflowV2WebhookRequest value) { WebhookResponse returnValue = null; var baseURL = Request.Host.ToString(); var keyUsedToAccess = Request.Headers["key"].ToString(); string intendDisplayName = value.QueryResult.Intent.DisplayName; var client = new RestClient("https://" + baseURL); var actionLink = BuildActionMethod(intendDisplayName); if (string.IsNullOrWhiteSpace(actionLink)) { returnValue = StdErrorMessageGenerator(); } else { var request = new RestRequest(actionLink, Method.POST); request.AddHeader("key", keyUsedToAccess); request.AddJsonBody(value); var response = client.Execute(request); if (response.IsSuccessful) { var returnMsg = response.Content; return(new ContentResult { Content = returnMsg, ContentType = "application/json", StatusCode = 200 }); } else { returnValue = StdErrorMessageGenerator(); } } var responseString = returnValue.ToString(); _log.LogTrace("Completed processing request"); return(new ContentResult { Content = responseString, ContentType = "application/json", StatusCode = 200 }); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> ProcessWebhook(GoogleCloudDialogflowV2WebhookRequest request) { switch (request.QueryResult.Intent.Name) { case "projects/projectivy-rkgwxr/agent/intents/f55a44e6-65c8-44c8-a418-e1f535c7bb89": return(await CreateExpense(request)); case "projects/projectivy-rkgwxr/agent/intents/2f5e913e-036d-437f-b33e-4ab91e3fbdc7": return(await GetConsecutiveConsumationDays(request)); case "projects/projectivy-rkgwxr/agent/intents/6aed36d0-3e1c-406b-9acf-39bc6fcece99": return(await GetDistance(request)); case "projects/projectivy-rkgwxr/agent/intents/c7020a73-a387-4d04-8c3f-961e6de9f99a": return(await GetTopSpeed(request)); case "projects/projectivy-rkgwxr/agent/intents/9a170975-9470-4719-a6cc-d9f611d34dab": return(await GetLatestOdometer()); case "projects/projectivy-rkgwxr/agent/intents/82855d04-184d-43f7-bc39-c594a9dc5773": return(await SetLatestOdometer(request)); case "projects/projectivy-rkgwxr/agent/intents/2a0a54f2-d03a-4ee5-aefb-af9b24916eb4": return(await GetConsumationCount(request)); case "projects/projectivy-rkgwxr/agent/intents/45356f36-e342-4c71-ae0d-c9c06e3df76d": return(await GetConsumationSum(request)); case "projects/projectivy-rkgwxr/agent/intents/a26b869b-23ff-4426-9158-8566fffc843b": return(await GetExpenseSum(request)); case "projects/projectivy-rkgwxr/agent/intents/970e9c94-06f0-482f-b459-568af5b631e8": return(await SetWeight(request)); case "projects/projectivy-rkgwxr/agent/intents/b8c5e20f-7c00-42a2-b70f-23611cb677b8": return(await GetMovieCount(request)); default: return(new GoogleCloudDialogflowV2WebhookResponse() { FulfillmentText = "Unknown intent" }); } }
public async Task <WebhookResponse> GetTrendingAsync(GoogleCloudDialogflowV2WebhookRequest intent) { var parameter = intent.QueryResult.Parameters[EntityTrendParameter].ToString(); var urlToUse = BuildUrlToUse(parameter, out string readableParameter); if (string.IsNullOrWhiteSpace(urlToUse)) { return(new WebhookResponse { FulfillmentText = Utilities.ErrorReturnMsg() }); } string outputMsg = await GetIexTradingDataAsync(urlToUse, readableParameter); return(new WebhookResponse { FulfillmentText = outputMsg }); }
public String Index([FromBody] GoogleCloudDialogflowV2WebhookRequest request) { string jsonstring = ""; OrchestratorApi oApi = new OrchestratorApi("https://platform.uipath.com", "admin", "shan999km", "shanslab"); JObject jobj = new JObject(); JsonSerializer js = new JsonSerializer(); //String jsonstring = "{\"fulfillmentText\": \"response text\",\"fulfillmentMessages\": [{\"simpleResponses\": {\"simpleResponses\": [ {\"textToSpeech\": \"response text\",\"displayText\": \"response text\"}]}}]}"; // String jsonstring = "{\"fulfillmentText\": \"This is a text response\",\"fulfillmentMessages\": [{\"simpleResponses\": {\"textToSpeech\": \"this is text to speech\",\"ssml\": \"this is ssml\",\"displayText\": \"this is display text\"}}]}"; // String jsonstring = "{\"payload\": {\"google\": {\"expectUserResponse\": true,\"richResponse\": {\"items\": [{\"simpleResponse\": {\"textToSpeech\": \"this is a simple response\"}}]}}}}"; //request.QueryResult.Parameters.Add("email", "Testmail"); var j = JsonConvert.SerializeObject(request.QueryResult.Parameters); Console.WriteLine(j); //////ViewData["req"] = ViewData["req"]+request.QueryResult.Parameters["Ops"].ToString()+Environment.NewLine; if (request.QueryResult.Parameters["Ops"].Equals("join")) { oApi.addObjectToQueue(j.ToString(), "Test"); } string username = request.QueryResult.Parameters["username"].ToString().Trim();; string pin = request.QueryResult.Parameters["pin"].ToString().Trim(); string useremail = checkUser(username, pin); if (!useremail.Equals("")) { j = j.Replace("\"}", ",\"email\":\"" + useremail + "\"}"); jsonstring = "{\"fulfillmentText\": \"response text\",\"fulfillmentMessages\": [{\"simpleResponses\": {\"simpleResponses\": [ {\"textToSpeech\": \"response text\",\"displayText\": \"response text\"}]}}],\"followupEventInput\": {\"name\": \"Dummy\",\"languageCode\": \"en-US\",\"parameters\": {\"msg\": \"password is sent to:" + useremail + "\"}}}"; Console.WriteLine(j.ToString()); oApi.addObjectToQueue(j.ToString(), "Test"); } else { jsonstring = "{\"fulfillmentText\": \"response text\",\"fulfillmentMessages\": [{\"simpleResponses\": {\"simpleResponses\": [ {\"textToSpeech\": \"response text\",\"displayText\": \"response text\"}]}}],\"followupEventInput\": {\"name\": \"AD_Pass_Reset\",\"languageCode\": \"en-US\",\"parameters\": {\"msg\": \"Please check your pin!\"}}}"; } return(jsonstring); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> CreateExpense(GoogleCloudDialogflowV2WebhookRequest request) { var unitCurrency = (JObject)request.QueryResult.Parameters["unit-currency"]; string currencyId = (string)unitCurrency["currency"]; var user = _userHandler.Get(UserId); var binding = new ExpenseBinding() { Amount = Convert.ToDecimal(unitCurrency["amount"]), CurrencyId = string.IsNullOrEmpty(currencyId) ? user.DefaultCurrency.Code : currencyId, Comment = (string)request.QueryResult.Parameters["description"], Date = (DateTime)request.QueryResult.Parameters["date"], ExpenseTypeId = ((string)request.QueryResult.Parameters["expense-type"]).Replace(" ", "-"), NeedsReview = true, PaymentTypeId = (string)request.QueryResult.Parameters["payment-type"] }; _expenseHandler.Create(binding); return(new GoogleCloudDialogflowV2WebhookResponse()); }
private async Task <WebhookResponse> ProcessIntent(GoogleCloudDialogflowV2WebhookRequest intent) { string intendDisplayName = intent.QueryResult.Intent.DisplayName; WebhookResponse returnValue = null; switch (intendDisplayName) { case "marketTrends": returnValue = await _obtainTrends.GetTrendingAsync(intent); break; case "newsFetch": break; case "stockQuote": break; case "fundamentals": break; default: break; } if (returnValue == null) { returnValue = new WebhookResponse { FulfillmentText = Utilities.ErrorReturnMsg() + Utilities.EndOfCurrentRequest() }; } else if (returnValue.FulfillmentMessages.Count == 0 && !returnValue.FulfillmentText.Contains(Utilities.EndOfCurrentRequest())) { returnValue.FulfillmentText = returnValue.FulfillmentText + "\n" + Utilities.EndOfCurrentRequest(); } return(returnValue); }
public async Task <WebhookResponse> GetMarketData(GoogleCloudDialogflowV2WebhookRequest stockQuoteParameter) { _log.LogTrace("Starting to obtain quotes"); var companyNameToResolve = stockQuoteParameter.QueryResult.Parameters[companyName].ToString(); var tickersToUse = await _obtainCompanyDetails.ResolveCompanyNameOrTicker(companyNameToResolve); if (string.IsNullOrWhiteSpace(tickersToUse)) { return(new WebhookResponse { FulfillmentText = $"Could not resolve {companyNameToResolve}" }); } var quotes = await _envHandler.ObtainFromWorldTrading(tickersToUse); string returnValueMsg = BuildOutputMsg(quotes); var returnValue = new WebhookResponse { FulfillmentText = returnValueMsg }; return(returnValue); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> PostDialogflow([FromBody] GoogleCloudDialogflowV2WebhookRequest request) => await _dialogflowHandler.ProcessWebhook(request);
public async Task <WebhookResponse> GetCompanyRatings(GoogleCloudDialogflowV2WebhookRequest ratingsParameters) { _log.LogTrace("Start obtain fundamentals"); var companyNameToResolve = ratingsParameters.QueryResult.Parameters[companyName].ToString(); var tickersToUse = await _obtainCompanyDetails.ResolveCompanyNameOrTicker(companyNameToResolve); if (string.IsNullOrWhiteSpace(tickersToUse)) { return(new WebhookResponse { FulfillmentText = $"Could not resolve {companyNameToResolve}" }); } var fulfillmentText = new StringBuilder(); try { int counter = 0; foreach (var ticker in tickersToUse.Split(',')) { var computedRatingMd = _connectionHandlerCF.Get().Where(x => x.Ticker.ToLower().Equals(ticker.ToLower()) && x.FYear == DateTime.Now.Year).FirstOrDefault(); if (computedRatingMd == null) { computedRatingMd = _connectionHandlerCF.Get().Where(x => x.Ticker.ToLower().Equals(ticker.ToLower()) && x.FYear == DateTime.Now.Year - 1).FirstOrDefault(); } PiotroskiScore computedRating = null; if (computedRatingMd != null) { computedRating = Mapper.Map <PiotroskiScore>(computedRatingMd); } fulfillmentText.Append(await BuildCompanyProfile(ticker, computedRating)); if (++counter >= 2) { break; } } if (counter >= 2) { fulfillmentText.Append($"Limiting result set as the search term {companyNameToResolve} resolved to too many results.\n"); } } catch (Exception ex) { _log.LogCritical($"Error while processing Getting Company Ratings; \n{ex.Message}"); return(new WebhookResponse { FulfillmentText = Utilities.ErrorReturnMsg() + Utilities.EndOfCurrentRequest() }); } if (fulfillmentText.ToString().Contains("Piotroski")) { fulfillmentText.Append("Note: Piotroski F-Score is based on company fundamentals; " + "a rating greater than 6 indicates strong fundamentals"); } var webhookResponse = new WebhookResponse { FulfillmentText = fulfillmentText.ToString() }; _log.LogTrace("End obtain fundamentals"); return(webhookResponse); }
public async Task <IActionResult> Post([FromBody] GoogleCloudDialogflowV2WebhookRequest value) { return(await _processMessages.ProcessValuesFromIntents(value)); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> GetConsumationCount(GoogleCloudDialogflowV2WebhookRequest request) { var binding = new ConsumationGetBinding(request.ToFilteredBinding()); int count = _consumationHandler.Count(binding); return(new GoogleCloudDialogflowV2WebhookResponse() { FulfillmentText = $"You've drank {count} beers." }); }
public async Task <GoogleCloudDialogflowV2WebhookResponse> GetConsecutiveConsumationDays(GoogleCloudDialogflowV2WebhookRequest request) { var consecutive = _consumationHandler.ConsecutiveDates(new ConsumationGetBinding()).FirstOrDefault(); return(new GoogleCloudDialogflowV2WebhookResponse() { FulfillmentText = $"{consecutive.To.Subtract(consecutive.From).TotalDays} days, from {consecutive.From} to {consecutive.To}" }); }