// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DayOfWeek[] days =
                Configuration.GetValue <string>("Days", "1, 2, 3, 4, 5, 6").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => (DayOfWeek)int.Parse(x)).ToArray();
            //new DayOfWeek[] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday };

            double startHour = Configuration.GetValue <double>("StartHour", 9);
            double endHour   = Configuration.GetValue <double>("EndHour", 18);

            string[] phoneNumbers = Configuration.GetValue <string>("PhoneNumbers", "").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            app.Run(async(context) =>
            {
                VoiceResponse response      = new VoiceResponse();
                TimeZoneInfo centralZone    = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
                DateTime currentCentralTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, centralZone);
                if ((days.Contains(currentCentralTime.DayOfWeek)) && (currentCentralTime > currentCentralTime.Date.AddHours(startHour)) && (currentCentralTime < currentCentralTime.Date.AddHours(endHour)))
                {
                    response.Play(null, null, "ww9ww9ww9");
                    response.Hangup();
                }
                else if (phoneNumbers.Any())
                {
                    phoneNumbers.ToList().ForEach(x => { response.Dial(x); });
                }
                else
                {
                    response.Say("Access Denied");
                }
                context.Response.ContentType = "text/xml";
                await context.Response.WriteAsync(response.ToString());
            });
        }
Exemplo n.º 2
0
        private async Task <VoiceResponse> TwiMlHangUp()
        {
            _logger.LogDebug("Hang up the phone");
            await _hubContext.Clients.All.SendAsync("SendShortAction", "Hang up");

            var hangUpVoices = new List <string>();

            foreach (var endingCat in _voiceConfig.Ending)
            {
                if (_voiceConfig.Mapping.ContainsKey(endingCat))
                {
                    hangUpVoices.AddRange(_voiceConfig.Mapping[endingCat]);
                }
            }

            if (hangUpVoices.Count == 0)
            {
                throw new InvalidConfigException("No ending voice configured");
            }

            var idx = new Random().Next(hangUpVoices.Count);

            var response = new VoiceResponse();

            response.Play(GetVoiceUrl(hangUpVoices[idx]));
            response.Hangup();
            return(response);
        }
Exemplo n.º 3
0
        public VoiceResponse Inbound(Tuple <Agent, bool> agentTuple)
        {
            var agent     = agentTuple?.Item1;
            var anyOnline = agentTuple != null ? agentTuple.Item2 : false;
            var response  = new VoiceResponse();

            if (settings.WorkingHours != null && settings.WorkingHours.Enabled)
            {
                var now = TenantUtil.DateTimeFromUtc(DateTime.UtcNow);
                if (!(settings.WorkingHours.From <= now.TimeOfDay && settings.WorkingHours.To >= now.TimeOfDay))
                {
                    return(AddVoiceMail(response));
                }
            }

            if (anyOnline)
            {
                if (!string.IsNullOrEmpty(settings.GreetingAudio))
                {
                    response.Play(Uri.EscapeUriString(settings.GreetingAudio));
                }

                response.Enqueue(settings.Queue.Name, GetEcho("Enqueue", agent != null), "POST",
                                 GetEcho("Wait", agent != null), "POST");
            }

            return(AddVoiceMail(response));
        }
Exemplo n.º 4
0
    static void Main()
    {
        var response = new VoiceResponse();

        response.Play("", digits: "wwww3");

        Console.WriteLine(response.ToString());;
    }
Exemplo n.º 5
0
        public ActionResult Play(string recordingUrl)
        {
            var response = new VoiceResponse();

            response.Play(new Uri(recordingUrl));

            return(TwiML(response));
        }
Exemplo n.º 6
0
    static void Main()
    {
        var response = new VoiceResponse();

        response.Play(new Uri("https://api.twilio.com/cowbell.mp3"));

        Console.WriteLine(response.ToString());;
    }
Exemplo n.º 7
0
    // /Voice
    public ActionResult Index()
    {
        var response = new VoiceResponse();

        response.Say("Hello. It's me.");
        response.Play("http://howtodocs.s3.amazonaws.com/ahoyhoy.mp3");
        return(Content(response.ToString(), "text/xml"));
    }
