Пример #1
0
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)
Пример #2
0
def outbound1():
    strr = request.form.get('SpeechResult')  #работа с вебом
    print(strr)
    #doc = nlp(strr)
    #print(doc.ents)
    '''
    
    if 'Color' in doc.ents.keys:
        add to db and form next question
    else:
        form reanswer request
        
    
    
    '''
    twiml_response = VoiceResponse(
    )  #twiML элемент response с него всегда нужно начинать twiML
    twiml_response.say('hi silly boy')  #twiML текст2спич
    twiml_response.play('http://k003.kiwi6.com/hotlink/9njt732wby/lol.mp3'
                        )  #twiML проигрование mp3
    # gather = Gather(action='http://28e81dff.ngrok.io/outbound2', input='speech', speechTimeout='auto')
    # gather.say('what car do you have?')
    # twiml_response.append(gather)
    # twiml_response.say('We didn\'t receive any input. Goodbye!')
    twiml_xml = twiml_response.to_xml(
    )  #twiML обязательный перевод в xml поскольку твилио это чистый xml
    return str(
        twiml_xml
    )  #twiML в конце перевожу в строку, потому что так было в примерчике
Пример #3
0
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)
Пример #4
0
def answeredby(request):
    # build validator manually because decorator not working
    logger.info(request.build_absolute_uri())
    twilio_request = decompose(request)
    validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)

    # Validate the request using its URL, POST data,
    # and X-TWILIO-SIGNATURE header
    request_valid = validator.validate(
        request.build_absolute_uri(), request.POST,
        request.META.get('HTTP_X_TWILIO_SIGNATURE', ''))

    if not request_valid:
        return HttpResponseForbidden()

    outbound = Outbound.objects.get(twilio_sid=twilio_request.callsid)
    response = VoiceResponse()

    if twilio_request.answeredby in ['human', 'unknown']:
        response.play(outbound.action.audio_file.url)

    else:
        response.hangup()

    outbound.answered_by = twilio_request.answeredby
    outbound.save()

    return HttpResponse(response)
Пример #5
0
def call_collect():
    resp = VoiceResponse()
    prompt = request.values.get('prompt')
    previous_recording = request.values.get('RecordingUrl')
    index = prompts.index(prompt)

    # Save recording from previous prompt
    if previous_recording:
        client = Client(account_sid, auth_token)
        client.messages.create(to=to_phone_number,
                               from_=from_phone_number,
                               body='New reply to prompt %d: %s' %
                               (index, previous_recording))

    # Say the current prompt_url
    prompt_url = app_url(request) + url_for('static',
                                            filename='prompts/' + prompt)
    resp.play(prompt_url)

    # Record and go to next prompt, if not the last prompt
    if index < len(prompts) - 1:
        action = '/call-collect?prompt=' + prompts[index + 1]
        resp.record(maxLength='300', action=action, finishOnKey='1')

    return str(resp)
Пример #6
0
def voice():

    resp = VoiceResponse()

    resp.play('https://files.freemusicarchive.org/storage-freemusicarchive-org/music/ccCommunity/Chad_Crouch/Field_Report_Vol_II_Reed_Canyon_Instrumental/Chad_Crouch_-_05_-_Song_Sparrow_Serenade_Instrumental.mp3', loop=1)

    return str(resp)
def voice():
    """Respond to incoming phone calls"""
    resp = VoiceResponse()
    incoming_number = request.values['From']

    # If an unknown number, filter out robo callers and forward to cell
    if incoming_number not in whitelisted_numbers:
        gather = Gather(num_digits=1, action='/buzzer/forward')
        gather.say('Press 1 to continue')
        resp.append(gather)

        return str(resp)

    # Tell the user a nice message that they are not permitted to enter
    if not allowed_to_buzz():
        resp.say(
            "The system cannot let you in. Did you dial the right buzzcode?")
        send_message(
            "A visitor was just rejected as the buzzer system was not unlocked"
        )
        return str(resp)

    # Otherwise, unlock the door
    resp.say(say_message, language='zh-CN')
    resp.play(digits=buzzcode)
    send_message("A visitor was just let in")

    return str(resp)
Пример #8
0
def voice():
    resp = VoiceResponse()
    print("HERE")
    print(str(resp))
    global isOpen
    global limited
    global numOfOpens
    global password
    if isOpen:
        resp.play(digits='wwwww9')
        time.sleep(2)
        print(str(resp))
        print(str(resp))
        return str(resp)
    if limited and numOfOpens > 0:
        numOfOpens -= 1
        if numOfOpens <= 0:
            limited = False
        open_door(resp)
        return str(resp)
    if password:
        gather = Gather(action='/gather')
        gather.say("Please Enter the password, then press pound")
        resp.append(gather)
        return str(resp)
    else:
        resp.say("Sorry, this apartment is not available right now")
