Example #1
0
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)
Example #2
0
def call_status_update_callback(request):
    call_data = request.GET
    logger.debug(call_data['employee'])
    try:
        user = User.objects.get(pk=call_data['employee'])
    except Exception as e:
        user = User.objects.get(pk=1)
        logger.warn(e)
        Log.objects.create(type="Call Summary Error (Getting User)", 
                           message=e,
                           user=user)

    try:
        call_log = Call.objects.get(twilio_id=call_data.get('ParentCallSid', 0))
    except Exception as e:
        logger.debug(e)
        logger.debug("New Call Created")
        call_log = Call()

    call_log.twilio_id = request.GET.get(u'ParentCallSid', call_log.twilio_id)
    call_log.type = call_log.type or call_data.get('Direction', call_log.type) 
    call_log.incoming_number = call_log.incoming_number or call_data.get('From', call_log.incoming_number)
    call_log.employee = user
    call_log.save()

    resp = VoiceResponse()
    resp.hangup()
    return HttpResponse(resp)
def get_voice_twiml():
    """Respond to incoming calls with a simple text message."""

    resp = VoiceResponse()
    resp.say("Thanks for calling!")

    return Response(str(resp), mimetype='text/xml')
def generate_wait():
    twiml_response = VoiceResponse()
    wait_message = 'Thank you for calling. Please wait in line for a few seconds. An agent will be with you shortly.'
    wait_music = 'http://com.twilio.music.classical.s3.amazonaws.com/BusyStrings.mp3'
    twiml_response.say(wait_message)
    twiml_response.play(wait_music)
    return str(twiml_response)
Example #5
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
Example #6
0
def verb_view(request):
    """
    A simple test view that returns a ``twilio.Verb`` object.
    """
    r = VoiceResponse()
    r.reject()
    return r
def voice():
    """Respond to incoming calls with a simple text message."""

    resp = VoiceResponse()
    resp.say("Hello. It's me.")
    resp.play("http://howtodocs.s3.amazonaws.com/ahoyhoy.mp3")
    return str(resp)
def generate_connect_conference(call_sid, wait_url, start_on_enter, end_on_exit):
    twiml_response = VoiceResponse()
    dial = Dial()
    dial.conference(call_sid,
                    start_conference_on_enter=start_on_enter,
                    end_conference_on_exit=end_on_exit,
                    wait_url=wait_url)
    return str(twiml_response.append(dial))
def voice():
    """Respond to incoming phone calls with a 'Hello world' message"""
    # Start our TwiML response
    resp = VoiceResponse()

    # Read a message aloud to the caller
    resp.say("hello world!", voice='alice')

    return str(resp)
def get_voice_twiml():
    """Respond to incoming calls with a simple text message."""

    resp = VoiceResponse()
    if "To" in request.form:
        resp.dial(request.form["To"], callerId="+15017250604")
    else:
        resp.say("Thanks for calling!")

    return Response(str(resp), mimetype='text/xml')