Exemplo n.º 8
0
    static void Main()
    {
        var response = new VoiceResponse();

        response.Play("https://api.twilio.com/cowbell.mp3", loop: 10);

        System.Console.WriteLine(response.ToString());
    }
Exemplo n.º 9
0
    static void Main()
    {
        var response = new VoiceResponse();

        response
        .Play("http://com.twilio.sounds.music.s3.amazonaws.com/MARKOVICHAMP-Borghestral.mp3");

        System.Console.WriteLine(response.ToString());
    }
    static void Main()
    {
        var response = new VoiceResponse();

        response.Say("Hello World");
        response.Play("https://api.twilio.com/Cowbell.mp3");

        System.Console.WriteLine(response.ToString());
    }
    // /Voice/HandleRecord
    public ActionResult HandleRecord()
    {
        var response = new VoiceResponse();

        response.Say("Listen to your recorded message.");
        response.Play(Request.Form["RecordingUrl"]);
        response.Say("Goodbye.");
        return(Content(response.ToString(), "text/xml"));
    }
Exemplo n.º 12
0
        public string CreateGateResponse()
        {
            for (var i = 0; i < _config.Value.IterationCount; i++)
            {
                _response.Play(new Uri(_config.Value.DtmfToneUrl));
                _response.Pause(_config.Value.PauseLength);
            }

            return(_response.ToString());
        }
Exemplo n.º 13
0
        public IActionResult PlayAll()
        {
            var allVoices = _voiceConfig.Mapping.Values.Aggregate((a, b) => a.Concat(b).ToList()).ToList();

            var response = new VoiceResponse();

            allVoices.ForEach(s => response.Play(GetVoiceUrl(s)));

            return(TwiML(response));
        }
Exemplo n.º 14
0
    public ActionResult Index(string fromCity)
    {
        // Get information about the incoming call, like the city associated
        // with the phone number (if Twilio can discover it)
        var city = fromCity;

        var response = new VoiceResponse();

        response.Say($"Never gonna give you up {city}", voice: "alice");
        response.Play("https://demo.twilio.com/docs/classic.mp3");

        return Content(response.ToString(), "text/xml")
    }
    public ActionResult Index(BodyData bodyData)
    {
        string recordingUrl = bodyData.RecordingUrl;

        Console.WriteLine(recordingUrl);

        var response = new VoiceResponse();

        response.Say("Thanks for howling... take a listen to what you howled.");
        response.Play(new Uri(recordingUrl));
        response.Say("Goodbye.");

        return(TwiML(response));
    }
Exemplo n.º 16
0
        public void TestPlay()
        {
            var vr = new VoiceResponse();

            vr.Play("www.twilio.com", loop: 2, digits: "5w");

            Assert.AreEqual(
                vr.ToString(),
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
                "<Response>" + Environment.NewLine +
                "  <Play loop=\"2\" digits=\"5w\">www.twilio.com</Play>" + Environment.NewLine +
                "</Response>"
                );
        }
    // /Voice
    public ActionResult Index()
    {
        var gather = new Gather(numDigits: 1, action: "/Voice/HandleGather");

        gather.Say("To speak to a real person, press 1.\n" +
                   "Press 2 to record a message for a Twilio educator.\n" +
                   "Press any other key to start over.");

        var response = new VoiceResponse();

        response.Say("Hello. It's me.", voice: "alice", language: "en-GB");
        response.Play("http://howtodocs.s3.amazonaws.com/ahoyhoy.mp3");
        response.Gather(gather);

        return(Content(response.ToString(), "text/xml"));
    }
        static void Main(string[] args)
        {
            /*
             *          // num_input and name_input imported from web
             *          int amnt_of_nums = name_input.Count(f => f == ',');
             *          List<string> names = new List<string>();
             *          List<string> phone_nums = new List<string>();
             *          int j, k = 0;
             *          string current_string = "";
             *          for(int i = 0; i < amnt_of_nums; i++)
             *          {
             *                  while(num_input[j] != ',')
             *                  {
             *                          current_string += num_input[j];
             *                          j += 1;
             *                  }
             *                  phone_nums.Add(current_string);
             *                  current_string = "";
             *                  while(name_input[k] != ',')
             *                  {
             *                          current_string += num_input[k];
             *                          k += 1;
             *                  }
             *                  names.Add(current_string);
             *
             *          }
             */

            const string accountSid = "AC47dca6777f98063b5a02357d7e609550";
            const string authToken  = "ec250cbca2521808ec9dbb8355f52b12";

            TwilioClient.Init(accountSid, authToken);

            var to       = new PhoneNumber("+13146606488");
            var from     = new PhoneNumber("+12055574602");
            var call     = CallResource.Create(to, from, url: new Uri("https://handler.twilio.com/twiml/EH092d0a51e18e85a126f9858221955e9e"));
            var response = new VoiceResponse();

            response.Play(digits: "wwww3");
            Console.WriteLine(response.ToString());


            Console.WriteLine(call.Sid);
        }