Пример #9
0
def callQ_handle():
	resp = VoiceResponse()
	conferences = client.conferences.list(status="in-progress", friendly_name="TEST")
	if(conferences == [])
		resp.redirect("/pop-first")
	resp.play(hold_mp3, loop=1)
	return str(resp)
Пример #10
0
def recording_handle():
	resp = VoiceResponse()
#	vm = request.form["RecordingUrl"]
#	SID = vm.rsplit('/', 1)[-1]
	resp.say("Thank you for leaving a voicemail. We will get back to you as soon as we can.")
	resp.play(hold_mp3, loop=0)
	return str(resp)
Пример #11
0
def verify():
    twilio_api = TwilioApi(opengateapp_config)

    if db.get_response_received() == False:
        response = VoiceResponse()
        response.redirect('/verify/')
        return str(response)

    response = db.get_sms_response()
    if response == "Yes":
        response = VoiceResponse()
        response.play('', digits='www99')
        twilio_api.gate_opened_notificiation()
        db.reset_response()
        return str(response)

    elif response == "No":
        response = VoiceResponse()
        response.say("Denied")
        db.reset_response()
        return str(response)

    else:
        response = VoiceResponse()
        response.redirect('/verify/')
        return str(response)
Пример #12
0
def bug_report():
    rick_roll = url_for('static', filename='rick_roll.mp3')
    resp = VoiceResponse()

    if 'Digits' in request.values:
        choice = request.values['Digits']

        if choice == '1':
            resp.say('Please describe the bug.', voice='man')
            resp.pause(5)
            excuse = EXCUSES[randint(1, 4)]
            resp.say('Here is a thoughtful solution to that bug: ',
                     voice='man')
            resp.say(excuse, voice='man')
            resp.redirect('/greeting')
        elif choice == '2':
            insult = get_insult()
            resp.say('Please extol our virtues', voice='man')
            resp.pause(5)
            resp.say(
                'Thanks for that. Here is a random thought we have about you: ',
                voice='man')
            resp.say(insult, voice='man')
            resp.redirect('/greeting')
        elif choice == '3':
            resp.say('Wait for it', voice='man')
            resp.play('https://demo.twilio.com/docs/classic.mp3')
            resp.redirect('/greeting')

    resp.redirect('/greeting')

    return str(resp)
Пример #13
0
def play_recording():
    resp = VoiceResponse()
    print(recording)
    if ('Digits' in request.values) and (request.values['Digits'] == '2'):
        #print("recording="+recording)
        resp.play(recording, loop=1)
    return str(resp)
Пример #14
0
    def execute(self):
        resp = self.handle_hours()
        if resp is not None:
            return str(resp)

        resp = VoiceResponse()

        if self.section_data['play_sample']:
            resp.play(self.section_data['play_sample'])
            resp.pause(1)

        voicemail_timeout = int(self.section_data['voicemail_timeout'])
        voicemail_max_length = int(self.section_data['voicemail_max_length'])

        resp.record(
            action=self.url_of(
                f'/ivr/callback/voicemail/hangup?initiated_by_section={self.name}'
            ),
            timeout=voicemail_timeout,
            max_length=voicemail_max_length,
            recording_status_callback=self.url_of(
                f'/ivr/callback/voicemail/alert_sms?initiated_by_section={self.name}'
            ),
            recording_status_callback_method='POST')

        return str(resp)
Пример #15
0
    def execute(self):
        resp = self.handle_hours()
        if resp is not None:
            return str(resp)

        resp = VoiceResponse()

        gather = Gather()
        gather.play(self.section_data['play_sample'], digits=1)

        pause = 2
        if 'pause' in self.section_data.keys():
            pause = int(self.section_data['pause'])

        gather.pause(length=pause)

        resp.append(gather)

        if ('no_input_max_loops' in self.section_data.keys()
                and self.loop_count >= int(
                    self.section_data['no_input_max_loops'])):
            if 'no_input_action_on_max_loops' in self.section_data.keys():
                resp.redirect(
                    self.url_of(
                        '/ivr/action/' +
                        self.section_data['no_input_action_on_max_loops']))
            else:
                resp.hangup()

        if 'no_input_sample' in self.section_data.keys():
            resp.play(self.section_data['no_input_sample'])

        resp.redirect(self.url_of(f'/ivr/menu?loop_count={self.loop_count}'))

        return str(resp)
Пример #16
0
def call():
	resp = VoiceResponse()
	# Play fake ringing
	resp.play('{}static/mp3/ringing.mp3'.format(os.getenv('BASE_URL')))
	# Start recording
	resp.record(timeout=20, transcribe=True, play_beep=False)
	resp.hangup()
	return str(resp)