def gather():
    """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 sales. Good for you!')
            return str(resp)
        elif choice == '2':
            resp.say('You need support. We will help!')
            return str(resp)
        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('/voice')

    return str(resp)
Example #12
0
def test(request):
    resp = VoiceResponse()

    gather = Gather(action="/api/v1/ivr/test/route_call/", method="POST", num_digits=1, timeout=10)
    gather.play(url="https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/ivr/audio-welcome.mp3")
    gather.play(url="https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/ivr/audio-sales.mp3")
    gather.play(url="https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/ivr/audio-customer-service.mp3")
    gather.play(url="https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/ivr/audio-accounting.mp3")
    resp.append(gather)

    return HttpResponse(resp)
Example #13
0
 def post_valid(self, request):
     """Expects a POST request from Twilio, and return a response directing
     Twilio to play the greeting mp3 and post the recorded response to
     the handle voicemail URL
     """
     response = VoiceResponse()
     self.static_greeting_path = static(self.voicemail_static_path)
     self.record_voicemail_url = request.build_absolute_uri(
         reverse('phone-handle_new_message')).replace('http:', 'https:')
     response.play(self.static_greeting_path)
     response.record(action=self.record_voicemail_url, method='POST')
     return HttpResponse(response)
Example #14
0
    def gatekeeper():
        logger.info("Call started: %s", request.values)

        response = VoiceResponse()

        if 'notFirstCall' not in request.values:
            # Accept Google voice call
            response.play(digits='1')

        add_gandalf_to_response(response)

        return str(response)
Example #15
0
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)
Example #16
0
def complete():
    params, campaign = parse_params(request)
    i = int(request.values.get('call_index', 0))

    if not params or not campaign:
        abort(400)

    (uid, prefix) = parse_target(params['targetIds'][i])
    (current_target, cached) = Target.get_or_cache_key(uid, prefix)
    call_data = {
        'session_id': params['sessionId'],
        'campaign_id': campaign.id,
        'target_id': current_target.id,
        'call_id': request.values.get('CallSid', None),
        'status': request.values.get('DialCallStatus', 'unknown'),
        'duration': request.values.get('DialCallDuration', 0)
    }

    try:
        db.session.add(Call(**call_data))
        db.session.commit()
    except SQLAlchemyError:
        current_app.logger.error('Failed to log call:', exc_info=True)

    resp = VoiceResponse()

    if call_data['status'] == 'busy':
        play_or_say(resp, campaign.audio('msg_target_busy'),
            title=current_target.title,
            name=current_target.name,
            lang=campaign.language_code)

    # TODO if district offices, try another office number

    i = int(request.values.get('call_index', 0))

    if i == len(params['targetIds']) - 1:
        # thank you for calling message
        play_or_say(resp, campaign.audio('msg_final_thanks'),
            lang=campaign.language_code)
    else:
        # call the next target
        params['call_index'] = i + 1  # increment the call counter
        calls_left = len(params['targetIds']) - i - 1

        play_or_say(resp, campaign.audio('msg_between_calls'),
            calls_left=calls_left,
            lang=campaign.language_code)

        resp.redirect(url_for('call.make_single', **params))

    return str(resp)
Example #17
0
def outbound():
    response = VoiceResponse()

    response.say("Thank you for contacting our sales department. If this "
                 "click to call application was in production, we would "
                 "dial out to your sales team with the Dial verb.",
                 voice='alice')
    '''
    # Uncomment this code and replace the number with the number you want
    # your customers to call.
    response.number("+16518675309")
    '''
    return str(response)
def voice():
    """Respond to incoming phone calls with a menu of options"""
    # Start our TwiML response
    resp = VoiceResponse()

    # Start our <Gather> verb
    gather = Gather(num_digits=1, action='/gather')
    gather.say('For sales, press 1. For support, press 2.')
    resp.append(gather)

    # If the user doesn't select an option, redirect them into a loop
    resp.redirect('/voice')

    return str(resp)
def voice():
    dest_number = request.values.get('PhoneNumber', None)
    default_client = request.values.get('PhoneNumber', None)
    resp = VoiceResponse()
    # item = request.values.get('item', None)
    # name = request.values.get('name', None)
 
    with resp.dial(callerId=caller_id, record='true') as r:

    # If we have a number, and it looks like a phone number:
        if dest_number and re.search('^[\d\(\)\- \+]+$', dest_number): 
            r.number(dest_number)
        else:
            r.client(default_client)
    return str(resp)
Example #20
0
def call():
    """Returns TwiML instructions to Twilio's POST requests"""
    response = VoiceResponse()

    dial = Dial(callerId=app.config['TWILIO_NUMBER'])
    # If the browser sent a phoneNumber param, we know this request
    # is a support agent trying to call a customer's phone
    if 'phoneNumber' in request.form:
        dial.number(request.form['phoneNumber'])
    else:
        # Otherwise we assume this request is a customer trying
        # to contact support from the home page
        dial.client('support_agent')

    return str(response.append(dial))
