Пример #1
0
def call_incoming():
    """ Returns TwiML which prompts the caller to record a message"""
    # Define TwiML response object
    response = VoiceResponse()

    # Make sure this is the first call to our URL and record and transcribe
    if 'RecordingSid' not in request.form:
        # Use <Say> verb to provide an outgoing message
        response.say("Hello, please leave your message after the tone.")

        # Use <Record> verb to record incoming message and set the transcribe argument to true
        response.record(
            recording_status_callback=url_for(".record_complete"),
            transcribe_callback=url_for(".twilio_transcription_complete"),
            transcribe=True)

        sid = request.form['CallSid']
        capture_json(BUCKET, f"calls/{sid}.json", request.form)
    else:
        # Hang up the call
        print("Hanging up...")
        response.hangup()
    return str(response)
Пример #2
0
def challenge_gather_input(request, challenge_uuid):
    """Processes results from the <Gather> prompt in /voice"""

    challenge = get_object_or_404(Challenge, uuid=challenge_uuid)
    # Start our TwiML response
    resp = VoiceResponse()

    # If Twilio's request to our app included already gathered digits,
    # process them
    digits = request.POST.get('Digits')

    if digits is not None:
        if digits == challenge.key:
            solve_challenge(challenge)
            resp.say('Correct. Thank you and have a safe ride.')
            return HttpResponse(str(resp))

    resp.say("Incorrect. Try again.")
    url = reverse('dectauth:challenge-callout',
                  kwargs={'challenge_uuid': str(challenge.uuid)})
    resp.redirect(url)

    return HttpResponse(str(resp))
Пример #3
0
def codecConference(From):
    conference_name = match("sip:(.*)@.*", From).group(1)

    if 'delay' in conference_name:
        group_status = conferenceStatus['delay']
    else:
        group_status = conferenceStatus['live']

    if group_status == 'off-air':
        return str(group_is_closed())

    response = VoiceResponse()
    dial = Dial()
    dial.conference(muted=False,
                    beep=False,
                    end_conference_on_exit=False,
                    start_conference_on_enter=True,
                    max_participants=250,
                    trim="do-not-trim",
                    name=conference_name)
    response.append(dial)

    return str(response)
Пример #4
0
def resultone():
    print("in twiml")
    twiml = VoiceResponse()
    gather = Gather(action="result",
                    input="speech",
                    partial_result_callback='/partial',
                    speechTimeout="5",
                    anguage="en-IN",
                    hints='end the call')
    twiml.say(
        "OK so now after count down to 1 anything you speak will be send it to you.",
        voice="Polly.Raveena",
        language="en-IN",
        rate="90%")
    gather.say(" three  two  one",
               voice="Polly.Raveena",
               language="en-IN",
               rate="65%")

    twiml.append(gather)

    twiml.redirect('/result')
    return str(twiml)
Пример #5
0
def bookMeeting():
    resp = VoiceResponse()
    if 'SpeechResult' in request.values:
        endTimeDetails =  parse_request(request.values['SpeechResult'])
        print("End Time: " + request.values['SpeechResult'])
        event['end']['dateTime'] = endTimeDetails[1] #adding to the dict
        resp.say(callscripts.WaitWhileBooking)
        CalendarResponse = makeEvent.create_event(event)
        print(CalendarResponse)
        if CalendarResponse != 'Busy':
            code = sendCodeToUser(request.values['From'])
            eventId = CalendarResponse[0]
            resp.say(callscripts.MeetingBookedSuccess)
            return str(resp)
        else:
            gather = Gather(input='speech dtmf', action='/retry')
            gather.say(callscripts.UserBusyMessage)
            resp.append(gather)
            return str(resp)
            print(event)
    else:
        resp.say(callscripts.SomethingHappenedErr)
        resp.redirect('/endTime')
Пример #6
0
    def on_get(self, req, resp):
        """
        Echo back user provided content query string in TwiML:

        Example:
            Query strings:

            content: OK

            TwiML:

            <?xml version="1.0" encoding="UTF-8"?>
            <Response>
                <Say language="en-US" voice="alice">OK</Say>
            </Response>
        """
        content = req.get_param('content')
        loop = req.get_param('loop')
        r = VoiceResponse()
        r.say(content, voice='alice', loop=loop, language="en-US")
        resp.status = falcon.HTTP_200
        resp.body = str(r)
        resp.content_type = 'application/xml'