Пример #17
0
 def play(self):
     """
     Return valid TwiML to Twilio for call.
     """
     response = VoiceResponse()
     response.play('http://%s:%s/call.mp3' %
                   (settings.ROOT_URL, settings.PORT))
     return str(response)
Пример #18
0
def music():
    response = VoiceResponse()
    # bonnie's bops!
    url = "https://s3.us-west-2.amazonaws.com/secure.notion-static.com/54470100-46cf-448c-b968-23b226eac638/music.mp3?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20201122%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20201122T100457Z&X-Amz-Expires=86400&X-Amz-Signature=984eafca1aef5b3c2687084a09c0db0a47037a39619a90c47dd04ce3bbc313f2&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22music.mp3%22";
    response.play(url, loop=10)
    response.redirect(url_for('agent'))

    return twiml_resp(response)
Пример #19
0
def voice():
    """Respond to incoming phone calls with '9'"""
    resp = VoiceResponse()

    resp.play('', digits='www9')
    resp.hangup()

    return str(resp)
Пример #20
0
def construct_response(path):
    """ return an xml response to request """
    url = '{}/Music/{}'.format(home_url, str(path))

    response = VoiceResponse()
    response.say("This is a music gift just for you!", voice='man')
    response.play(url)
    return str(response)
def exchange_voice():
    form = ExchangeForm()
    outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

    response = VoiceResponse()
    response.play("http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")
    response.dial(outgoing_number)
    return twiml(response)
Пример #22
0
    def test_play_hello(self):
        """ should play hello monkey """
        r = VoiceResponse()
        r.play('http://hellomonkey.mp3')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Play>http://hellomonkey.mp3</Play></Response>'
        )
Пример #23
0
def car():
    """Respond to incoming phone calls with a brief message."""
    # Start our TwiML response
    response = VoiceResponse()
    response.play('https://youcustomizeit.s3.us-east-2.amazonaws.com/car.mp3')
    # Read a message aloud to the caller
    # response.say("Thank you for calling! Have a great day.")

    return str(response)
Пример #24
0
def leave_message():
    recording_url = request.values.get("RecordingUrl", None)
    response = VoiceResponse()
    response.say(
        "Thanks for leaving a message... if you would like to listen to the message you just left, please stay on the line."
    )
    response.play(recording_url)
    response.say("Goodbye.")
    return str(response)
Пример #25
0
def ivrSend_view(request):
    audioID = request.matchdict["audioid"]
    response = VoiceResponse()
    response.play(
        request.url_for_static("static/audio/" + getAudioFileName(request, audioID)),
        loop=0,
    )
    response.hangup()
    return twiml(response)
Пример #26
0
def handle_recording(request):

    recording_url = request.values.get("RecordingUrl", None)

    resp = VoiceResponse()
    resp.say("Thanks for leaving a message... take a listen to what you said.")
    resp.play(recording_url)
    resp.say("Goodbye.")
    return HttpResponse(str(resp))
Пример #27
0
    def test_play_digits(self):
        """ should play digits """
        r = VoiceResponse()
        r.play(digits='w123')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Play digits="w123" /></Response>'
        )
Пример #28
0
    def test_play_hello_loop(self):
        """ should play hello monkey loop """
        r = VoiceResponse()
        r.play(url='http://hellomonkey.mp3', loop=3)

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Play loop="3">http://hellomonkey.mp3</Play></Response>'
        )
Пример #29
0
    def test_empty_play(self):
        """ should play hello monkey """
        r = VoiceResponse()
        r.play()

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Play /></Response>'
        )
Пример #30
0
def directions_view(request):
    # some kind of auth ...
    # implement twilio signatures later, need https for that...
    print request.GET.get('IvrType')
    #    if request.GET.get('AccountSid') == settings.TWILIO_ACCOUNT_SID:

    if request.GET.get('IvrType') == 'custom' or request.GET.get(
            'IvrType') == 'aggregate':
        # first get the AutocallPk from GET params
        autocall_pk = long(request.GET.get('AutocallPk'))
        # retrieve autocall by pk
        autocall = Autocall.objects.get(pk=autocall_pk)
        # now get call directions
        number_of_steps = autocall.number_of_steps  # don't need this, just use @property call_steps
        transcribe_seconds = autocall.transcribe_seconds

        # action url for record verb in twiML,
        # after recording is completed, call will be directed to this url i.e. even hangup verb is unreachable after Record verb
        # only if Record receives empty recording, it continues disregards action url and continues with next verb
        action_url = settings.HOST + "process/directions/hangup/"
        # transcription of the recording will be sent there once available
        # asynchronous POST with TranscriptionText as one of the params
        transcribe_url = settings.HOST + "process/transcription/"

        response = VoiceResponse()

        for step in autocall.call_steps:
            #step = (promt, enter_keys, wait_time)
            response.pause(length=step[2])
            response.play(digits=step[1])

        # for testing purposes, short pause when recording the whole call, instead of response.record below
        #response.pause(length=10)

        response.record(
            action=action_url,
            method='GET',
            # timeout after 30s of silence, stop recording
            timeout=30,
            # max_length of the recording
            max_length=transcribe_seconds,
            # don't need beep sound before recording (default is True)
            play_beep=False,
            # do not trim silence
            #trim = 'do-not-trim',
            # if transcribeCallback is given, transcribe=True is implied
            transcribe_callback=transcribe_url,
        )

        response.hangup()
        # this verb will be reached only if recording is empty

        return HttpResponse(str(response))

    else:
        return HttpResponse(status=401)