def voice():
    """Respond to incoming phone calls and mention the caller's city"""
    # Get the caller's city from Twilio's request to our app
    city = request.values['FromCity']

    # Start our TwiML response
    resp = VoiceResponse()

    # Read a message aloud to the caller
    resp.say('Never gonna give you up, {}!'.format(city), voice='alice')

    # Play an audio file for the caller
    resp.play('https://demo.twilio.com/docs/classic.mp3')

    return str(resp)
Example #22
0
def say(request, text, voice=None, language=None, loop=None):
    """
See: http://www.twilio.com/docs/api/twiml/say.

Usage::

    # urls.py
    urlpatterns = patterns('',
        # ...
        url(r'^say/$', 'django_twilio.views.say', {'text': 'hello, world!'})
        # ...
    )
    """
    r = VoiceResponse()
    r.say(text, voice=voice, language=language, loop=loop)
    return r
Example #23
0
def voice(request):
    """Returns TwiML instructions to Twilio's POST requests"""
    resp = VoiceResponse()
    dial = Dial(caller_id='+6625088681')

    # If the browser sent a phoneNumber param, we know this request
    # is a support agent trying to call a customer's phone
    if 'phoneNumber' in request.POST:
        dial.number(request.POST['phoneNumber'])
    else:
        # Otherwise we assume this request is a customer trying
        # to contact support from the home page
        dial.client('support_agent')
    
    resp.append(dial)
    return HttpResponse(resp)
def get_voice_twiml():
    """Respond to incoming calls with a simple text message."""

    resp = VoiceResponse()
    if "To" in request.form:
        dial = Dial(callerId="+15017250604")
        # wrap the phone number or client name in the appropriate TwiML verb
        # by checking if the number given has only digits and format symbols
        if phone_pattern.match(request.form["To"]):
            dial.number(request.form["To"])
        else:
            dial.client(request.form["To"])
        resp.append(dial)
    else:
        resp.say("Thanks for calling!")

    return Response(str(resp), mimetype='text/xml')
def voice_twiml(question):
    response = VoiceResponse()
    response.say(question.content)
    response.say(VOICE_INSTRUCTIONS[question.kind])

    action_url = url_for('answer', question_id=question.id)
    transcription_url = url_for('answer_transcription',
                                question_id=question.id)
    if question.kind == Question.TEXT:
        response.record(action=action_url,
                        transcribe_callback=transcription_url)
    else:
        response.gather(action=action_url)
    return str(response)
Example #26
0
def intro_wait_human(params, campaign):
    """
    Play intro message, and wait for key press to ensure we have a human on the line.
    Then, redirect to _make_calls.
    """
    resp = VoiceResponse()

    play_or_say(resp, campaign.audio('msg_intro'))

    action = url_for("call._make_calls", **params)

    # wait for user keypress, in case we connected to voicemail
    # give up after 10 seconds
    g = Gather(num_digits=1, method="POST", timeout=10, action=action)
    play_or_say(g, campaign.audio('msg_intro_confirm'), lang=campaign.language_code)
    resp.append(g)

    return str(resp)
Example #27
0
def play(request, url, loop=None):
    """
    See: http://www.twilio.com/docs/api/twiml/play.

    Usage::

        # urls.py
        urlpatterns = patterns('',
            # ...
            url(r'^play/$', 'django_twilio.views.play', {
                    'url': 'http://blah.com/blah.wav',
            }),
            # ...
        )
    """
    r = VoiceResponse()
    r.play(url, loop=loop)
    return r
Example #28
0
def gather(request, action=None, method='POST', num_digits=None, timeout=None,
           finish_on_key=None):
    """
    See: http://www.twilio.com/docs/api/twiml/gather.

    Usage::

        # urls.py
        urlpatterns = patterns('',
            # ...
            url(r'^gather/$', 'django_twilio.views.gather'),
            # ...
        )
    """
    r = VoiceResponse()
    r.gather(action=action, method=method, num_digits=num_digits,
             timeout=timeout, finish_on_key=finish_on_key)
    return r