Exemplo n.º 19
0
        private VoiceResponse GatherPlayResponse(string voice)
        {
            _logger.LogDebug($"Play interactive voice response {voice}");
            var response = new VoiceResponse();

            response.Play(GetVoiceUrl(voice));

            response.Gather(language: Gather.LanguageEnum.CmnHansCn,
                            action: new Uri("/voice/gatherresult", UriKind.Relative),
                            input: new List <Gather.InputEnum>()
            {
                Gather.InputEnum.Speech
            },
                            speechTimeout: "auto"
                            );

            response.Redirect(new Uri("/voice/gatherresult"));
            return(response);
        }
Exemplo n.º 20
0
        private async Task <VoiceResponse> TwiMlTransfer()
        {
            _logger.LogDebug("Transferring call");
            await _hubContext.Clients.All.SendAsync("SendShortAction", "Transfer the call to human");

            if (!_voiceConfig.Mapping.ContainsKey("None"))
            {
                throw new InvalidConfigException("Transfer voices not found in config");
            }

            var voices = _voiceConfig.Mapping["None"];
            var idx    = new Random().Next(voices.Count);

            var response = new VoiceResponse();

            response.Play(GetVoiceUrl(voices[idx]));
            response.Dial(_voiceConfig.TransferTo);
            return(response);
        }