def incoming():
    """Handle incoming calls from any number, agent or otherwise."""
    from_number = request.form["From"]
    call_sid = request.form["CallSid"]

    if from_number in AGENT_NUMBERS:
        return handle_agent(from_number, call_sid)

    response = VoiceResponse()
    dial = Dial()

    try:
        # If an agent is available immediately, connect the customer to them.
        available_agent = AGENT_QUEUE.popitem(last=False)
        dial.conference(available_agent[1])
    except KeyError:
        # Otherwise, place them in a conference called `Waiting Room` with the
        # other customers currently on hold.
        CUSTOMER_QUEUE[from_number] = call_sid
        dial.conference('Waiting Room')

    response.append(dial)
    return Response(str(response), 200, mimetype="application/xml")
Пример #8
0
def run_question(request, pk, question_pk):
    question = Question.objects.get(id=question_pk)
    twiml_response = VoiceResponse()
    action = save_response_url(question)
    if question.kind == Question.TEXT:
        twiml_response = question.say_question_and_prompt(twiml_response)
        twiml_response.record(action=action,
                              method='POST',
                              max_length=10,
                              timeout=4,
                              transcribe=True,
                              transcribe_callback=action)
    else:
        gather = Gather(action=action,
                        method='POST',
                        numDigits=question.max_length,
                        timeout=question.timeout)
        gather = question.say_question_and_prompt(gather)
        twiml_response.append(gather)
        twiml_response.redirect(action, method='POST')

    request.session['answering_question_id'] = question.id
    return HttpResponse(twiml_response, content_type='application/xml')
Пример #9
0
def hello_monkey():
    to_number = request.values.get('To', None)

    print(to_number)  # Print the number to the terminal when it picks up
    resp = VoiceResponse()  # Initialize the VoiceResponse object

    resp.pause(length=30
               )  # Pause for 30 seconds to give time for the agent to pick up

    response = "This is what Twilio will say when the caller picks up."
    resp.say(response)

    # Wait 1 second before continuing on
    resp.pause(length=1)

    # Say it two more times
    resp.say(response)
    resp.pause(length=1)
    resp.say(response)
    resp.pause(length=1)

    # Exit the call
    return str(resp)
Пример #10
0
def schedule_prompt(params, campaign):
    """
    Prompt the user to schedule calls
    """
    if not params or not campaign:
        abort(400)

    resp = VoiceResponse()
    g = Gather(num_digits=1, timeout=3, method="POST", action=url_for("call.schedule_parse", **params))
    
    existing_schedule = ScheduleCall.query.filter_by(campaign_id=campaign.id, phone_number=params['userPhone']).first()
    if existing_schedule and existing_schedule.subscribed:
        play_or_say(g, campaign.audio('msg_alter_schedule'), lang=campaign.language_code)
    else:
        play_or_say(g, campaign.audio('msg_prompt_schedule'), lang=campaign.language_code)
    
    resp.append(g)

    # in case the timeout occurs, we need a redirect verb to ensure that the call doesn't drop
    params['scheduled'] = False
    resp.redirect(url_for('call._make_calls', **params))

    return str(resp)
Пример #11
0
def handle(code: str) -> VoiceResponse:
    response = VoiceResponse()

    # check for code validity
    if code not in config.valid_codes:
        if len(code) >= 1:
            response.say('invalid code')
        response.say('forwarding call')
        response.dial(number=config.fallback_phone)
        return response

    # send notification sms
    client = Client(config.account_sid, config.auth_token)
    client.messages.create(
        body='Front door unlocked for {}'.format(config.valid_codes[code]),
        to=config.notification_phone,
        from_=config.twilio_phone,
    )

    # unlock door
    response.play(digits="9w9w9w9w9w9w")

    return response
