public void Example_2b() { var response = new TwilioResponse(); response.DialConference("1234", new { startConferenceOnEnter = false, endConferenceOnExit = true }); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Dial() { var response = new TwilioResponse(); response.Dial("555-111-2222"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Dial_Multiple_Numbers() { var response = new TwilioResponse(); response.DialNumbers("555-111-1111", "555-222-2222", "555-333-3333"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_3() { var response = new TwilioResponse(); response.DialConference("SimpleRoom", new { muted = true }); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Dial_And_Attributes() { var response = new TwilioResponse(); response.Dial("555-111-2222", new { action = "dial.xml", method = "GET", timeout = "30", hangupOnStar = "true", timeLimit = "1000", callerId = "555-111-2222" }); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Dial_Conference_And_Attributes() { var response = new TwilioResponse(); response.DialConference("room1", new { muted = true, beep = false, waitUrl = "wait.xml", waitMethod = "GET" }); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Dial_Conference() { var response = new TwilioResponse(); response.DialConference("room1"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_1() { var response = new TwilioResponse(); response.Dial(new Number("415-123-4567", new { sendDigits = "wwww1928" })); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_2() { var response = new TwilioResponse(); response.DialNumbers("858-987-6543", "415-123-4567", "619-765-4321"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_2() { var response = new TwilioResponse(); response.Redirect("../nextInstructions"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Single_Hangup() { var response = new TwilioResponse(); response.Hangup(); Assert.True(IsValidTwiML(response.ToXDocument())); }
public void Example_1() { var response = new TwilioResponse(); response.Gather(); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_1() { var response = new TwilioResponse(); response.Redirect("http://www.foo.com/nextInstructions"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Gather_With_All_Options() { var response = new TwilioResponse(); response.Gather(new { action = "example.xml", timeout = 10, method = "GET", finishOnKey = "#", numDigits = 3 }); Assert.True(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Gather_With_No_Options() { var response = new TwilioResponse(); response.Gather(); Assert.True(IsValidTwiML(response.ToXDocument())); }
public void Example_2() { var response = new TwilioResponse(); response.Say("Hello world", new { voice = "woman", loop = 2 }); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_2() { var response = new TwilioResponse(); response.Sms("Store Location: 123 Easy St.", new { action = "/SmsHandler.php", method = "POST" }); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_3() { var response = new TwilioResponse(); response.Sms("Store Location: 123 Easy St.", new { statusCallback = "/SMSHandler.php" }); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_1() { var response = new TwilioResponse(); response.Sms("Store Location: 123 Easy St."); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void _1_0() { var response = new TwilioResponse(); response.Sms("Hello, Mobile Monkey"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Dial_And_Client_Noun() { var response = new TwilioResponse(); response.Dial(new Client("Jenny")); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_1() { var response = new TwilioResponse(); response.Play("http://foo.com/cowbell.mp3"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Single_Say_And_Attributes() { var response = new TwilioResponse(); response.Say("Hello world", new { language = "en" }); Assert.True(IsValidTwiML(response.ToXDocument())); }
public void Example_2() { var response = new TwilioResponse(); response.Reject("busy"); Assert.True(IsValidTwiML(response.ToXDocument())); }
public void Example_5b() { var response = new TwilioResponse(); response.DialConference("Customer Waiting Room", new { beep = false, endConferenceOnExit = true }); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Single_Say() { var response = new TwilioResponse(); response.Say("Hello world"); Assert.True(IsValidTwiML(response.ToXDocument())); }
public void Can_Generate_Single_Record() { var response = new TwilioResponse(); response.Record(); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_4() { var response = new TwilioResponse(); response.DialConference("NoMusicNoBeepRoom", new { beep = false, waitUrl = "", startConferenceOnEnter = true, endConferenceOnExit = false }); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_1() { var response = new TwilioResponse(); response.Say("Hello world"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public void Example_1() { var response = new TwilioResponse(); response.DialConference("1234"); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
/// <summary> /// /// </summary> /// <param name="response"></param> private void BeginMenu(TwilioResponse response) { response.BeginGather(new { numDigits = 1, action = GetAction("DoMenu", controller: "VoiceAdmin"), timeout = 10 }); }
void OnCompleted(WorkflowApplicationCompletedEventArgs args) { // we're done, hang up on the user TwilioResponse.Add(new XElement("Hangup")); }
/// <summary> /// Invoked when a web request arrives. /// </summary> public void ProcessRequest(HttpContext context) { try { // bind ourselves to the context Context = context; // request was for a resource if (Request[ResourceQueryKey] != null) { // handle it and return, no need to deal with workflow ProcessResourceRequest(Request[ResourceQueryKey]); return; } // obtain our activity instance Activity = CreateActivity(); // configure application WorkflowApplication = Request[InstanceIdQueryKey] == null ? new WorkflowApplication(Activity, GetArguments()) : new WorkflowApplication(Activity); WorkflowApplication.Extensions.Add <ITwilioContext>(() => this); WorkflowApplication.SynchronizationContext = new SynchronizedSynchronizationContext(); WorkflowApplication.InstanceStore = CreateInstanceStore(); WorkflowApplication.Aborted = OnAborted; WorkflowApplication.Completed = OnCompleted; WorkflowApplication.Idle = OnIdle; WorkflowApplication.OnUnhandledException = OnUnhandledException; WorkflowApplication.PersistableIdle = OnPersistableIdle; WorkflowApplication.Unloaded = OnUnloaded; // attempt to resolve current instance id and reload workflow state if (Request[InstanceIdQueryKey] != null) { WorkflowApplication.Load(Guid.Parse(Request[InstanceIdQueryKey]), Timeout); } // postback to resume a bookmark if (Request[BookmarkQueryKey] != null) { WorkflowApplication.ResumeBookmark(Request[BookmarkQueryKey], GetPostData(), Timeout); } else { // begin running the workflow from the start WorkflowApplication.Run(Timeout); } // throw exception if (UnhandledExceptionInfo != null) { UnhandledExceptionInfo.Throw(); } // strip off temporary attributes foreach (var element in TwilioResponse.DescendantsAndSelf()) { foreach (var attribute in element.Attributes()) { if (attribute.Name.Namespace == tmpNs) { attribute.Remove(); } } } // write finished twilio output Response.ContentType = "text/xml"; using (var wrt = XmlWriter.Create(Response.Output)) TwilioResponse.WriteTo(wrt); // if we've reached the end, no need to force unload WorkflowApplication = null; } finally { // clean up application if possible if (WorkflowApplication != null) { try { WorkflowApplication.Unload(Timeout); WorkflowApplication = null; } catch { // ignore } } } }
public static void SayVoice(this TwilioResponse response, string format, params object[] args) { response.Say(string.Format(format, args), new { voice = "woman" }); }
private TwilioResponse AddVoiceMail(TwilioResponse response) { return(string.IsNullOrEmpty(settings.VoiceMail) ? response.Say("") : response.Play(EncodePlay(settings.VoiceMail)).Record(new { method = "POST", action = GetEcho("voiceMail"), maxLength = 30 })); }
/// <summary> /// Returns a property formatted TwiML response /// </summary> /// <param name="response"></param> /// <returns></returns> public TwiMLResult TwiML(TwilioResponse response) { return(new TwiMLResult(Request, response)); }
public HttpResponseMessage IncomingMessage([FromUri] TwilioMessage request) { if (request == null || string.IsNullOrWhiteSpace(request.To) || string.IsNullOrWhiteSpace(request.From) || string.IsNullOrWhiteSpace(request.Body)) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } var response = new TwilioResponse(); 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 { var departmentId = _departmentSettingsService.GetDepartmentIdByTextToCallNumber(textMessage.To); if (departmentId.HasValue) { var department = _departmentsService.GetDepartmentById(departmentId.Value); var textToCallEnabled = _departmentSettingsService.GetDepartmentIsTextCallImportEnabled(departmentId.Value); var textCommandEnabled = _departmentSettingsService.GetDepartmentIsTextCommandEnabled(departmentId.Value); var dispatchNumbers = _departmentSettingsService.GetTextToCallSourceNumbersForDepartment(departmentId.Value); var authroized = _limitsService.CanDepartmentProvisionNumber(departmentId.Value); var customStates = _customStateService.GetAllActiveCustomStatesForDepartment(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 = _departmentsService.GetAllUsersForDepartment(departmentId.Value, true); foreach (var u in users) { var cd = new CallDispatch(); cd.UserId = u.UserId; c.Dispatches.Add(cd); } var savedCall = _callsService.SaveCall(c); var cqi = new CallQueueItem(); cqi.Call = savedCall; cqi.Profiles = _userProfileService.GetSelectedUserProfiles(users.Select(x => x.UserId).ToList()); cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId); _queueService.EnqueueCallBroadcast(cqi); messageEvent.Processed = true; } if (!isDispatchSource && textCommandEnabled) { var profile = _userProfileService.FindProfileByMobileNumber(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; _actionLogsService.SetUserAction(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; _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; _userProfileService.DisableTextMessagesForUser(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; _actionLogsService.SetUserAction(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; _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 = _actionLogsService.GetLastActionLogForUser(profile.UserId); var userStaffing = _userStateService.GetLastUserStateByUserId(profile.UserId); var customStatusLevel = _customStateService.GetCustomPersonnelStatus(department.DepartmentId, userStatus); var customStaffingLevel = _customStateService.GetCustomPersonnelStaffing(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 = _callsService.GetActiveCallsByDepartment(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()); break; case TextCommandTypes.Units: messageEvent.Processed = true; var unitStatus = _unitsService.GetAllLatestStatusForUnitsByDepartmentId(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 = _customStateService.GetCustomUnitState(unit); unitStatusesText.Append($"{unit.Unit.Name} is {unitState.ButtonText}" + Environment.NewLine); } response.Message(unitStatusesText.ToString()); break; case TextCommandTypes.CallDetail: messageEvent.Processed = true; var call = _callsService.GetCallById(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 = _userProfileService.FindProfileByMobileNumber(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; _userProfileService.DisableTextMessagesForUser(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 { _numbersService.SaveInboundMessageEvent(messageEvent); } //return Request.CreateResponse(HttpStatusCode.OK); //var response = new TwilioResponse(); return(Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter())); }
public void Example_6() { var response = new TwilioResponse(); response.Dial(new Conference("LoveTwilio"), new { action = "handleLeaveConference.php", method = "POST", hangupOnStar = "true", timeLimit = 30 }); }
public ActionResult Hello() { var response = new TwilioResponse(); response.Say(name); return TwiML(response); }
public TwiMLResult(TwilioResponse response) { data = response.ToXDocument(); }
private TwilioResponse AddVoiceMail(TwilioResponse response) { return(settings.VoiceMail == null || !settings.VoiceMail.Enabled ? response : response.Play(settings.VoiceMail.Url).Record(new { method = "GET", action = GetEcho("voiceMail"), maxLength = settings.VoiceMail.TimeOut })); }
public HttpResponseMessage VoiceCall(string userId, int callId) { var response = new TwilioResponse(); var call = _callsService.GetCallById(callId); if (call == null) { response.Say("This call has been closed. Goodbye.").Hangup(); return(Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter())); } if (call.State == (int)CallStates.Cancelled || call.State == (int)CallStates.Closed || call.IsDeleted) { response.Say(string.Format("This call, Id {0} has been closed. Goodbye.", call.Number)).Hangup(); return(Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter())); } var stations = _departmentGroupsService.GetAllStationGroupsForDepartment(call.DepartmentId); string address = call.Address; if (String.IsNullOrWhiteSpace(address) && !string.IsNullOrWhiteSpace(call.GeoLocationData)) { try { string[] points = call.GeoLocationData.Split(char.Parse(",")); if (points != null && points.Length == 2) { address = _geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(points[0]), double.Parse(points[1])); } } catch { } } if (String.IsNullOrWhiteSpace(address) && !String.IsNullOrWhiteSpace(call.Address)) { address = call.Address; } StringBuilder sb = new StringBuilder(); if (!String.IsNullOrWhiteSpace(address)) { sb.Append(string.Format("{0}, Priority {1} Address {2} Nature {3}", call.Name, call.GetPriorityText(), call.Address, call.NatureOfCall)); } else { sb.Append(string.Format("{0}, Priority {1} Nature {2}", call.Name, call.GetPriorityText(), call.NatureOfCall)); } sb.Append(", Press 0 to repeat, Press 1 to respond to the scene"); for (int i = 0; i < stations.Count; i++) { if (i >= 8) { break; } sb.Append(string.Format(", press {0} to respond to {1}", i + 2, stations[i].Name)); } response.BeginGather(new { numDigits = 1, timeout = 10, method = "GET", action = string.Format("{0}/Twilio/VoiceCallAction/{1}/{2}", Config.SystemBehaviorConfig.ResgridApiBaseUrl, userId, callId) }).Say(sb.ToString()).EndGather().Pause(10).Hangup(); return(Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter())); }
public HttpResponseMessage Menu_Selection(VoiceRequest request) { var response = new TwilioResponse(); if (request.Digits == "4") { response.Redirect("/ivr/record/" + CallType.Unknown); return(TWiML(response)); } var record = true; var type = CallType.Unknown; response.BeginGather(new { action = "record/" + type }); // "To skip these recordings and leave a message, press 1 at any time. " response.Play("/audio/skip.mp3"); switch (request.Digits) { case ("1"): { // "The house sits on the corner of West Ellsworth and Bannock located in the heart of the historic Baker neighborhood. " + // "There is over 1700 finished square feet in this classic contemporary town-home, built in the 1890s. " + // "The house has been updated with modern finishes, like the walnut cabinets, granite counter-tops and stainless steel appliances. " + // "There are two bedrooms upstairs and a non-conforming master bedroom in the basement that could also serve as a theater room, den or man-cave. " + // "The kitchen has granite counter-tops and new stainless steel appliances. " + // "This location is perfect for urban commuters. It's only a few blocks from the light-rail station, and the zero bus (which runs downtown every 15 minutes). " + // "Located two blocks off Broadway, the house is a stone's throw from many great restaurants, boutiques, coffee shops and an ice-cream parlor. " + // "Not to mention the thriving nightlife. " + // "There is beautiful hardwood floors, brand-new high-quality carpet, sky lights and two great travertine tiled bathrooms, " + // "one with a full tub the other with a two-person shower. " + // "The asking price is 375 thousand. " response.Play("/audio/description.mp3"); record = false; break; } case ("2"): { // "This house is for sale by owner. The owner will work with buyers agents. " + // "To gain access to the home, please leave a message with your full name, company name, mobile number, buyers name and the date and time you would like to view the home. " + // "When approved, you will receive a text with the lock-box access code. " response.Play("/audio/agents.mp3"); type = CallType.Agent; break; } case ("3"): { // "To schedule a viewing please leave a message with your full name, drivers license number, cell-phone number and the date and time you would like to view the home. " + // "When approved, you will receive a text with the lock-box access code. "+ // "To speak directly to the owner, press 2. " response.Play("/audio/non-agent.mp3"); type = CallType.NonAgent; break; } case ("4"): { type = CallType.Request; break; } } response.EndGather(); response.Redirect(record ? "/ivr/record/" + type : "menu"); return(TWiML(response)); }
public void Can_Generate_Empty_Response() { var response = new TwilioResponse(); Assert.IsTrue(IsValidTwiML(response.ToXDocument())); }
public async Task <TwilioResponse> DoSignInOut(TwilioRequest request) { var response = new TwilioResponse(); using (var db = dbFactory()) { var signin = await db.SignIns.Where(f => f.MemberId == this.session.MemberId).OrderByDescending(f => f.TimeIn).FirstOrDefaultAsync(); var call = await db.Calls.SingleAsync(f => f.CallId == request.CallSid); DateTimeOffset time = TimeUtils.GetLocalDateTime(this.config); var sayDate = TimeUtils.GetMiltaryTimeVoiceText(time); if (signin == null || signin.TimeOut.HasValue) { if (this.session.IsSignedIn) { throw new InvalidOperationException("Tried to sign out when not signed in"); } signin = new MemberSignIn { MemberId = this.session.MemberId, isMember = true, Name = this.session.MemberName, TimeIn = time, EventId = (this.CurrentEvents.Count == 1) ? this.CurrentEvents[0].Id : this.session.EventId, }; db.SignIns.Add(signin); call.Actions.Add(new CallAction { Call = call, CallId = call.Id, Time = signin.TimeIn, Action = "Signed in " + signin.Name }); await db.SaveChangesAsync(); this.session.IsSignedIn = true; if (this.CurrentEvents.Count == 0) { await RosterController.AssignInternal(signin, null, db, this.config); BeginMenu(response); response.SayVoice(Speeches.SignedInUnassignedTemplate, this.session.MemberName, sayDate); await EndMenu(response); } else if (this.CurrentEvents.Count == 1) { await RosterController.AssignInternal(signin, this.CurrentEvents[0].Id, db, this.config); BeginMenu(response); response.SayVoice(Speeches.SignedInTemplate, this.CurrentEvents[0].Name, this.session.MemberName, sayDate); await EndMenu(response); } else { await RosterController.AssignInternal(signin, null, db, this.config); BuildSetEventMenu(response, string.Format(Speeches.SignedInUnassignedTemplate, this.session.MemberName, sayDate), Url.Content("~/api/voice/SetSigninEvent")); } } else { signin.TimeOut = time; call.Actions.Add(new CallAction { Call = call, CallId = call.Id, Time = time, Action = "Signed out " + this.session.MemberName }); this.session.IsSignedIn = false; await db.SaveChangesAsync(); this.config.GetPushHub <CallsHub>().updatedRoster(RosterController.GetRosterEntry(signin.Id, db), true); // add prompt for timeout beyond right now response.BeginGather(new { timeout = 10, action = GetAction("SetTimeOut") }); response.SayVoice(Speeches.SignedOutTemplate, this.session.MemberName, sayDate); response.SayVoice(Speeches.TimeoutPrompt); response.EndGather(); } } return(LogResponse(response)); }
protected abstract void HandleBrowseInternal(TwilioResponse response);
public ActionResult Reply(string Body, string From) { var response = new TwilioResponse(); //get the session object via phone number Conversation c = Session[From] as Conversation; if (c == null) { c = new Conversation(); c.NextStep = "name"; Session[From] = c; response.Sms("STOP! He who would cross the Bridge of Death must answer me these questions three ere the other side he see. What...is your name?"); return(TwiML(response)); } if (Body == "clearplayer") { Session[From] = null; Session.Abandon(); response.Sms("You have been forgotten."); return(TwiML(response)); } switch (c.NextStep) { case "name": c.NextStep = "color"; c.Name = Body; Session[From] = c; response.Sms(string.Format("Welcome {0}! Now, what...is your favorite color?", Body)); break; case "color": c.NextStep = "swallow"; c.Color = Body; Session[From] = c; response.Sms(string.Format("Great answer {0}. {1} is a wonderful color. Lastly, what...is the airspeed velocity of an unladen swallow?", c.Name, Body)); break; case "swallow": Session[From] = null; Session.Abandon(); if (Body.ToLower().Contains("african or european")) { response.Sms(string.Format("Well...I don't know...AAAAARRRRRRRRRRRRRRRGGGGGHHHH!!! Curse you {0}", c.Name)); } else { response.Sms(string.Format("{0}? Wrong! The correct answer is 'African or European?' Good try though {1}. And I do still like the color {2}.", Body, c.Name, c.Color)); } break; } return(TwiML(response)); }
private void BeginMenu(TwilioResponse response) { response.BeginGather(new { numDigits = 1, action = GetAction("DoMenu"), timeout = 10 }); }
// GET: Phone public async Task <ActionResult> Store(string to, string from, string body) { var response = new TwilioResponse(); //do we want to fail fast on non-numeric bodies? body = body.Trim(); var survey = context.Surveys.Include(s => s.Responses).Where(s => s.PhoneNumber == to).FirstOrDefault(); if (survey != null) { if (!survey.IsEnabled) { return(TwiML(response)); } //parse the NPS value and comment from the body int value; if (!int.TryParse(body, out value)) { if (body.Contains(' ')) { if (!int.TryParse(body.Substring(0, body.IndexOf(' ')), out value)) { response.Message("Hmm. We could not find a score in your message."); //no number could be found at the start of the message return(TwiML(response)); } } } var surveyresponse = new SurveyResponse() { From = from, To = to, Body = body, Score = value }; survey.Responses.Add(surveyresponse); try { await context.SaveChangesAsync(); var surveyIdParam = new SqlParameter("@SurveyId", survey.SurveyId); await context.Database.ExecuteSqlCommandAsync("[dbo].[CalculateNps] @SurveyId", surveyIdParam); } catch (Exception exc) { //log string msg = exc.Message; return(new HttpStatusCodeResult(500, exc.Message)); } response.Message(survey.ResponseText); return(TwiML(response)); } return(new HttpStatusCodeResult(500)); }
protected HttpResponseMessage TwiMLResponse(TwilioResponse response) { return(this.Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter())); }