def handle_recording():
    """Play back the caller's recording."""

    recording_url = request.values.get("RecordingUrl", None)

    resp = VoiceResponse()
    resp.say("Listen to your recorded message.")
    resp.play(recording_url)
    resp.say("Goodbye.")
    return str(resp)
Пример #32
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)
Пример #33
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)
Пример #34
0
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)
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)
Пример #36
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
Пример #37
0
    def password_entered():
        digits = request.values['Digits']
        logger.info("Password entered: %s", digits)

        response = VoiceResponse()
        if digits == "12345":
            correct_clip = pick_random_file("correct")
            response.play(correct_clip)
            response.play(digits="9")
        elif digits == "54321":
            response.play(digits="99")
        else:
            wrong_clip = pick_random_file("wrong")
            response.play(wrong_clip)
            add_gandalf_to_response(response)

        return str(response)
Пример #38
0
from twilio.twiml.voice_response import Play, VoiceResponse

response = VoiceResponse()
response.play(
    'http://com.twilio.sounds.music.s3.amazonaws.com/MARKOVICHAMP-Borghestral.mp3'
)

print(response)
Пример #39
0
from twilio.twiml.voice_response import Play, VoiceResponse

response = VoiceResponse()
response.play('https://api.twilio.com/cowbell.mp3', loop=10)

print(response)
from twilio.twiml.voice_response import Play, VoiceResponse, Say

response = VoiceResponse()
response.say('Hello World')
response.play('https://api.twilio.com/Cowbell.mp3')

print(response)
Пример #41
0
from twilio.twiml.voice_response import Play, VoiceResponse

response = VoiceResponse()
response.play('', digits='wwww3')

print(response)
Пример #42
0
def route_call(request):


    digits = int(request.POST.get('Digits', '0'))
    call_origin = request.POST.get('From', None)

    call_log = Call.objects.create(twilio_id=request.POST.get('CallSid', None), 
                                   type="incoming", 
                                   incoming_number=call_origin)
    if digits == 1:
        message = "https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/ivr/audio-transferring-sales.mp3"
        numbers = [(73, '+66819189145')]
        clients = [(73, "sidarat")]
        caller_id = call_origin or '+6625088681'

        call_log.forwarding_number = '+66819189145'
        call_log.save()

    elif digits == 2:
        message = "https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/ivr/audio-transferring-customer-service.mp3"
        numbers = [(16, '+66914928558'), (42, '+66952471426'), (42, '+66634646465')]
        clients = [(16, "chup"), (42, 'apaporn')]
        caller_id = '+6625088681'

    elif digits == 3:
        message = "https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/ivr/audio-transferring-accounting.mp3"
        numbers = [(63, '+66988325610')]
        clients = [(63, "mays")]
        caller_id = '+6625088681'

    elif digits == 8:
        message = "https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/ivr/audio-transferring-accounting.mp3"
        numbers = [(1, '+66990041468')]
        clients = [(1, "charliephairoj")]
        caller_id = "+6625088681"

        call_log.forwarding_number = '+66990041468'
        call_log.save()

    else:
        message = "https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/ivr/audio-transferring-customer-service.mp3"
        numbers = [(16, '+66914928558'), (42, '+66952471426')]
        clients = [(16, "chup"), (42, 'apaporn')]
        caller_id = '+6625088681' or '+6625088681'

    resp = VoiceResponse()
    resp.play(message)

    dial = Dial(caller_id=caller_id, 
                record='record-from-ringing', 
                recording_status_callback="/api/v1/ivr/recording/")

    for number in numbers:
        dial.number(number[1],
                    status_callback_event='answered completed',
                    status_callback=_get_status_callback_url(number[0]),
                    status_callback_method="GET")
    
    for client in clients:
        dial.client(client[1],
                    status_callback_event='answered completed',
                    status_callback=_get_status_callback_url(client[0]),
                    status_callback_method="GET")

    resp.append(dial)

    return HttpResponse(resp)