Exemplo n.º 21
0
        public void TestElementWithChildren()
        {
            var elem = new VoiceResponse();

            elem.Dial(
                "number",
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                1,
                true,
                1,
                "caller_id",
                Dial.RecordEnum.DoNotRecord,
                Dial.TrimEnum.TrimSilence,
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                Promoter.ListOfOne(Dial.RecordingEventEnum.InProgress),
                true,
                Dial.RingToneEnum.At
                );

            elem.Echo();

            elem.Enqueue(
                "name",
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                "workflow_sid"
                );

            elem.Gather(
                Gather.InputEnum.Dtmf,
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                1,
                "speech_timeout",
                1,
                true,
                "finish_on_key",
                1,
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                Gather.LanguageEnum.AfZa,
                "hints",
                true
                );

            elem.Hangup();

            elem.Leave();

            elem.Pause(1);

            elem.Play(new Uri("https://example.com"), 1, "digits");

            elem.Queue(
                "name",
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                "reservation_sid",
                "post_work_activity_sid"
                );

            elem.Record(
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                1,
                "finish_on_key",
                1,
                true,
                Record.TrimEnum.TrimSilence,
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                true,
                new Uri("https://example.com")
                );

            elem.Redirect(new Uri("https://example.com"), Twilio.Http.HttpMethod.Get);

            elem.Reject(Reject.ReasonEnum.Rejected);

            elem.Say("message", Say.VoiceEnum.Man, 1, Say.LanguageEnum.DaDk);

            elem.Sms(
                "message",
                new Twilio.Types.PhoneNumber("+15558675310"),
                new Twilio.Types.PhoneNumber("+15017122661"),
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                new Uri("https://example.com")
                );

            Assert.AreEqual(
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
                "<Response>" + Environment.NewLine +
                "  <Dial action=\"https://example.com\" method=\"GET\" timeout=\"1\" hangupOnStar=\"true\" timeLimit=\"1\" callerId=\"caller_id\" record=\"do-not-record\" trim=\"trim-silence\" recordingStatusCallback=\"https://example.com\" recordingStatusCallbackMethod=\"GET\" recordingStatusCallbackEvent=\"in-progress\" answerOnBridge=\"true\" ringTone=\"at\">number</Dial>" + Environment.NewLine +
                "  <Echo></Echo>" + Environment.NewLine +
                "  <Enqueue action=\"https://example.com\" method=\"GET\" waitUrl=\"https://example.com\" waitUrlMethod=\"GET\" workflowSid=\"workflow_sid\">name</Enqueue>" + Environment.NewLine +
                "  <Gather input=\"dtmf\" action=\"https://example.com\" method=\"GET\" timeout=\"1\" speechTimeout=\"speech_timeout\" maxSpeechTime=\"1\" profanityFilter=\"true\" finishOnKey=\"finish_on_key\" numDigits=\"1\" partialResultCallback=\"https://example.com\" partialResultCallbackMethod=\"GET\" language=\"af-ZA\" hints=\"hints\" bargeIn=\"true\"></Gather>" + Environment.NewLine +
                "  <Hangup></Hangup>" + Environment.NewLine +
                "  <Leave></Leave>" + Environment.NewLine +
                "  <Pause length=\"1\"></Pause>" + Environment.NewLine +
                "  <Play loop=\"1\" digits=\"digits\">https://example.com</Play>" + Environment.NewLine +
                "  <Queue url=\"https://example.com\" method=\"GET\" reservationSid=\"reservation_sid\" postWorkActivitySid=\"post_work_activity_sid\">name</Queue>" + Environment.NewLine +
                "  <Record action=\"https://example.com\" method=\"GET\" timeout=\"1\" finishOnKey=\"finish_on_key\" maxLength=\"1\" playBeep=\"true\" trim=\"trim-silence\" recordingStatusCallback=\"https://example.com\" recordingStatusCallbackMethod=\"GET\" transcribe=\"true\" transcribeCallback=\"https://example.com\"></Record>" + Environment.NewLine +
                "  <Redirect method=\"GET\">https://example.com</Redirect>" + Environment.NewLine +
                "  <Reject reason=\"rejected\"></Reject>" + Environment.NewLine +
                "  <Say voice=\"man\" loop=\"1\" language=\"da-DK\">message</Say>" + Environment.NewLine +
                "  <Sms to=\"+15558675310\" from=\"+15017122661\" action=\"https://example.com\" method=\"GET\" statusCallback=\"https://example.com\">message</Sms>" + Environment.NewLine +
                "</Response>",
                elem.ToString()
                );
        }