Пример #12
0
def recording_received():
    
    print(request.form["RecordingUrl"])
    recordingURL = request.form["RecordingUrl"]
    userNumber = request.values.get('From')

    resp = VoiceResponse()
    resp.say("Nice to meet you. In just a few moments you'll be speaking to the grandpapi or grandmommy of your dreams! Sit tight while we find you a snazzy gran gran that will warm your heart!", voice='Polly.Emma')

    create_new_profile(userNumber, recordingURL)

    match_number = check_available(userNumber)

    # if match_number == -1:
    #     print("no available users online, connecting to new conference call")
    # else:
    #     print("matching you with a user")

    # Start with a <Dial> verb
    with Dial() as dial:
        # If the caller is our MODERATOR, then start the conference when they
        # join and end the conference when they leave
        if request.values.get('From') == MODERATOR:

            dial.conference(
                'My conference',
                start_conference_on_enter=True,
                end_conference_on_exit=True, wait_url="https://burgundy-balinese-9698.twil.io/assets/Robbie%20Williams%20-%20Beyond%20the%20Sea-%5BAudioTrimmer.com%5D%2010.16.53%20PM.mp3")
        else:
            # Otherwise have the caller join as a regular participant
            resp.say("................")
            resp.say("We have found your grandpapi or grandmommy. Ready to get talkey?", voice='Polly.Emma')
            dial.conference('My conference', start_conference_on_enter=False, wait_url="https://burgundy-balinese-9698.twil.io/assets/Robbie%20Williams%20-%20Beyond%20the%20Sea-%5BAudioTrimmer.com%5D%2010.16.53%20PM.mp3")

    resp.append(dial)

    return str(resp)
Пример #13
0
def call_places():
    """Processes results from the <Gather> prompt in /voice"""
    # Start our TwiML response
    resp = VoiceResponse()

    # If Twilio's request to our app included already gathered digits,
    # process them
    if 'Digits' in request.values:
        # Get which digit the caller chose
        choice = request.values['Digits']

        # <Say> a different message depending on the caller's choice
        if choice == '1':
            resp.say(
                'You selected Wellness 360 Adult. Redirecting your call now...'
            )
            resp.dial('210-567-2788')
            return str(resp)
        elif choice == '2':
            resp.say(
                'You selected University Health System Inpatient. Redirecting your call now...'
            )
            resp.dial('210-358-4000')
            return str(resp)
        elif choice == '3':
            resp.say(
                "You selected Samhd Main Immunizations Clinic. Redirecting your call now..."
            )
            resp.dial('210-207-8894')
        else:
            # If the caller didn't choose 1 or 2, apologize and ask them again
            resp.say("Sorry, I don't understand that choice.")

    # If the user didn't choose 1 or 2 (or anything), send them back to /voice
    resp.redirect('/list_places')

    return str(resp)
Пример #14
0
def conference(request,
               name,
               muted=None,
               beep=None,
               start_conference_on_enter=None,
               end_conference_on_exit=None,
               wait_url=None,
               wait_method='POST',
               max_participants=None):
    """
    See: http://www.twilio.com/docs/api/twiml/conference.
    """
    # Usage::
    #
    #     # urls.py
    #     urlpatterns = patterns('',
    #         # ...
    #         url(r'^conference/(?P<name>\w+)/$',
    #             'django_twilio.views.conference',
    #              {'max_participants': 10}
    #         ),
    #         # ...
    #     )
    #
    r = VoiceResponse()
    dial = Dial()
    dial.conference(
        name=name,
        muted=muted,
        beep=beep,
        startConferenceOnEnter=start_conference_on_enter,
        endConferenceOnExit=end_conference_on_exit,
        waitUrl=wait_url,
        waitMethod=wait_method,
    )
    r.append(dial)
    return r