Example #29
0
def dial(request, number, action=None, method='POST', timeout=None,
         hangup_on_star=None, time_limit=None, caller_id=None):
    """
    See: http://www.twilio.com/docs/api/twiml/dial.

    Usage::

        # urls.py
        urlpatterns = patterns('',
            # ...
            url(r'^dial/?(P<number>\w+)/$', 'django_twilio.views.dial'),
            # ...
        )
    """
    r = VoiceResponse()
    r.dial(number=number, action=action, method=method, timeout=timeout,
           hangup_on_star=hangup_on_star, time_limit=time_limit,
           caller_id=caller_id)
    return r
Example #30
0
def perform_call(number, caller_id=None):
    response = VoiceResponse()
    d = Dial()
    if number == PRIVATE_NUMBER:
        p = Play("http://phone.ehnerd.com/music/intro.wav")
        response.append(p)
        d.number(number, url="/callscreen")
    else:
        d.number(number)
    response.append(d)
    return str(response)
def dial(numbers, flavor=''):
    response = VoiceResponse()
    for num in numbers:
        dial = Dial()
        dial.number(num)
        response.append(dial)

    if flavor:
        response.say(flavor, voice='woman', language='en')

    return str(response)
Example #32
0
def generate_twiml():
    response = VoiceResponse()
    # inbound
    inbound = Start()
    inbound.stream(name='in Audio Stream',
                   url="wss://" + os.environ["WSS_URL"],
                   track="inbound_track")
    response.append(inbound)
    response.pause(length=call_duration)
    print(response)
    return str(response)
    def accessible(self):
        response = VoiceResponse()

        message = (
            "You were successfully redirected to an authenticated route. "
            "Goodbye."
        )
        response.say(message, voice="woman", language="en")
        response.hangup()

        return response
Example #34
0
def gather():
    resp = VoiceResponse()
    if 'SpeechResult' in request.values:
        name = request.values['SpeechResult']
        print("Name of the caller: " + name) #Check
        gatherSummary = Gather(input = 'speech dtmf', action='/location')
        gatherSummary.say("Hello " + name + callscripts.AskForReason)
        resp.append(gatherSummary)
        return str(resp)
    else:
        resp.redirect('/voice')
Example #35
0
def record_call():
    response = "Listen Up"
    if request.method == "POST":
        response = "Call in progess"
        response = VoiceResponse()
        response.say("This is your local policital office. Please leave your message.")
        response.record(transcribe=True, play_beep='true', max_length=20, transcribeCallback="/transcribing")

        return str(response)
    else:
        return response
def gather():
    resp = VoiceResponse()
    if 'Digits' in request.values:
        choice = request.values['Digits']
        if int(choice) == password:
            open_door(resp)
            return str(resp)
        else:
            resp.say("Invalid Password!")
            resp.hangup()
            return str(resp)
Example #37
0
def user_input():
    num = request.values.get('Digits', None)
    response = VoiceResponse()

    if num.isdigit():  # checks to make sure user entered a number
        output = fizz_buzz(int(num))
        response.say(" ".join(output))
        return str(response)
    else:
        response.say("The input wasn't digits. Feel free to try again")
        return str(response)
Example #38
0
def outbound():
    response = VoiceResponse()

    response.say(
        "Thank you for contacting our sales department. If this "
        "click to call application was in production, we would "
        "dial out to your sales team with the Dial verb.",
        voice='alice')

    response.number("+254740415950")
    return str(response)