Exemplo n.º 22
0
        public void TestElementWithChildren()
        {
            var elem = new VoiceResponse();

            elem.Connect(new Uri("https://example.com"), Twilio.Http.HttpMethod.Get);

            elem.Dial(
                "number",
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                1,
                true,
                1,
                "caller_id",
                Dial.RecordEnum.DoNotRecord,
                Dial.TrimEnum.TrimSilence,
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                Promoter.ListOfOne(Dial.RecordingEventEnum.InProgress),
                true,
                Dial.RingToneEnum.At
                );

            elem.Echo();

            elem.Enqueue(
                "name",
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                "workflow_sid"
                );

            elem.Gather(
                Promoter.ListOfOne(Gather.InputEnum.Dtmf),
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                1,
                "speech_timeout",
                1,
                true,
                "finish_on_key",
                1,
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                Gather.LanguageEnum.AfZa,
                "hints",
                true,
                true,
                true,
                Gather.SpeechModelEnum.Default,
                true
                );

            elem.Hangup();

            elem.Leave();

            elem.Pause(1);

            elem.Play(new Uri("https://example.com"), 1, "digits");

            elem.Queue(
                "name",
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                "reservation_sid",
                "post_work_activity_sid"
                );

            elem.Record(
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                1,
                "finish_on_key",
                1,
                true,
                Record.TrimEnum.TrimSilence,
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                Promoter.ListOfOne(Record.RecordingEventEnum.InProgress),
                true,
                new Uri("https://example.com")
                );

            elem.Redirect(new Uri("https://example.com"), Twilio.Http.HttpMethod.Get);

            elem.Reject(Reject.ReasonEnum.Rejected);

            elem.Say("message", Say.VoiceEnum.Man, 1, Say.LanguageEnum.Arb);

            elem.Sms(
                "message",
                new Twilio.Types.PhoneNumber("+15558675310"),
                new Twilio.Types.PhoneNumber("+15017122661"),
                new Uri("https://example.com"),
                Twilio.Http.HttpMethod.Get,
                new Uri("https://example.com")
                );

            elem.Pay(
                Pay.InputEnum.Dtmf,
                new Uri("https://example.com"),
                Pay.BankAccountTypeEnum.ConsumerChecking,
                new Uri("https://example.com"),
                Pay.StatusCallbackMethodEnum.Get,
                1,
                1,
                true,
                "postal_code",
                1,
                "payment_connector",
                Pay.PaymentMethodEnum.AchDebit,
                Pay.TokenTypeEnum.OneTime,
                "charge_amount",
                "currency",
                "description",
                Promoter.ListOfOne(Pay.ValidCardTypesEnum.Visa),
                Pay.LanguageEnum.DeDe
                );

            elem.Prompt(
                Prompt.ForEnum.PaymentCardNumber,
                Promoter.ListOfOne(Prompt.ErrorTypeEnum.Timeout),
                Promoter.ListOfOne(Prompt.CardTypeEnum.Visa),
                Promoter.ListOfOne(1)
                );

            elem.Start(new Uri("https://example.com"), Twilio.Http.HttpMethod.Get);

            elem.Stop();

            elem.Refer(new Uri("https://example.com"), Twilio.Http.HttpMethod.Get);

            Assert.AreEqual(
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
                "<Response>" + Environment.NewLine +
                "  <Connect action=\"https://example.com\" method=\"GET\"></Connect>" + Environment.NewLine +
                "  <Dial action=\"https://example.com\" method=\"GET\" timeout=\"1\" hangupOnStar=\"true\" timeLimit=\"1\" callerId=\"caller_id\" record=\"do-not-record\" trim=\"trim-silence\" recordingStatusCallback=\"https://example.com\" recordingStatusCallbackMethod=\"GET\" recordingStatusCallbackEvent=\"in-progress\" answerOnBridge=\"true\" ringTone=\"at\">number</Dial>" + Environment.NewLine +
                "  <Echo></Echo>" + Environment.NewLine +
                "  <Enqueue action=\"https://example.com\" method=\"GET\" waitUrl=\"https://example.com\" waitUrlMethod=\"GET\" workflowSid=\"workflow_sid\">name</Enqueue>" + Environment.NewLine +
                "  <Gather input=\"dtmf\" action=\"https://example.com\" method=\"GET\" timeout=\"1\" speechTimeout=\"speech_timeout\" maxSpeechTime=\"1\" profanityFilter=\"true\" finishOnKey=\"finish_on_key\" numDigits=\"1\" partialResultCallback=\"https://example.com\" partialResultCallbackMethod=\"GET\" language=\"af-ZA\" hints=\"hints\" bargeIn=\"true\" debug=\"true\" actionOnEmptyResult=\"true\" speechModel=\"default\" enhanced=\"true\"></Gather>" + Environment.NewLine +
                "  <Hangup></Hangup>" + Environment.NewLine +
                "  <Leave></Leave>" + Environment.NewLine +
                "  <Pause length=\"1\"></Pause>" + Environment.NewLine +
                "  <Play loop=\"1\" digits=\"digits\">https://example.com</Play>" + Environment.NewLine +
                "  <Queue url=\"https://example.com\" method=\"GET\" reservationSid=\"reservation_sid\" postWorkActivitySid=\"post_work_activity_sid\">name</Queue>" + Environment.NewLine +
                "  <Record action=\"https://example.com\" method=\"GET\" timeout=\"1\" finishOnKey=\"finish_on_key\" maxLength=\"1\" playBeep=\"true\" trim=\"trim-silence\" recordingStatusCallback=\"https://example.com\" recordingStatusCallbackMethod=\"GET\" recordingStatusCallbackEvent=\"in-progress\" transcribe=\"true\" transcribeCallback=\"https://example.com\"></Record>" + Environment.NewLine +
                "  <Redirect method=\"GET\">https://example.com</Redirect>" + Environment.NewLine +
                "  <Reject reason=\"rejected\"></Reject>" + Environment.NewLine +
                "  <Say voice=\"man\" loop=\"1\" language=\"arb\">message</Say>" + Environment.NewLine +
                "  <Sms to=\"+15558675310\" from=\"+15017122661\" action=\"https://example.com\" method=\"GET\" statusCallback=\"https://example.com\">message</Sms>" + Environment.NewLine +
                "  <Pay input=\"dtmf\" action=\"https://example.com\" bankAccountType=\"consumer-checking\" statusCallback=\"https://example.com\" statusCallbackMethod=\"GET\" timeout=\"1\" maxAttempts=\"1\" securityCode=\"true\" postalCode=\"postal_code\" minPostalCodeLength=\"1\" paymentConnector=\"payment_connector\" paymentMethod=\"ach-debit\" tokenType=\"one-time\" chargeAmount=\"charge_amount\" currency=\"currency\" description=\"description\" validCardTypes=\"visa\" language=\"de-DE\"></Pay>" + Environment.NewLine +
                "  <Prompt for=\"payment-card-number\" errorType=\"timeout\" cardType=\"visa\" attempt=\"1\"></Prompt>" + Environment.NewLine +
                "  <Start action=\"https://example.com\" method=\"GET\"></Start>" + Environment.NewLine +
                "  <Stop></Stop>" + Environment.NewLine +
                "  <Refer action=\"https://example.com\" method=\"GET\"></Refer>" + Environment.NewLine +
                "</Response>",
                elem.ToString()
                );
        }