Пример #15
0
def recording():
	response = VoiceResponse()
	currentStepCount= request.values.get("StepNumber", None)
	testcaseid = request.values.get("TestCaseId", None)
	print("testcaseid is " + testcaseid)
	filename = testcaseid + ".json"
	print("CurrentStepCount is " + currentStepCount)
	with open(filename) as json_file:
		testCaseJSON = json.load(json_file)
		currentTestCaseid = testCaseJSON["test_case_id"]
		print ("Test Case ID ==>"+currentTestCaseid)
		action = testCaseJSON["steps"][int(currentStepCount)]["action"]
		print("Action is =>" + action)
		input_type = testCaseJSON["steps"][int(currentStepCount)]["input_type"]
		print("Input Type is =>" + input_type)
		input_value = testCaseJSON["steps"][int(currentStepCount)]["input_value"]
		print("Input Value is =>" + input_value)
		pause = testCaseJSON["steps"][int(currentStepCount)]["pause"]
	if pause!="":
		response.pause(length=int(pause))
		print("I have paused")
	if "Reply" in action:
		if "DTMF" in input_type:
			print("i am at DTMF input step")
			currentStepCount=int(currentStepCount)+1
			session['currentCount']=str(currentStepCount)
			response.play(digits=input_value)
			response.record(trim="trim-silence", action=url_for('.recording', StepNumber=[str(currentStepCount)], TestCaseId=[currentTestCaseid], _external=True), timeout="3", playBeep="false", recordingStatusCallback=url_for('.recording_stat', step=[str(currentStepCount)], currentTestCaseID=[currentTestCaseid], _scheme='https', _external=True),recordingStatusCallbackMethod="POST")
		if "Say" in input_type:
			print("i am at Say input step")
			currentStepCount=int(currentStepCount)+1
			session['currentCount']=str(currentStepCount)
			response.say(input_value, voice="alice", language="en-US")
			response.record(trim="trim-silence", action=url_for('.recording', StepNumber=[str(currentStepCount)], TestCaseId=[currentTestCaseid], _external=True), timeout="3", playBeep="false", recordingStatusCallback=url_for('.recording_stat', step=[str(currentStepCount)], currentTestCaseID=[currentTestCaseid], _scheme='https', _external=True),recordingStatusCallbackMethod="POST")
	if "Hangup" in action:
		response.hangup()
	return str(response)
Пример #16
0
def choose_service(request: HttpRequest) -> HttpResponse:
    vr = VoiceResponse()

    digits = request.POST.get('Digits')

    if (digits == '1'):
        vr.say('You are being connected to the nearest Hospital')
        vr.dial('+91xxxxxxxxxx')

    elif (digits == '2'):
        vr.say('You are being connected to the nearest Pharmacy')
        vr.dial('+91xxxxxxxxxx')

    elif (digits == '3'):
        vr.say('You are being connected to the nearest Supermarket')
        vr.dial('+91xxxxxxxxxx')

    elif (digits == '4'):
        vr.say('You are being connected to the nearest Dairy Centre')
        vr.dial('+91xxxxxxxxxx')

    else:
        vr.say(f'You have entered {(digits)}')
    return HttpResponse(str(vr), content_type='text/xml')
Пример #17
0
def enqueue_wait_url(request):
    resp = VoiceResponse()
    say(
        resp,
        "Willkommen bei der",
    )
    resp.say(
        "Helping Agents",
    )
    say(
        resp,
        "Hotline! Wir werden Ihren Aufruf an einen Freiwilligen vermitteln.",
    )
    pos = request.POST.get("QueuePosition")
    if int(pos) < 2:
        say(
            resp, "Gleich sind Sie dran. Bitte warten Sie noch einen Augenblick",
        )
    else:
        say(resp, f"Sie sind Position {pos} in der Warteschlange")
    resp.pause(length=2)
    say(resp, get_random_corona_fact())
    resp.play("http://com.twilio.music.classical.s3.amazonaws.com/ClockworkWaltz.mp3")
    return HttpResponse(str(resp), content_type="application/xml")
def extract_content(question):
    recording = {}
    if is_sms_request():
        return request.values['Body']
    elif question.kind == Question.TEXT or question.kind == Question.RECORDING:
        recording['recording_url'] = request.values['RecordingUrl']
        recording['recording_sid'] = request.values['RecordingSid']
        recording['transcript'] = 'Transcription in progress.'
        recording['transcription_sid'] = ''
        return recording
    else:
        if 1 <= int(request.values['Digits']) <= 2:
            parsed_content = request.values['Digits']
        else:
            response = VoiceResponse()
            response.say("please choose a valid option",
                         voice='alice',
                         language='en-AU')
            recording["next_question"] = question
        recording['recording_url'] = ''
        recording['recording_sid'] = ''
        recording['transcription_sid'] = ''
        recording['transcript'] = parsed_content[0]
        return recording