Example #39
0
def get_capability_token():
    print("New call initiated...")
    print('Saying: "Thanks for calling Citi Bank!  How can I help you today?"')
    resp = VoiceResponse()
    gather = Gather(input='speech', partial_result_callback='/partial')
    gather.say("Thanks for calling Citi Bank!  How can I help you today?")
    threading.Thread(target=countDown).start()
    resp.append(gather)
    resp.redirect('/completed', method='POST')
    print(resp)
    return str(resp)
Example #40
0
def choose_theater(request: HttpRequest) -> HttpResponse:
    validate_django_request(request)
    vr = VoiceResponse()
    vr.say('Welcome to movie info!')

    with vr.gather(
            action=reverse('choose-movie'),
            finish_on_key='#',
            timeout=20,
    ) as gather:
        gather.say('Please choose a theater and press #')
        theaters = (Theater.objects.filter(
            digits__isnull=False).order_by('digits'))
        for theater in theaters:
            gather.say(
                f'For {theater.name} at {theater.address} press {theater.digits}'
            )

    vr.say('We did not receive your selection')
    vr.redirect('')

    return HttpResponse(str(vr), content_type='text/xml')
Example #41
0
def audio():
    id_aula = request.args.get('id')
    print('Consultado aula com id ' + id_aula + ', aguarde...')
    query = "SELECT url,materia,assunto FROM aulas where id = '" + id_aula + "'"
    linhas = consulta(query)
    if linhas != {}:
        print('Foi encontrado aula com o id referenciado. Criando página...')
        response = VoiceResponse()
        response.say("A aula de {}-{} será reproduzida em instantes.".format(
            linhas[0]['materia'], linhas[0]['assunto']),
                     language='pt-BR')
        response.play(configuracoes['URL_SERVER'] + 'audio?id=' + id_aula)
        response = response.to_xml()
        return response, 200, {'Content-Type': 'text/xml; charset=utf-8'}
    return 'error'
Example #42
0
    def decorated_function(*args, **kwargs):
        validator = RequestValidator(TWILIO_SECRET)
        url = list(urlparse(request.url))
        url[1] = url[1].encode("idna").decode("utf-8")
        url = urlunparse(url)

        signature = request.headers.get("X-TWILIO-SIGNATURE", "")

        request_valid = validator.validate(url, request.form, signature)

        if request_valid or current_app.debug:
            resp = VoiceResponse()
            f(resp, *args, **kwargs)
            return str(resp)

        else:
            return abort(403)
def voice():

    resp = VoiceResponse()
    # Greet the caller by name
    resp.say("Hello. It's me. ")
    # Play an mp3
    resp.play("http://howtodocs.s3.amazonaws.com/ahoyhoy.mp3")

    # Gather digits.
    with resp.gather(numDigits=1, action="/handle-gather", method="POST") as g:
        g.say("""To speak to a real person, press 1.
                 Press 2 to record a message for a Twilio educator.
                 Press any other key to start over.""")

    return str(resp)
Example #44
0
def incoming():
    """
    Handles incoming calls to the twilio numbers.
    Required Params: campaignId

    Each Twilio phone number needs to be configured to point to:
    server.org/call/incoming?campaignId=12345
    from twilio.com/user/account/phone-numbers/incoming
    """
    params, campaign = parse_params(request, inbound=True)

    if not params or not campaign:
        abort(400)

    if campaign.status == 'archived':
        resp = VoiceResponse()
        play_or_say(resp, campaign.audio('msg_campaign_complete'))
        return str(resp)

    # pull user phone from Twilio incoming request
    params['userPhone'] = request.values.get('From')
    campaign_number = request.values.get('To')

    # create incoming call session
    call_session_data = {
        'campaign_id': campaign.id,
        'from_number': campaign_number,
        'direction': 'inbound'
    }
    if current_app.config['LOG_PHONE_NUMBERS']:
        call_session_data['phone_number'] = params['userPhone']
        # user phone numbers are hashed by the init method
        # but some installations may not want to log at all

    call_session = Session(**call_session_data)
    db.session.add(call_session)
    db.session.commit()

    params['sessionId'] = call_session.id

    if campaign.segment_by == SEGMENT_BY_LOCATION and campaign.locate_by in [
            LOCATION_POSTAL, LOCATION_DISTRICT
    ]:
        return intro_location_gather(params, campaign)
    else:
        return intro_wait_human(params, campaign)
