public TwiMLResult PostSMS() { var messagingResponse = new MessagingResponse(); var form = Request.Form; //set AccountSid if (form["AccountSid"] != "**********************************") { messagingResponse.Message("ERROR. Wrong Account"); return(TwiML(messagingResponse)); } SMS sms = new SMS() { AccountSid = form["AccountSid"], ApiVersion = form["ApiVersion"], Body = form["Body"], DateCreated = form["DateCreated"] != null?DateTime.Parse(form["DateCreated"]) : (DateTime?)null, DateSent = form["DateSent"] != null?DateTime.Parse(form["DateSent"]) : (DateTime?)null, DateUpdated = form["DateUpdated"] != null?DateTime.Parse(form["DateUpdated"]) : (DateTime?)null, Direction = form["Direction"], ErrorCode = form["ErrorCode"] != null?int.Parse(form["ErrorCode"]) : (int?)null, ErrorMessage = form["ErrorMessage"], From = form["From"], MessagingServiceSid = form["MessagingServiceSid"], NumMedia = form["NumMedia"], NumSegments = form["NumSegments"], Price = form["Price"] != null?decimal.Parse(form["Price"]) : (decimal?)null, PriceUnit = form["PriceUnit"], Sid = form["Sid"], Status = form["Status"], //SubresourceUris = null, To = form["To"], Uri = form["Uri"] }; db.SMS.Add(sms); db.SaveChanges(); string bodyStr = form["Body"]; Regex DATregex = new Regex(@"^DAT:"); bool ifDAT = DATregex.Matches(bodyStr).Count > 0; Regex RPTregex = new Regex(@"^RPT:"); bool ifRPT = RPTregex.Matches(bodyStr).Count > 0; if (!(ifRPT || ifDAT)) { messagingResponse.Message("ERROR. Wrong type sms"); return(TwiML(messagingResponse)); } try { SMSparse(sms.Id); //messagingResponse.Message("ALL OK. Parsed"); } catch (Exception ex) { messagingResponse.Message($"ERROR Parsing. [{ex.Message}]"); return(TwiML(messagingResponse)); } return(TwiML(messagingResponse)); }
public static string CreateTwilioResponse(string message) { var response = new MessagingResponse().Message(message); return(response.ToString().Replace("utf-16", "utf-8")); }
/// <summary> /// Returns a properly formatted TwiML response /// </summary> /// <param name="response"></param> /// <returns></returns> // ReSharper disable once InconsistentNaming protected TwiMLResult TwiML(MessagingResponse response) { return(new TwiMLResult(response)); }
public async Task <TwiMLResult> Index(SmsRequest incomingMessage) { var messagingResponse = new MessagingResponse(); string RsvpResponse = incomingMessage.Body; string cleanPhone = incomingMessage.From.Remove(0, 2); var user = await repository.GetUserByPhone(cleanPhone); var invite = user.Invites.FindLast(i => i.Status == RSVPStatus.Pending); if (invite == null) { messagingResponse.Message("You currently have no pending invitations"); return(TwiML(messagingResponse)); } if (!Int32.TryParse(RsvpResponse, out int CleanResponse)) { if (RsvpResponse.StartsWith("QUESTION")) { var comment = new EventComment { Comment = RsvpResponse.Remove(0, 9), UserId = user.Id, EventId = invite.EventId }; await repository.SaveComment(comment); messagingResponse.Message($"You have asked {invite.Event.EventHost} \"{RsvpResponse.Remove(0, 9)}\" for the {invite.Event.EventName} event. We'll let you know as soon as the event is updated."); } else { messagingResponse.Message("Invalid response. 1 for Yes, 2 for No, 3 for Maybe, 4 to get more Details, 5 for event description, or 6 to ask a question"); } } else { switch (CleanResponse) { case 1: invite.Status = RSVPStatus.Accepted; await repository.SaveStatus(invite); messagingResponse.Message($"You have now RSVP'd to {invite.Event.EventName} as attending"); break; case 2: invite.Status = RSVPStatus.Declined; await repository.SaveStatus(invite); messagingResponse.Message($"You have now RSVP'd to {invite.Event.EventName} as not attending"); break; case 3: invite.Status = RSVPStatus.Maybe; await repository.SaveStatus(invite); messagingResponse.Message($"You have now RSVP'd to {invite.Event.EventName} as possibly attending"); break; case 4: messagingResponse.Message($"{invite.Event.EventName} will be on {invite.Event.Start}. It's located at {invite.Event.Location}. There will {(invite.Event.Food ? "" : "not")} be food. It {(invite.Event.Cost > 0 ? "will cost " + invite.Event.Cost + " dollars" : " is free")}." + " Would you like to attend? 1 for Yes, 2 for No, 3 for Maybe, 4 to get more Details, 5 for event description, or 6 to ask a question." ); break; case 5: messagingResponse.Message($"The event description is: {invite.Event.Description}." + " Would you like to attend? 1 for Yes, 2 for No, 3 for Maybe, 4 to get more Details, 5 for event description, or 6 to ask a question." ); break; case 6: messagingResponse.Message("What question would you like to leave for the event host? Please start the message with QUESTION."); return(TwiML(messagingResponse)); default: messagingResponse.Message("Invalid response. 1 for Yes, 2 for No, 3 for Maybe, 4 to get more Details, 5 for event description, or 6 to ask a question"); break; } } return(TwiML(messagingResponse)); }
public TwiMLResult Index(SmsRequest incomingMessage) { #region early stuff // Step 1: Fixed Text //var messagingResponse = new MessagingResponse(); //messagingResponse.Message("The copy cat says: " + incomingMessage.Body); // Step 2: Media // respond with media //var message = new Message(); //message.Body("The Robots are coming! Head for the hills!"); //message.Media(new Uri(@"https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg")); //var messagingResponse = new MessagingResponse(); //messagingResponse.Message(message); //messagingResponse.Append(message); #endregion // Step 3: Variable Reponse string requestBody = incomingMessage.Body.ToLower().Trim(); string requestBody2 = Regex.Replace(requestBody, @"\s+", string.Empty); if (requestBody2.StartsWith(@"saleshttps://")) { requestBody = "sales_alexa"; } // format of sending phoen no is: "+15134986016" string fromPhoneNumber = incomingMessage.From; var response = new MessagingResponse(); // lookup the merchant using the incoming phone number MerchantMBE merchant = MerchantController.LookupMerchant(fromPhoneNumber); if (requestBody == @"help" || requestBody == @"help?" || requestBody == @"???" || requestBody == @"?") { StringBuilder helpMsg = new StringBuilder(); helpMsg.AppendLine(" Available Commands"); helpMsg.AppendLine("------------------------------"); helpMsg.AppendLine("Summary: Today's Summary"); helpMsg.AppendLine("Sales: Today's Sales"); helpMsg.AppendLine("Cback: Pending Chargebacks"); helpMsg.AppendLine("Returns: Today's Returns"); helpMsg.AppendLine("Stop: Unsubscribe"); helpMsg.AppendLine("FAF: Sign-up for Fast Access"); helpMsg.AppendLine("help?: this list"); helpMsg.AppendLine("join: resend welcome message"); //helpMsg.AppendLine("unjoin: reverse join (for testing)"); helpMsg.AppendLine("Settings: view/update alert settings"); helpMsg.AppendLine("User: Account Details"); response.Message(helpMsg.ToString()); } else if (requestBody == @"summary") { DateTime xctPostingDate = DateTime.Today; string salesInfo = MerchantController.BuildSummaryMessage(merchant.merchant_id, xctPostingDate); response.Message(salesInfo); } else if (requestBody == @"sales") { DateTime xctPostingDate = DateTime.Today; string salesInfo = MerchantController.BuildSalesSummaryMessage(merchant.merchant_id, xctPostingDate); response.Message(salesInfo); } else if (requestBody == @"cback" || requestBody == @"chargeback" || requestBody == @"chargebacks") { DateTime xctPostingDate = DateTime.Today; string salesInfo = MerchantController.BuildChargebackDetails(merchant.merchant_id, xctPostingDate); response.Message(salesInfo); } else if (requestBody == @"returns" || requestBody == @"refunds") { DateTime xctPostingDate = DateTime.Today; string refundsInfo = MerchantController.BuildReturnsSummaryMessage(merchant.merchant_id, xctPostingDate); response.Message(refundsInfo); } else if (requestBody == @"faf") { DateTime xctPostingDate = DateTime.Today; string faf = MerchantController.BuildFAFMessage(merchant.merchant_id, xctPostingDate); response.Message(faf); } else if (requestBody == @"confirm") { DateTime xctPostingDate = DateTime.Today; string fafMsg = MerchantController.BuildConfirmFAFMessage(merchant.merchant_id, xctPostingDate); response.Message(fafMsg); } else if (requestBody == @"undo") { DateTime xctPostingDate = DateTime.Today; string fafMsg = MerchantController.BuildUndoFAFMessage(merchant.merchant_id, xctPostingDate); response.Message(fafMsg); } else if (requestBody == @"join") { string welcomeMsg = MerchantController.BuildWelcomeMessage(merchant); string configMsg = MerchantController.BuildConfigMessage(merchant.merchant_id); response.Message($"{welcomeMsg}\n{configMsg}"); } else if (requestBody == @"unjoin") { string unjoinMsg = MerchantController.ResetAcceptedJoin(merchant.merchant_id); response.Message(unjoinMsg); } else if (requestBody == @"config" || requestBody == @"settings") { string msg = MerchantController.BuildConfigMessage(merchant.merchant_id); response.Message(msg); } else if (requestBody == @"user" || requestBody == @"whoami") { string msg = $"Hi {merchant.primary_contact.first_name} !\n{merchant.merchant_name} [id: {merchant.merchant_id}]\np: {merchant.primary_contact.phone_no}"; response.Message(msg); } else if (requestBody == @"sales_alexa") { response.Message("Getting Closer to WOW"); } else if (requestBody == @"yes") // welcome accept { string msg = MerchantController.AcceptWelcomeMessage(merchant.merchant_id, true); response.Message(msg); } else if (requestBody == @"status") { response.Message(@"not closed"); } else if (requestBody == @"testurl") { string msg = @"https://www.google.com"; response.Message(msg); } else if (requestBody == @"testnew") { string welcomeMsg = MerchantController.BuildWelcomeMessage(merchant); response.Message(welcomeMsg); } else if (requestBody == @"testaccept") { string welcomeMsg = MerchantController.TestWelcomeAccept(merchant.merchant_id); response.Message(welcomeMsg); } else { response.Message($"Sorry I do not understand [{requestBody}], text help? to see a list of the available commmands."); } return(TwiML(response)); }
public MessagingResponse GetResponse(string messageBody, string messagePhone) { //Recoit Un message et le numero de telephone, Si le message correspont au norme et est trouver, //un MessageStatus.Closed/MessageStatus.Follow est appliquer sinon envoie un erreur var answer = new Message(); if (messageBody.Length > 5 && (messageBody.ToUpper().StartsWith(_InputMessages[0]) || messageBody.ToUpper().StartsWith(_InputMessages[1]))) { string flight_id = messageBody.ToUpper().Substring(5); if (Regex.IsMatch(flight_id, NotificationApp.NumVolRegex)) { Notification notif = DB2.Aeroport().Notifications.SingleOrDefault(m => m.Num_Phone == messagePhone); MessageStatus status = (notif != null) ? MessageStatus.Closed : MessageStatus.Error; string result = MessageDistributor(status, notif); answer.Body(result); //If status is Closed then set to True if (status == MessageStatus.Closed) { db.Entry(notif).Property(u => u.Statut).CurrentValue = true; } } else { answer.Body(MessageDistributor(MessageStatus.Error)); } } else if (messageBody.Length > 5 && (messageBody.ToUpper().StartsWith(_InputMessages[2]) || messageBody.ToUpper().StartsWith(_InputMessages[3]))) { string flight_id = messageBody.ToUpper().Substring(5); if (Regex.IsMatch(flight_id, NotificationApp.NumVolRegex)) { Notification notif = db.Notifications.SingleOrDefault(m => m.Num_Phone == messagePhone); MessageStatus status = (notif != null) ? MessageStatus.Followed : MessageStatus.Error; string result = MessageDistributor(status, notif); answer.Body(result); //If status is Followed then set to False if (status == MessageStatus.Followed) { db.Entry(notif).Property(u => u.Statut).CurrentValue = false; } } else { answer.Body(MessageDistributor(MessageStatus.Error)); } } else { answer.Body(MessageDistributor(MessageStatus.Error)); } var messageResponce = new MessagingResponse(); messageResponce.Append(answer); return(messageResponce); }
public static async Task <Object> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage reqm, HttpRequest req, ILogger log) { log.LogInformation("Main Request"); string GUID = req.Query["GUID"]; log.LogInformation(GUID); Records RecordsObj = (Records) await GetRecord(GUID, new Records()); var data = await reqm.Content.ReadAsStringAsync(); var formValues = data.Split('&') .Select(value => value.Split('=')) .ToDictionary(pair => Uri.UnescapeDataString(pair[0]).Replace("+", " "), pair => Uri.UnescapeDataString(pair[1]).Replace("+", " ")); var response = new MessagingResponse() .Message($"Your Message {formValues["Body"]}"); var twiml = response.ToString(); twiml = twiml.Replace("utf-16", "utf-8"); var smsBody = formValues["Body"]; var smsFrom = formValues["From"]; var smsID = formValues["MessageSid"]; var smsDate = DateTime.Now; string dateString = smsDate.ToString(); string platform = RecordsObj.Platform; log.LogInformation(platform); if (platform == "NWC" || platform == "nwc" || platform == "Nwc") { string NWCurl = RecordsObj.NWCurl; var NWCPayLoad = new { se_number = smsFrom, se_body = smsBody }; string NWCTaskjson = JsonConvert.SerializeObject(NWCPayLoad); StringContent nwctaskdata = new StringContent(NWCTaskjson, Encoding.UTF8, "application/json"); var client = new HttpClient(); var taskresponse = await client.PostAsync(NWCurl, nwctaskdata); client.Dispose(); return(RecordsObj.ReturnMessage); } if (platform == "K2" || platform == "k2") { string K2Url = RecordsObj.K2Url; log.LogInformation(K2Url); string K2User = RecordsObj.K2User; log.LogInformation(K2User); string K2Pass = RecordsObj.K2Pass; log.LogInformation(K2Pass); log.LogInformation("C# HTTP trigger function processed a request."); HttpClient k2CloudClient; NetworkCredential k2credentials = new NetworkCredential(K2User, K2Pass); HttpClientHandler loginHandler = new HttpClientHandler { Credentials = k2credentials }; k2CloudClient = new HttpClient(loginHandler, true); string requesturi = K2Url; string instanceDataJSON; string body = smsBody; string number = smsFrom; DataFields myDF = new DataFields(); myDF.Body = body; myDF.Number = number; WorkflowInstance myInstance = new WorkflowInstance() { Folio = "Process started via Twilio SMS", Priority = 1, DataFields = myDF }; using (MemoryStream ms = new MemoryStream()) { DataContractJsonSerializer mySerializerWI = new DataContractJsonSerializer(myInstance.GetType()); mySerializerWI.WriteObject(ms, myInstance); StreamReader reader = new StreamReader(ms); ms.Position = 0; instanceDataJSON = reader.ReadToEnd(); } StringContent datacontent = new StringContent(instanceDataJSON, Encoding.UTF8, "application/json"); var task = k2CloudClient.PostAsync(requesturi, datacontent); HttpResponseMessage myResponse = task.Result; return(RecordsObj.ReturnMessage); } else { return("Missing Platform"); } }
public async Task <ActionResult> IncomingMessage([FromQuery] TwilioMessage request) { if (request == null || string.IsNullOrWhiteSpace(request.To) || string.IsNullOrWhiteSpace(request.From) || string.IsNullOrWhiteSpace(request.Body)) { return(BadRequest()); } var response = new MessagingResponse(); var textMessage = new TextMessage(); textMessage.To = request.To.Replace("+", ""); textMessage.Msisdn = request.From.Replace("+", ""); textMessage.MessageId = request.MessageSid; textMessage.Timestamp = DateTime.UtcNow.ToLongDateString(); textMessage.Data = request.Body; textMessage.Text = request.Body; var messageEvent = new InboundMessageEvent(); messageEvent.MessageType = (int)InboundMessageTypes.TextMessage; messageEvent.RecievedOn = DateTime.UtcNow; messageEvent.Type = typeof(InboundMessageEvent).FullName; messageEvent.Data = JsonConvert.SerializeObject(textMessage); messageEvent.Processed = false; messageEvent.CustomerId = ""; try { UserProfile userProfile = null; var departmentId = await _departmentSettingsService.GetDepartmentIdByTextToCallNumberAsync(textMessage.To); if (!departmentId.HasValue) { userProfile = await _userProfileService.GetProfileByMobileNumberAsync(textMessage.Msisdn); if (userProfile != null) { var department = await _departmentsService.GetDepartmentByUserIdAsync(userProfile.UserId); if (department != null) { departmentId = department.DepartmentId; } } } if (departmentId.HasValue) { var department = await _departmentsService.GetDepartmentByIdAsync(departmentId.Value); var textToCallEnabled = await _departmentSettingsService.GetDepartmentIsTextCallImportEnabledAsync(departmentId.Value); var textCommandEnabled = await _departmentSettingsService.GetDepartmentIsTextCommandEnabledAsync(departmentId.Value); var dispatchNumbers = await _departmentSettingsService.GetTextToCallSourceNumbersForDepartmentAsync(departmentId.Value); var authroized = await _limitsService.CanDepartmentProvisionNumberAsync(departmentId.Value); var customStates = await _customStateService.GetAllActiveCustomStatesForDepartmentAsync(departmentId.Value); messageEvent.CustomerId = departmentId.Value.ToString(); if (authroized) { bool isDispatchSource = false; if (!String.IsNullOrWhiteSpace(dispatchNumbers)) { isDispatchSource = _numbersService.DoesNumberMatchAnyPattern(dispatchNumbers.Split(Char.Parse(",")).ToList(), textMessage.Msisdn); } // If we don't have dispatchNumbers and Text Command isn't enabled it's a dispatch text if (!isDispatchSource && !textCommandEnabled) { isDispatchSource = true; } if (isDispatchSource && textToCallEnabled) { var c = new Call(); c.Notes = textMessage.Text; c.NatureOfCall = textMessage.Text; c.LoggedOn = DateTime.UtcNow; c.Name = string.Format("TTC {0}", c.LoggedOn.TimeConverter(department).ToString("g")); c.Priority = (int)CallPriority.High; c.ReportingUserId = department.ManagingUserId; c.Dispatches = new Collection <CallDispatch>(); c.CallSource = (int)CallSources.EmailImport; c.SourceIdentifier = textMessage.MessageId; c.DepartmentId = departmentId.Value; var users = await _departmentsService.GetAllUsersForDepartmentAsync(departmentId.Value, true); foreach (var u in users) { var cd = new CallDispatch(); cd.UserId = u.UserId; c.Dispatches.Add(cd); } var savedCall = await _callsService.SaveCallAsync(c); var cqi = new CallQueueItem(); cqi.Call = savedCall; cqi.Profiles = await _userProfileService.GetSelectedUserProfilesAsync(users.Select(x => x.UserId).ToList()); cqi.DepartmentTextNumber = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(cqi.Call.DepartmentId); _queueService.EnqueueCallBroadcastAsync(cqi); messageEvent.Processed = true; } if (!isDispatchSource && textCommandEnabled) { var profile = await _userProfileService.GetProfileByMobileNumberAsync(textMessage.Msisdn); if (profile != null) { var payload = _textCommandService.DetermineType(textMessage.Text); var customActions = customStates.FirstOrDefault(x => x.Type == (int)CustomStateTypes.Personnel); var customStaffing = customStates.FirstOrDefault(x => x.Type == (int)CustomStateTypes.Staffing); switch (payload.Type) { case TextCommandTypes.None: response.Message("Resgrid (https://resgrid.com) Automated Text System. Unknown command, text help for supported commands."); break; case TextCommandTypes.Help: messageEvent.Processed = true; var help = new StringBuilder(); help.Append("Resgrid Text Commands" + Environment.NewLine); help.Append("---------------------" + Environment.NewLine); help.Append("These are the commands you can text to alter your status and staffing. Text help for help." + Environment.NewLine); help.Append("---------------------" + Environment.NewLine); help.Append("Core Commands" + Environment.NewLine); help.Append("---------------------" + Environment.NewLine); help.Append("STOP: To turn off all text messages" + Environment.NewLine); help.Append("HELP: This help text" + Environment.NewLine); help.Append("CALLS: List active calls" + Environment.NewLine); help.Append("C[CallId]: Get Call Detail i.e. C1445" + Environment.NewLine); help.Append("UNITS: List unit statuses" + Environment.NewLine); help.Append("---------------------" + Environment.NewLine); help.Append("Status or Action Commands" + Environment.NewLine); help.Append("---------------------" + Environment.NewLine); if (customActions != null && customActions.IsDeleted == false && customActions.GetActiveDetails() != null && customActions.GetActiveDetails().Any()) { var activeDetails = customActions.GetActiveDetails(); for (int i = 0; i < activeDetails.Count; i++) { help.Append($"{activeDetails[i].ButtonText.Trim().Replace(" ", "").Replace("-", "").Replace(":", "")} or {i + 1}: {activeDetails[i].ButtonText}" + Environment.NewLine); } } else { help.Append("responding or 1: Responding" + Environment.NewLine); help.Append("notresponding or 2: Not Responding" + Environment.NewLine); help.Append("onscene or 3: On Scene" + Environment.NewLine); help.Append("available or 4: Available" + Environment.NewLine); } help.Append("---------------------" + Environment.NewLine); help.Append("Staffing Commands" + Environment.NewLine); help.Append("---------------------" + Environment.NewLine); if (customStaffing != null && customStaffing.IsDeleted == false && customStaffing.GetActiveDetails() != null && customStaffing.GetActiveDetails().Any()) { var activeDetails = customStaffing.GetActiveDetails(); for (int i = 0; i < activeDetails.Count; i++) { help.Append($"{activeDetails[i].ButtonText.Trim().Replace(" ", "").Replace("-", "").Replace(":", "")} or S{i + 1}: {activeDetails[i].ButtonText}" + Environment.NewLine); } } else { help.Append("available or s1: Available Staffing" + Environment.NewLine); help.Append("delayed or s2: Delayed Staffing" + Environment.NewLine); help.Append("unavailable or s3: Unavailable Staffing" + Environment.NewLine); help.Append("committed or s4: Committed Staffing" + Environment.NewLine); help.Append("onshift or s4: On Shift Staffing" + Environment.NewLine); } response.Message(help.ToString()); //_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Help", help.ToString(), department.DepartmentId, textMessage.To, profile); break; case TextCommandTypes.Action: messageEvent.Processed = true; await _actionLogsService.SetUserActionAsync(profile.UserId, department.DepartmentId, (int)payload.GetActionType()); response.Message(string.Format("Resgrid received your text command. Status changed to: {0}", payload.GetActionType())); //_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Status", string.Format("Resgrid recieved your text command. Status changed to: {0}", payload.GetActionType()), department.DepartmentId, textMessage.To, profile); break; case TextCommandTypes.Staffing: messageEvent.Processed = true; await _userStateService.CreateUserState(profile.UserId, department.DepartmentId, (int)payload.GetStaffingType()); response.Message(string.Format("Resgrid received your text command. Staffing level changed to: {0}", payload.GetStaffingType())); //_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Staffing", string.Format("Resgrid recieved your text command. Staffing level changed to: {0}", payload.GetStaffingType()), department.DepartmentId, textMessage.To, profile); break; case TextCommandTypes.Stop: messageEvent.Processed = true; await _userProfileService.DisableTextMessagesForUserAsync(profile.UserId); response.Message("Text messages are now turned off for this user, to enable again log in to Resgrid and update your profile."); break; case TextCommandTypes.CustomAction: messageEvent.Processed = true; await _actionLogsService.SetUserActionAsync(profile.UserId, department.DepartmentId, payload.GetCustomActionType()); if (customActions != null && customActions.IsDeleted == false && customActions.GetActiveDetails() != null && customActions.GetActiveDetails().Any() && customActions.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomActionType()) != null) { var detail = customActions.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomActionType()); response.Message(string.Format("Resgrid received your text command. Status changed to: {0}", detail.ButtonText)); } else { response.Message("Resgrid received your text command and updated your status"); } break; case TextCommandTypes.CustomStaffing: messageEvent.Processed = true; await _userStateService.CreateUserState(profile.UserId, department.DepartmentId, payload.GetCustomStaffingType()); if (customStaffing != null && customStaffing.IsDeleted == false && customStaffing.GetActiveDetails() != null && customStaffing.GetActiveDetails().Any() && customStaffing.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomStaffingType()) != null) { var detail = customStaffing.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomStaffingType()); response.Message(string.Format("Resgrid received your text command. Staffing changed to: {0}", detail.ButtonText)); } else { response.Message("Resgrid received your text command and updated your staffing"); } break; case TextCommandTypes.MyStatus: messageEvent.Processed = true; var userStatus = await _actionLogsService.GetLastActionLogForUserAsync(profile.UserId); var userStaffing = await _userStateService.GetLastUserStateByUserIdAsync(profile.UserId); var customStatusLevel = await _customStateService.GetCustomPersonnelStatusAsync(department.DepartmentId, userStatus); var customStaffingLevel = await _customStateService.GetCustomPersonnelStaffingAsync(department.DepartmentId, userStaffing); response.Message($"Hello {profile.FullName.AsFirstNameLastName} at {DateTime.UtcNow.TimeConverterToString(department)} your current status is {customStatusLevel.ButtonText} and your current staffing is {customStaffingLevel.ButtonText}."); break; case TextCommandTypes.Calls: messageEvent.Processed = true; var activeCalls = await _callsService.GetActiveCallsByDepartmentAsync(department.DepartmentId); var activeCallText = new StringBuilder(); activeCallText.Append($"Active Calls for {department.Name}" + Environment.NewLine); activeCallText.Append("---------------------" + Environment.NewLine); foreach (var activeCall in activeCalls) { activeCallText.Append($"CallId: {activeCall.CallId} Name: {activeCall.Name} Nature:{activeCall.NatureOfCall}" + Environment.NewLine); } response.Message(activeCallText.ToString().Truncate(1200)); break; case TextCommandTypes.Units: messageEvent.Processed = true; var unitStatus = await _unitsService.GetAllLatestStatusForUnitsByDepartmentIdAsync(department.DepartmentId); var unitStatusesText = new StringBuilder(); unitStatusesText.Append($"Unit Statuses for {department.Name}" + Environment.NewLine); unitStatusesText.Append("---------------------" + Environment.NewLine); foreach (var unit in unitStatus) { var unitState = await _customStateService.GetCustomUnitStateAsync(unit); unitStatusesText.Append($"{unit.Unit.Name} is {unitState.ButtonText}" + Environment.NewLine); } response.Message(unitStatusesText.ToString().Truncate(1200)); break; case TextCommandTypes.CallDetail: messageEvent.Processed = true; var call = await _callsService.GetCallByIdAsync(int.Parse(payload.Data)); var callText = new StringBuilder(); callText.Append($"Call Information for {call.Name}" + Environment.NewLine); callText.Append("---------------------" + Environment.NewLine); callText.Append($"Id: {call.CallId}" + Environment.NewLine); callText.Append($"Number: {call.Number}" + Environment.NewLine); callText.Append($"Logged: {call.LoggedOn.TimeConverterToString(department)}" + Environment.NewLine); callText.Append("-----Nature-----" + Environment.NewLine); callText.Append(call.NatureOfCall + Environment.NewLine); callText.Append("-----Address-----" + Environment.NewLine); if (!String.IsNullOrWhiteSpace(call.Address)) { callText.Append(call.Address + Environment.NewLine); } else if (!string.IsNullOrEmpty(call.GeoLocationData)) { try { string[] points = call.GeoLocationData.Split(char.Parse(",")); if (points != null && points.Length == 2) { callText.Append(_geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(points[0]), double.Parse(points[1])) + Environment.NewLine); } } catch { } } response.Message(callText.ToString()); break; } } } } } else if (textMessage.To == "17753765253") // Resgrid master text number { var profile = await _userProfileService.GetProfileByMobileNumberAsync(textMessage.Msisdn); var payload = _textCommandService.DetermineType(textMessage.Text); switch (payload.Type) { case TextCommandTypes.None: response.Message("Resgrid (https://resgrid.com) Automated Text System. Unknown command, text help for supported commands."); break; case TextCommandTypes.Help: messageEvent.Processed = true; var help = new StringBuilder(); help.Append("Resgrid Text Commands" + Environment.NewLine); help.Append("---------------------" + Environment.NewLine); help.Append("This is the Resgrid system for first responders (https://resgrid.com) automated text system. Your department isn't signed up for inbound text messages, but you can send the following commands." + Environment.NewLine); help.Append("---------------------" + Environment.NewLine); help.Append("STOP: To turn off all text messages" + Environment.NewLine); help.Append("HELP: This help text" + Environment.NewLine); response.Message(help.ToString()); break; case TextCommandTypes.Stop: messageEvent.Processed = true; await _userProfileService.DisableTextMessagesForUserAsync(profile.UserId); response.Message("Text messages are now turned off for this user, to enable again log in to Resgrid and update your profile."); break; } } } catch (Exception ex) { Framework.Logging.LogException(ex); } finally { await _numbersService.SaveInboundMessageEventAsync(messageEvent); } //Ok(); //var response = new TwilioResponse(); //return Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter()); //return Ok(new StringContent(response.ToString(), Encoding.UTF8, "application/xml")); return(new ContentResult { Content = response.ToString(), ContentType = "application/xml", StatusCode = 200 }); }
/// <summary> /// Returns a properly formatted TwiML response /// </summary> /// <param name="response"></param> /// <param name="encoding">Encoding to use for Xml</param> /// <returns></returns> // ReSharper disable once InconsistentNaming public TwiMLResult TwiML(MessagingResponse response, Encoding encoding) { return(new TwiMLResult(response, encoding)); }
/// <summary> /// Returns a properly formatted TwiML response /// </summary> /// <param name="response"></param> /// <returns></returns> // ReSharper disable once InconsistentNaming public TwiMLResult TwiML(MessagingResponse response) { return(new TwiMLResult(response)); }
public ActionResult SmsResponse() { var messagingResponse = new MessagingResponse(); System.Diagnostics.Debug.WriteLine("SMS Response" + " " + Request["from"] + " " + Request["body"]); if (Request["body"].ToLower() == "yes") { var users = DatabaseUserService.GetMultipleByPhone(Request["from"]); Patient user = null; Notification newest = null; foreach (var u in users) { var patT = DatabasePatientService.GetByUserIdActive(u.UserId); var notificationsT = DatabaseNotificationService.GetByPatientId(patT.PatientId); var newestT = notificationsT[0]; foreach (var n in notificationsT) { if (newestT.SentTime > n.SentTime) { newestT = n; } } if (newestT.Sent && newestT.SentTime > DateTime.Now.AddMinutes(-10)) { user = patT; newest = newestT; } } user.LoadUserData(); newest.NotificationResponse = Request["body"]; DatabaseNotificationService.Update(newest); var pres = DatabasePrescriptionService.GetByPatientId(user.PatientId); var refill = DatabaseRefillService.GetByPrescriptionId(pres.PrescriptionId); refill.RefillIt = true; DatabaseRefillService.Update(refill); messagingResponse.Message("Thanks, your prescription will be ready shortly"); } else if (Request["body"].ToLower() == "stop") { var user = DatabaseUserService.GetByPhoneActive(Request["from"]); var pat = DatabasePatientService.GetByUserIdActive(user.UserId); var notifications = DatabaseNotificationService.GetByPatientId(pat.PatientId); var newest = notifications[0]; foreach (var n in notifications) { if (newest.SentTime < n.SentTime) { newest = n; } } if (newest.Type == Notification.NotificationType.Refill) { pat.SendRefillMessage = false; messagingResponse.Message("You have been unsubscribed from refill notifications"); } else if (newest.Type == Notification.NotificationType.Birthday) { pat.SendBirthdayMessage = false; messagingResponse.Message("You have been unsubscribed from birthday notifications"); } else if (newest.Type == Notification.NotificationType.Ready) { pat.SendRefillMessage = false; messagingResponse.Message("You have been unsubscribed from refill notifications"); } DatabasePatientService.Update(pat); } else if (Request["body"].ToLower() == "stop all") { var user = DatabaseUserService.GetByPhoneActive(Request["from"]); var pat = DatabasePatientService.GetByUserIdActive(user.UserId); pat.ContactMethod = Patient.PrimaryContactMethod.OptOut; } return(new TwiMLResult(messagingResponse)); }