Пример #19
0
def ShowTestResult():
    response = VoiceResponse()
    testcaseid = request.values.get("TestCaseId", None)
    conn = pymysql.connect(host=databasehost,
                           user=databaseusername,
                           passwd=databasepassword,
                           port=3306,
                           db=databasename)
    cur = conn.cursor()
    query = "SELECT * FROM ivr_test_case_master where testcaseid=%s"
    args = (str(testcaseid))
    cur.execute(query, args)
    fileContent = """<html><title>IVR test case Execution Result</title><body><table border="1"><tr><th>Testcase ID</th><th>Step No</th><th>Action</th><th>Input Type</th><th>Input Value</th><th>Pause</th><th>Expected Prompt</th><th>Expected Prompt Duration</th><th>Min Confidence</th><th>Actual Prompt</th><th>Result</th><th>Recording URL</th><th>Recording duration</th><th>Uploaded date</th><th>Execution status</th><th>Execution date</th></tr>"""
    for r in cur:
        fileContent = fileContent + '<tr><td>' + validateString(
            r[0]
        ) + '</td><td>' + validateString(r[1]) + '</td><td>' + validateString(
            r[2]
        ) + '</td><td>' + validateString(r[3]) + '</td><td>' + validateString(
            r[4]
        ) + '</td><td>' + validateString(r[5]) + '</td><td>' + validateString(
            r[6]
        ) + '</td><td>' + validateString(r[7]) + '</td><td>' + validateString(
            r[8]) + '</td><td>' + validateString(
                r[9]) + '</td><td>' + validateString(
                    r[10]) + '</td><td>' + validateString(
                        r[11]) + '</td><td>' + validateString(
                            r[12]) + '</td><td>' + validateString(
                                r[13]) + '</td><td>' + validateString(
                                    r[14]) + '</td><td>' + validateString(
                                        r[15]) + '</td></tr>'
        print("R3==>" + r[3])
    cur.close()
    conn.close()
    fileContent = fileContent + '</body></html>'
    return fileContent
Пример #20
0
def answer_call():
    """Respond to incoming phone calls with a brief message."""
    global adventure

    # Start our TwiML response
    resp = VoiceResponse()

    resp.say(
        "You're about to enter a world of endless possibilities, where you can do absolutely anything you can imagine...",
        voice='Polly.Emma-Neural')

    resp.say(
        "The story will begin now, when you hear a male voice saying 'you', say something to do or say, good luck.",
        voice='Polly.Emma-Neural')

    # Generate a random story for the user
    adventure = new_story()
    story = random_story()

    # Once upon a time...
    resp.say(story)
    resp.redirect('/gather')

    return str(resp)
Пример #21
0
def list_showtimes(request: HttpRequest) -> HttpResponse:
    validate_django_request(request)
    vr = VoiceResponse()

    digits = request.POST.get('Digits')
    theater = Theater.object.get(id=request.GET['theater'])

    try:
        movie = Movie.objects.get(id=digits)
    except Movie.DoesNotExist:
        vr.say("Please select a movie from the list.")
        vr.redirect(f"{reverse('choose-movie')}?theater={theater.id}")
    else:
        # User selected movie and theater, search shows in the next 12 hours:
        from_time = timezone.now()
        util_time = from_time + datetime.timedelta(hours=12)
        shows = list(
            Show.objects.filter(
                theater=theater,
                movie=movie,
                starts_at__range=(from_time, util_time)).order_by('starts_at'))
        if len(shows) == 0:
            vr.say(
                "Sorry, the movie is not playing any time soon in this theater."
            )
        else:
            showtimes = ", ".join(show.starts_at.time().strftime('%I:%M%p')
                                  for show in shows)
            vr.say(
                f"The movie {movie.title} will be playing at {theater.name} at {showtimes}"
            )

        vr.say("Thank you for using movie info!")
        vr.hangup()

    return HttpResponse(str(vr), content_type="text/xml")
Пример #22
0
def choose_movie(request: HttpRequest) -> HttpResponse:
    validate_django_request(request)
    vr = VoiceResponse()

    digits = request.POST.get('Digits')
    try:
        theater = Theater.objects.get(digits=digits)
    except Theater.DoesNotExist:
        vr.say("Please select a theater from the list.")
        vr.redirect(reverse('choose-theater'))
    else:
        with vr.gather(
                action=f"{reverse('list-showtimes')}?theater={theater.id}",
                finish_on_key="#",
                timeout=20,
        ) as gather:
            gather.say("Please choose a movie a press #")
            movies = (Movie.objects.filter(
                digits__isnull=False).order_by("digits"))
            for movie in movies:
                gather.say(f"For {movie.title} press {movie.digits}")
        vr.say("We did not receive your selection")
        vr.redirect(reverse("choose-theater"))
    return HttpResponse(str(vr), content_type='text/xml')