Example #45
0
def menu():
    ''''print("VIJAY:", request)
    print("form type:", type(request.form))
    print("ditionary:", request.form)
    for k in request.form.keys():
        print(k, request.form[k])'''

    selected_option = request.form['Digits']
    user_data[request.form['Caller']]['count']= 0
    option_actions = {'1': _reset_ad_password_get_emp_id}

    if selected_option in option_actions:
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()
Example #46
0
    def simple(delay):
        response = VoiceResponse()
        response.say(TwilioFizzBuzz.GREETING,
                     voice=TwilioFizzBuzz.VOICE_GENDER,
                     language=TwilioFizzBuzz.VOICE_LANGUAGE)

        gather = Gather(input=TwilioFizzBuzz.INPUT_TYPE,
                        method="GET",
                        timeout=TwilioFizzBuzz.INPUT_TIMEOUT,
                        num_digits=TwilioFizzBuzz.INPUT_DIGITS,
                        action='/fizzbuzz?delay=' + delay)
        gather.say('Please enter a number.',
                   voice=TwilioFizzBuzz.VOICE_GENDER,
                   language=TwilioFizzBuzz.VOICE_LANGUAGE)

        response.append(gather)
        response.redirect('/simple')  # If user doesn't input anything, restart

        return str(response)
Example #47
0
def collect():
    '''Respond to incoming phone calls with a menu of options'''
    resp = VoiceResponse()
    gather = Gather(num_digits=1,
                    action='/hooks/play?roomid={}'.format(
                        request.args.get('roomid')))
    gather.say(
        'Welcome to tic tac telephone. Use the keypad digits of 1-9 to play')
    resp.append(gather)
    # If the user doesn't select an option, redirect them into a loop
    resp.redirect('/hooks/collect')
    return str(resp)
Example #48
0
def validate(phone, true_code, _num_digits=6, _timeout=10):
    """Respond to incoming phone calls with a menu of options"""
    # Start our TwiML response
    resp = VoiceResponse()
    # Start our <Gather> verb
    # num_digits is how many digits in authentication
    inp = Gather(num_digits=_num_digits, timeout=_timeout)
    inp.say('Please enter your 6 digit passcode.')
    resp.append(inp)
    # If the user doesn't select an option, redirect them into a loop
    resp.redirect('/voice')
    return str(resp) == true_code
def voice():
    """Respond to incoming phone calls with a text message."""
    # Start our TwiML response
    resp = VoiceResponse()

    # Read a message aloud to the caller
    resp.say("Hello! You will get an SMS message soon.")

    # Also tell Twilio to send a text message to the caller
    resp.sms("This is the ship that made the Kessel Run in fourteen parsecs?")

    return str(resp)
def call_second_senator(senator_id):
    """Forward the caller to their second senator."""
    senator = Senator.query.get(senator_id)

    response = VoiceResponse()
    response.say("Connecting you to {}.".format(senator.name))
    response.dial(
        senator.phone,
        action=url_for('end_call')
    )

    return Response(str(response), 200, mimetype="application/xml")
Example #51
0
def call_action(request, name):
    response = VoiceResponse()
    menu = get_menu(name)
    items = get_menu_items(menu)
    action_text = None
    action_phone = None
    action_url = None
    next_menu = name
    next_page = None

    query_dict = get_query_dict(request)
    digit = query_dict['Digits']

    digit_items = items.filter(menu_digit=digit)
    if len(digit_items):
        item = digit_items.first()

        if item.action_text:
            action_text = item.action_text
        if item.action_phone:
            action_phone = item.action_phone
            if action_text is None:
                action_text = twilio_default_transfer
        if item.action_url:
            action_url = item.action_url
        elif item.action_submenu:
            next_menu = item.action_submenu.name
            next_page = "call-menu"

    if action_text is not None:
        twilio_say(menu, response, action_text)
    if action_phone is None:
        next_page = "call-menu"
        if action_text is not None:
            response.pause(1)
    else:
        if next_page is None:
            next_page = "call-end"
        response.dial(action_phone)
    if action_url is None:
        action_url = call_reverse(next_menu, next_page)
    response.redirect(action_url)
    return response
