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)
def startRecording(): resp = VoiceResponse() if 'Digits' in request.values and request.values['Digits'] == '1': caller = request.values.get("From", None) slacktext = '{} pressed 1 and should speak in Dutch.'.format(caller) sc.api_call('chat.postMessage', channel=slack_channel, text=slacktext, username=caller, icon_emoji=':phone:') resp.record(max_length=120, play_beep=True, action="/end-call-dutch") elif 'Digits' in request.values and request.values['Digits'] == '2': caller = request.values.get("From", None) slacktext = '{} pressed 2 and should speak in English.'.format(caller) sc.api_call('chat.postMessage', channel=slack_channel, text=slacktext, username=caller, icon_emoji=':phone:') resp.record(max_length=120, play_beep=True, action="/end-call-english") else: caller = request.values.get("From", None) slacktext = '{} punched his phone and should learn to listen.'.format( caller) sc.api_call('chat.postMessage', channel=slack_channel, text=slacktext, username=caller, icon_emoji=':phone:') resp.say(text['recording']) resp.gather(num_digits=1, action='/start-recording', timeout=15) return str(resp)
def post(self, request): """ Serve the Twilio client directions for collecting input. """ voice_response = VoiceResponse() if self.accept_keypress: keypress_timeout = 0 if self.accept_speech else self.timeout gather = Gather(input='dtmf', action=reverse(self.submit_view), finish_on_key='', timeout=keypress_timeout, num_digits=1) self.ask(request, gather) voice_response.append(gather) else: self.ask(request, voice_response) if self.accept_speech: end_keys = SKIP_DIGIT + REPEAT_DIGIT + digits if self.accept_keypress else '' voice_response.record(action=reverse(self.submit_view), play_beep=self.play_beep, timeout=self.timeout, max_length=self.recording_max_duration, recording_status_callback=reverse( self.recording_callback), finish_on_key=end_keys) self.fallback(voice_response) voice_response.redirect(reverse(self.submit_view)) return HttpResponse(voice_response, content_type='application/xml')
def record(): client = Client(account_sid, auth_token) # Start our TwiML response response = VoiceResponse() # Use <Say> to give the caller some instructions response.say('Hello this is LINC. What would you like to talk about?') # Use <Record> to record the caller's message response.record(transcribe=True, playBeep=True, timeout=4) # response.pause(length=3) client = Client(account_sid, auth_token) trans_list = client.transcriptions.list() for transcription in trans_list: latest_transcript = transcription.transcription_text status = transcription.status if (latest_transcript != None): unicodedata.normalize('NFKD', latest_transcript).encode('ascii', 'ignore') print(status) print(transcription.sid) print(latest_transcript) transcription.delete() break else: response.say("I'm sorry. I didn't get that. Can you repeat it?") print(latest_transcript != "hello") if (latest_transcript != "hello"): print("boolean worked") response.redirect("http://4b930e15.ngrok.io/voice_response") response.hangup() return str(response)
def menu(request: request.HttpRequest): try: _ = request.META['HTTP_X_TWILIO_SIGNATURE'] digit = request.POST.get('Digits') from_number = request.POST.get("From").strip("+") call_sid = request.POST.get("CallSid") channel_layer = channels.layers.get_channel_layer() resp = VoiceResponse() #record if digit == '1': resp.say("Please leave a message. Press the pound or hash key to end the recording.") #without an action or recording_status_callback attribute then you will have an endless loop of calling into the view resp.record(play_beep=True, max_length=30, finish_on_key="#", recording_status_callback="/api/record/", action="/api/hangup/") async_to_sync(channel_layer.group_send)(f"chat_{from_number}", {"type": "chat_message", "message": 'Incoming recording...'}) #stream elif digit == '2': caller: Caller = Caller.objects.get(number=from_number) Call(sid=call_sid, length_of_call=0, caller_id=caller.id, call_type="L").save() redisController.set(key=call_sid,value=from_number) async_to_sync(channel_layer.group_send)(f"chat_{from_number}", {"type": "chat_message", "stream": True, "message": 'Incoming stream...'}) resp.say("Please begin speaking...") connect = Connect() connect.stream(url=ws_url) resp.append(connect) else: resp.say("Incorrect entry. Please try again.") resp.redirect('/api/voice/') return HttpResponse(str(resp)) except KeyError: return
async def answer_backend(): response = VoiceResponse() call_id = request.args["CallSid"] try: connection_to_communicate = Glob["ws_" + call_id] except: print("error") RecordingUrl = request.args["RecordingUrl"] parsed_RecordingUrl = urllib.parse.unquote(RecordingUrl) recording = requests.get(parsed_RecordingUrl) print("sending response from %s" % parsed_RecordingUrl) connection_to_communicate.send(recording.content, opcode=ABNF.OPCODE_BINARY) reply = connection_to_communicate.recv() j = json.loads(reply) if j['ask_flag'] == False: if j['ask_flag'] == False and j['exit_flag'] == False: second_response = await get_second_response_from_stephnie( connection_to_communicate) text = j['text'] + second_response else: text = j['text'] response.say(text, voice='alice', language='en-AU') response.hangup() connection_to_communicate.close() return str(response) else: text = j['text'] print(text) response.say(text + INSTRUCTION, voice='alice', language='en-AU') response.record(action="/answer_backend", method='GET', trim="do-not-trim") return str(response)
def answer(): global second_lang second_lang = '' response = VoiceResponse() response.say('Hello, what language do you want to translate to?') response.record(action='/recorded', timeout=2, trim='trim-silence') return str(response)
def handle_key(): """Handle key press from a user.""" digit_pressed = request.values.get('Digits', None) if digit_pressed == "1": print('{}, record'.format(request.values.get("From", None))) resp = VoiceResponse() resp.play(path_for_recording('leave_message')) resp.record(timeout=5, trim='trim-silence', action="/handle-recording") return str(resp) elif digit_pressed == "2": print('{}, listen'.format(request.values.get("From", None))) resp = VoiceResponse() resp.play(path_for_recording('listen')) rand_message = Recording.query.order_by(func.random()).first() resp.play(rand_message.url) resp.play(path_for_recording('bye')) return str(resp) else: return redirect("/")
def recordAndSend(): resp = VoiceResponse() if 'Digits' in request.values: choice = request.values['Digits'] if choice == '1': resp.say("Hi, how can I help you today?", voice='alice', language="en-US") resp.record(maxLength=20, timeout=10, transcribe=True, transcribeCallback="/handleVoiceResponse") print(resp) return str(resp) if choice == '2': resp.say("Please stay online.", voice='alice', language="en-US") resp.hangup() else: resp.say("We got your msg. Thank you.", voice='alice', language="en-US") resp.hangup() return str(resp)
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)
def forward_call(request): """Connects an incoming call to the correct forwarding number""" # First look up the lead source source = LeadSources.objects.get(incoming_number=request.POST['Called']) # Then look up the lead's user user = source.user # Create a lead entry for this call lead = Lead( user=user, source=source, phone_number=request.POST['Caller'], city=request.POST['CallerCity'], state=request.POST['CallerState'], zipcode=request.POST['CallerZip'], ) lead.save() # Immediately create a recent call entry call = Call(user=user, lead_number=request.POST['Caller'], lead_source=source, forwarding_number=getattr(source, 'forwarding_number')) call.save() # Respond with some TwiML that connects the caller to the forwarding_number response = VoiceResponse() response.record() response.dial(source.forwarding_number.as_e164) return HttpResponse(response)
def post(self, request, *args, **kwargs): survey_id = request.GET.get('survey') survey_phone = request.GET.get('phone') survey_model = Survey.objects.get(id=survey_id) survey_script_flow = survey_model.script_flow['data'] survey_response = request.GET.get('response') print('Answer CallSid', request.data['CallSid']) # Quickly creating the response field just to let react knows that we are working on this response response_model = Response.objects.create( question_id=str(survey_script_flow[0]['id'])) response_model.save() survey_model = SurveyResponse.objects.get(id=survey_response) survey_model.responses.add(response_model.id) response = VoiceResponse() response.say(survey_script_flow[0]['question'], voice=survey_script_flow[0]['voice_gender']) response.record( timeout=3, max_length=survey_script_flow[0]['record_time'], action=WEBSITE_URL + '/next/?counter=1&survey=' + str(survey_id) + '&response=' + str(survey_response), # maxLength recordingStatusCallback=WEBSITE_URL + '/save/?survey=' + str(survey_id) + '&question=' + str(survey_script_flow[0]['id']) + '&response=' + str(survey_response), trim="trim-silence") response.say('I did not receive a recording') response.hangup() print(str(response)) return HttpResponse(str(response), content_type='text/xml')
def record(request, action=None, method='POST', timeout=None, finish_on_key=None, max_length=None, transcribe=None, transcribe_callback=None, play_beep=None): """ See: http://www.twilio.com/docs/api/twiml/record. Usage:: # urls.py urlpatterns = patterns('', # ... url(r'^record/$', 'django_twilio.views.record'), # ... ) """ r = VoiceResponse() r.record(action=action, method=method, timeout=timeout, finishOnKey=finish_on_key, maxLength=max_length, transcribe=transcribe, transcribeCallback=transcribe_callback, playBeep=play_beep) return r
def answer_call(): """Respond to incoming phone calls with a brief message if phone number is not recognized by our database.""" """If the phone number calling us is in the database, user may merge call and record.""" # Start TwiML response resp = VoiceResponse() # Read a message aloud to the caller if caller calls the twilio num # If caller number in database, record, otherwise, text to voice message. data = request.form caller_num = data["Caller"][2:] caller = User.query.filter_by(phone_num=caller_num).all() user_num = caller[0].phone_num if user_num == caller_num: resp.record( method='GET', timeout=24 * 60 * 60, #24 hours is a nice large upper bound finish_on_key='', action=BASE_URL + "incoming-call-to-db") else: resp.say("The person you are trying to reach is unavailable", voice='alice') #print("######## request form {}".format(request.form)) # Recording caller's phone call #resp.record() #end the call when caller hangsup resp.hangup() r = str(resp) #r = r.replace("finishonkey","finishOnKey") print("########## NEW RESP = {}".format(str(r))) return r
def answer_call(): resp = VoiceResponse() resp.say( "I am the notetaker I will help you to take notes. Tell me what I should write down", voice='alice') resp.record(timeout="60", transcribe="True") return str(resp)
def incoming(): response = VoiceResponse() response.say('Please leave a message') response.record() response.hangup() return twiml(response)
def twilio_voicemail(matrix_id,send_notification): twilio_client = util.getTwilioClient(matrix_id) call = twilio_client.calls(request.values["CallSid"]).fetch() to_number = call.to from_number = call.from_ try: call_status = request.values["DialCallStatus"] except: call_status = request.values["CallStatus"] json_config = util.getIncomingNumberConfig(matrix_id, to_number) url = util.getAppserviceAddress().rstrip('/') + urllib.parse.urlparse(request.url).path response = VoiceResponse() if json_config["voicemail_enabled"] and call_status != "completed": room_id = util.findRoomId(matrix_id,[to_number] + [from_number]) author = util.getBotMatrixId() if send_notification: util.sendMsgToRoom(room_id,author, "missed call") response.say(json_config["voicemail_tts"]) kwargs = { "timeout": json_config["voicemail_timeout"], "transcribe": json_config["voicemail_transcribe"], "playBeep": True, "recordingStatusCallback": util.adjustUrl(url,"voicemail_recording"), "action": util.adjustUrl(url,"reject"), "transcribeCallback": util.adjustUrl(url,"voicemail_transcription") } response.record(**kwargs) else: response.reject() return str(response)
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)
def record_welcome(): response = VoiceResponse() currentTestCaseid=request.values.get("test_case_id", None) prompt_duration=request.values.get("prompt_duration", '') username=request.values.get("user_name", '') #response.record(trim="trim-silence", action=url_for('.recording', StepNumber=1, TestCaseId=[currentTestCaseid], user_name=[username],_external=True), timeout="3", playBeep="false", maxLength=prompt_duration, recordingStatusCallback=url_for('.recording_stat', step=[1], currentTestCaseID=[currentTestCaseid], user_name=[username], _scheme='https', _external=True),recordingStatusCallbackMethod="POST") response.record(trim="trim-silence", action=url_for('.recording', StepNumber=1, TestCaseId=[currentTestCaseid], user_name=[username],_external=True), timeout="3", playBeep="false", maxLength=prompt_duration) return str(response)
def voice(): # Start our TwiML response response = VoiceResponse() response.say('Hi! I want to know what do you think about coding.') response.record(maxLength="10", action="/recording") response.hangup() return str(response)
def record(): response = VoiceResponse() response.say('Hello. Please leave a message after the beep.') response.record() return str(response)
def record(): response = VoiceResponse() response.record(timeout=2, transcribe=True, max_length=60, play_beep=False, action=api_url + '/call-ended') return str(response)
def voice(): response = VoiceResponse() response.say( 'Hello, welcome to Joes Court House. Your call might be recorded.') #response.dial("+19734070493", timeLimit="10", record="record-from-answer-dual", trim="trim-silence") response.record(maxLength="10", action="/recording") response.hangup() return str(response)
def test_record_transcribe(self): """ should record with a transcribe and transcribeCallback """ r = VoiceResponse() r.record(transcribe_callback='example.com') assert_equal( self.strip(r), '<?xml version="1.0" encoding="UTF-8"?><Response><Record transcribeCallback="example.com" /></Response>' )
def test_record_max_length_finish_timeout(self): """ should record with an maxLength, finishOnKey, and timeout """ r = VoiceResponse() r.record(timeout=4, finish_on_key='#', max_length=30) assert_equal( self.strip(r), '<?xml version="1.0" encoding="UTF-8"?><Response><Record finishOnKey="#" maxLength="30" timeout="4" /></Response>' )
def test_record_empty(self): """ should record """ r = VoiceResponse() r.record() assert_equal( self.strip(r), '<?xml version="1.0" encoding="UTF-8"?><Response><Record /></Response>' )
def test_record_action_method(self): """ should record with an action and a get method """ r = VoiceResponse() r.record(action='example.com', method='GET') assert_equal( self.strip(r), '<?xml version="1.0" encoding="UTF-8"?><Response><Record action="example.com" method="GET" /></Response>' )
def handle_voice(): """Handle incoming voice calls.""" response = VoiceResponse() response.say("Record a message and stay on the line when finished.") response.record(timeout=2, action='/record_action', recordingStatusCallback='/recording_status') print(response) return str(response)
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 record(): response = VoiceResponse() response.say("What's cracking, fool?", loop=1) # response.play("/audio/beep.wav") response.record(max_length=30, timeout=30, action="/hangup", transcribe_callback="/transcribe") response.hangup() return str(response)
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)
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)
def record(): """Returns TwiML which prompts the caller to record a message""" # Start our TwiML response response = VoiceResponse() # Use <Say> to give the caller some instructions response.say('Hello. Please leave a message after the beep.') # Use <Record> to record the caller's message response.record() # End the call with <Hangup> response.hangup() return str(response)
def record(): """Returns TwiML which prompts the caller to record a message""" # Start our TwiML response response = VoiceResponse() # Use <Say> to give the caller some instructions response.say('Hello. Please leave a message and I will transcribe it.') # Use <Record> to record and transcribe the caller's message response.record(transcribe=True, max_length=30) # End the call with <Hangup> response.hangup() return str(response)
def record(request, action=None, method='POST', timeout=None, finish_on_key=None, max_length=None, transcribe=None, transcribe_callback=None, play_beep=None): """ See: http://www.twilio.com/docs/api/twiml/record. Usage:: # urls.py urlpatterns = patterns('', # ... url(r'^record/$', 'django_twilio.views.record'), # ... ) """ r = VoiceResponse() r.record(action=action, method=method, timeout=timeout, finish_on_key=finish_on_key, max_length=max_length, transcribe=transcribe, transcribe_callback=transcribe_callback, play_beep=play_beep) return r
def handle_gather(): """Handle key press from a user.""" digit_pressed = request.values.get('Digits', None) if digit_pressed == "1": resp = VoiceResponse() # Dial (310) 555-1212 - connect that number to the incoming caller. resp.dial("+13105551212") # If the dial fails: resp.say("The call failed, or the remote party hung up. Goodbye.") return str(resp) elif digit_pressed == "2": resp = VoiceResponse() resp.say("Record your message after the tone.") resp.record(maxLength="30", action="/handle-recording") return str(resp) # If the caller pressed anything but 1, redirect them to the homepage. else: return redirect("/")
from twilio.twiml.voice_response import Record, VoiceResponse, Say response = VoiceResponse() response.say( 'Please leave a message at the beep.\nPress the star key when finished.' ) response.record( action='http://foo.edu/handleRecording.php', method='GET', max_length=20, finish_on_key='*' ) response.say('I did not receive a recording') print(response)
from twilio.twiml.voice_response import Record, VoiceResponse response = VoiceResponse() response.record(transcribe=True, transcribe_callback='/handle_transcribe.php') print(response)
from twilio.twiml.voice_response import Record, VoiceResponse response = VoiceResponse() response.record() print(response)
from twilio.twiml.voice_response import Record, VoiceResponse response = VoiceResponse() response.record(timeout=10, transcribe=True) print(response)