Exemplo n.º 23
0
        private async System.Threading.Tasks.Task HandleIncomingBotMessagesAsync(IList <Activity> botReplies, string callSid)
        {
            var voiceResponse    = new VoiceResponse();
            var says             = new StringBuilder();
            var forwardingNumber = string.Empty;
            var forward          = false;
            var error            = false;
            var errorMessage     = string.Empty;

            foreach (var activity in botReplies)
            {
                var languagesManager = new LanguagesManager();
                var localeCulture    = languagesManager.CheckAndReturnAppropriateCulture(activity.Locale);
                CultureInfo.CurrentCulture = new CultureInfo(localeCulture);

                //Using TTS to repond to the caller
                var ttsResponse = await System.Threading.Tasks.Task.Run(() =>
                                                                        _textToSpeech.TransformTextToSpeechAsync(activity.Text, CultureInfo.CurrentCulture.Name));

                var wavGuid = Guid.NewGuid();
                var pathToAudioDirectory = _hostingEnvironment.WebRootPath + "/audio";
                var pathCombined         = Path.Combine(pathToAudioDirectory, $"{ wavGuid }.wav");
                var formatConverter      = new FormatConvertor();
                await formatConverter.TurnAudioStreamToFile(ttsResponse, pathCombined);

                voiceResponse.Play(new Uri($"{_directlineConfig.Host}audio/{wavGuid}.wav"));

                if (activity.Entities != null)
                {
                    foreach (var entity in activity.Entities)
                    {
                        forward          = entity.Properties.TryGetValue("forward", out var numberJToken);
                        forwardingNumber = forward ? numberJToken.ToString() : string.Empty;

                        error = entity.Properties.TryGetValue("error", out var errorMessageJToken);
                        if (error)
                        {
                            break;
                        }
                    }
                }
            }

            if (error)
            {
                voiceResponse.Hangup();
            }
            else if (forward)
            {
                voiceResponse.Dial(number: forwardingNumber);
            }
            else
            {
                voiceResponse.Gather(
                    input: new List <Gather.InputEnum> {
                    Gather.InputEnum.Speech
                },
                    language: CultureInfo.CurrentCulture.Name,
                    action: new Uri($"{_directlineConfig.Host}api/voice/send"),
                    method: HttpMethod.Get,
                    speechTimeout: "auto",
                    hints: _hints
                    );
            }

            var xmlFileName        = Guid.NewGuid();
            var pathToXMLDirectory = _hostingEnvironment.WebRootPath + "/xml";

            System.IO.File.WriteAllText($"{pathToXMLDirectory}/{xmlFileName}.xml", voiceResponse.ToString());

            CallResource.Update(
                method: HttpMethod.Get,
                url: new Uri($"{_directlineConfig.Host}xml/{xmlFileName}.xml"),
                pathSid: callSid
                );
        }