Example #52
0
def answer_call():
    # Hang up after giving a message to the caller
    global NUM_CALLS
    response = VoiceResponse()
    response.say("Hello! I'm very busy and important!")
    response.hangup()
    NUM_CALLS += 1
    caller = request.values.get("Caller")
    _text_caller(caller=caller)
    _text_user(from_number=caller)
    # Why can't I return "('', 204)" here?
    return str(response)
Example #53
0
def hello_user():
    global from_number
    from_number = request.values.get('To', None)
    print type(from_number)
    resp = VoiceResponse()
    for x in database.get_users():
        if str(x['phone']) == str(from_number):
            resp.say("Hello " + str(x['name']), voice='alice')
    resp.say("Are you available for the delivery Now ?", voice='alice')
    g = Gather(
        numDigits=1,
        action="/handle-yn",
        timeout=2,
        method="POST",
    )
    g.say("If Yes, Press 1, if No Press 2.", voice='alice')
    resp.append(g)

    return str(resp)
Example #54
0
def answer_call():
    #begin twilio response
    resp = VoiceResponse()

    # Read out the base IVR menu option
    resp.say("Welcome to Dr. Brewer's test message line!", voice='alice')
    resp.say("Press 1 to record a message for later use!", voice='alice')

    #grab the next digit entered
    resp.gather(numDigits=1, action='/start-recording')

    return str(resp)
def gather():
    """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 the one-time password input
        caller = request.values['From']

        if check_verification(caller, request.values['Digits']):
            resp.say("That was correct. Joining conference.")
            return join_conference(caller, resp)
        else:
            resp.say("Please try again.")
            resp.redirect('/voice')

    return str(resp)
Example #56
0
 def test_blacklist_works(self):
     with override_settings(DEBUG=False):
         request = self.factory.post(self.str_uri, {'From': '+13333333333'})
         response = str_view(request)
         r = VoiceResponse()
         r.reject()
         self.assertEqual(
             response.content,
             str(r).encode('utf-8'),
         )
     with override_settings(DEBUG=True):
         request = self.factory.post(self.str_uri, {'From': '+13333333333'})
         response = str_view(request)
         r = VoiceResponse()
         r.reject()
         self.assertEqual(
             response.content,
             str(r).encode('utf-8'),
         )
Example #57
0
def retrieve_recording():
    resp = VoiceResponse()
    global recording
    recording = request.form.get('RecordingUrl')
    print(recording)

    resp.say(
        "If you would like to hear the message you just recorded, please press 2 now. Otherwise, you may hang up to end the call.",
        voice='alice')
    resp.gather(numDigits=1, action='/play-recording')

    return str(resp)
Example #58
0
def handle_incoming():
    response = VoiceResponse()

    gather = Gather(action='/say_fizzbuzz', method='POST')

    gather.say(
        'Enter the upper bound for fizzbuzz, followed by the pound symbol')

    response.append(gather)
    response.say('Thank you for using PhoneBuzz')

    return str(response)
Example #59
0
def start_recording():
    resp = VoiceResponse()
    #check to see if the caller actually pressed 1, and start the recording if so
    if ('Digits' in request.values) and (request.values['Digits'] == '1'):
        resp.say(
            "Please record your message after the tone, and press star to finish",
            voice='alice')
        resp.record(max_length="30",
                    finishOnKey='*',
                    action='/retrieve-recording')

    return str(resp)