Exemplo n.º 24
0
        public async Task <ActionResult> VoiceCall(string userId, int callId)
        {
            var response = new VoiceResponse();
            var call     = await _callsService.GetCallByIdAsync(callId);

            call = await _callsService.PopulateCallData(call, true, true, true, true, true, true, true);

            if (call == null)
            {
                response.Say("This call has been closed. Goodbye.").Hangup();
                //return Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter());
                return(Ok(new StringContent(response.ToString(), Encoding.UTF8, "application/xml")));
            }

            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());
                return(Ok(new StringContent(response.ToString(), Encoding.UTF8, "application/xml")));
            }

            var stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(call.DepartmentId);

            if (call.Attachments != null &&
                call.Attachments.Count(x => x.CallAttachmentType == (int)CallAttachmentTypes.DispatchAudio) > 0)
            {
                var audio = call.Attachments.FirstOrDefault(x =>
                                                            x.CallAttachmentType == (int)CallAttachmentTypes.DispatchAudio);

                if (audio != null)
                {
                    var url = await _callsService.GetShortenedAudioUrlAsync(call.CallId, audio.CallAttachmentId);

                    Play playResponse = new Play();
                    playResponse.Url = new Uri(url);

                    Gather gatherResponse1 = new Gather();
                    gatherResponse1.NumDigits = 1;
                    gatherResponse1.Timeout   = 10;
                    gatherResponse1.Method    = "GET";
                    gatherResponse1.Action    = new Uri(string.Format("{0}/Twilio/VoiceCallAction/{1}/{2}", Config.SystemBehaviorConfig.ResgridApiBaseUrl, userId, callId));

                    StringBuilder sb1 = new StringBuilder();
                    sb1.Append("Press 0 to repeat, Press 1 to respond to the scene");

                    for (int i = 0; i < stations.Count; i++)
                    {
                        if (i >= 8)
                        {
                            break;
                        }

                        sb1.Append(string.Format(", press {0} to respond to {1}", i + 2, stations[i].Name));
                    }

                    response.Play(playResponse).Say(sb1.ToString()).Gather(gatherResponse1).Pause(10).Hangup();

                    return(new ContentResult
                    {
                        Content = response.ToString(),
                        ContentType = "application/xml",
                        StatusCode = 200
                    });
                }
            }

            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 = await _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));
            }

            Gather gatherResponse = new Gather();

            gatherResponse.NumDigits = 1;
            gatherResponse.Timeout   = 10;
            gatherResponse.Method    = "GET";
            gatherResponse.Action    = new Uri(string.Format("{0}/Twilio/VoiceCallAction/{1}/{2}", Config.SystemBehaviorConfig.ResgridApiBaseUrl, userId, callId));

            response.Gather(gatherResponse).Say(sb.ToString()).Pause(10).Hangup();

            return(new ContentResult
            {
                Content = response.ToString(),
                ContentType = "application/xml",
                StatusCode = 200
            });
        }
Exemplo n.º 25
0
 private VoiceResponse AddVoiceMail(VoiceResponse response)
 {
     return(string.IsNullOrEmpty(settings.VoiceMail)
                ? response.Say("")
                : response.Play(Uri.EscapeUriString(settings.VoiceMail)).Record(method: "POST", action: GetEcho("voiceMail"), maxLength: 30));
 }