def send_mfa_code_phone(request, code): template = get_template('simplemfa/auth_voice.html') context = get_message_context(request, code) msg = str(template.render(context)) + "," client = get_twilio_client() if hasattr(settings, "MFA_USER_PHONE_ATTRIBUTE") and client is not None: phone_object_string = f"request.user.{settings.MFA_USER_PHONE_ATTRIBUTE}" try: recipient = eval(phone_object_string) code_list = [str(i) for i in str(code)] if recipient is not None: recipient = parse_phone(recipient) response = VoiceResponse() say = Say() say.p(f",,,,,,,,,{msg},,,,,,,,,...") for char in code_list: say.say_as(f",,,,,,,,...{str(char)},,,,,,,,...", interpret_as="spell-out") say.p(f",,,,,,,,,...Again, {msg},,,,,,,,,") for char in code_list: say.say_as(f",,,,,,,,...{str(char)},,,,,,,,...", interpret_as="spell-out") say.p(",,,,,,Goodbye!") response.append(say) print(response.to_xml()) client.calls.create(to=recipient, from_=settings.TWILIO_NUMBER, twiml=str(response.to_xml())) return True except: return False return False
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 в конце перевожу в строку, потому что так было в примерчике
def conference_call(request): response = VoiceResponse() room_name = request.POST['roomName'] dial = Dial() dial.conference(room_name) response.append(dial) return HttpResponse(response.to_xml(), content_type='text/xml')
def send(self, text, contact): if 'phone' not in contact: return { 'success': False, 'message': "User dose not have a phone number" } try: twiml_response = VoiceResponse() twiml_response.say(text) twiml_response.hangup() twiml_xml = twiml_response.to_xml() call = self.client.calls.create(to=contact['phone'], twiml=twiml_xml, from_=self.from_phone) except TwilioRestException as e: return { 'success': False, 'message': "Error calling Twilio: {}".format(e.msg) } return { 'success': True, 'contact': contact['phone'], 'call_id': call.sid }
def getVoiceMessage(uid): # fill in with info from appointmentID cursor = db.appointment.find_one({'_id': ObjectId(uid)}) doctorUID = cursor["doctorUid"] sTime = cursor["timeframe"] # number from 0 to 24, increments of .5 startTime = datetime.fromtimestamp(int(sTime), ) convertedTime = startTime.hour - 4 + startTime.minute / 60 date = startTime.strftime("%B %d") patientID = cursor["userId"] cursor2 = db.user.find_one({"_id": ObjectId(patientID)}) patientFName = cursor2[ 'firstName'] # first and last names may (should?) be combined into one string patientLName = cursor2["lastName"] doctor = betterdoctor.getDoctor("975eb48667ccb9eb20008d302685981d", doctorUID) doctorName = doctor["data"]["profile"]["last_name"] message = (patientFName + " " + patientLName + " has an appointment with doctor" + doctorName + " from " + stringTime(convertedTime) + " to " + stringTime(convertedTime + .5) + "on " + date) response = VoiceResponse() response.say(message) response.hangup() xml = response.to_xml() return xml
def example(): """ Some example usage of different twilio resources. """ client = Client(ACCOUNT_SID, AUTH_TOKEN) # Get all messages all_messages = client.messages.list() print('There are {} messages in your account.'.format(len(all_messages))) # Get only last 10 messages... some_messages = client.messages.list(limit=10) print('Here are the last 10 messages in your account:') for m in some_messages: print(m) # Get messages in smaller pages... all_messages = client.messages.list(page_size=10) print('There are {} messages in your account.'.format(len(all_messages))) print('Sending a message...') new_message = client.messages.create(to='XXXX', from_='YYYY', body='Twilio rocks!') print('Making a call...') new_call = client.calls.create(to='XXXX', from_='YYYY', method='GET') print('Serving TwiML') twiml_response = VoiceResponse() twiml_response.say('Hello!') twiml_response.hangup() twiml_xml = twiml_response.to_xml() print('Generated twiml: {}'.format(twiml_xml))
def collect_2gathers_response(text, hints, phone, sufix='', add_step=True, timeout='auto'): """ функция собирает TwiML с gather для получения ответа на вопрос заданый в параметре text. stage увеличивается если ответ удовлетворительный и разговор движется к следующему вопросу. Params: text ==> (str) вопрос на который мы хотим получить ответ. hints ==> (str) подсказки для лучшего распознавания ответа на вопрос text sufix ==> (str) '' или '_1' для перехода к побочной ветке диалога add_step ==> (bool) если True диалог движется к следующему вопросу """ global out if add_step: out['stage'][out['phone'] == phone] = 1 + out['stage'][out['phone'] == phone][0] twiml_response = VoiceResponse() twiml_response.append( collect_speech_gather(text, hints, phone, sufix, timeout)) twiml_response.append( collect_speech_gather(phrases.cld_u_rpt, hints, phone, sufix, timeout)) twiml_response.say(phrases.ddnt_rcv_inp) return twiml_response.to_xml()
def collect_keybrd_response(text, phone): """ """ response = VoiceResponse() response.append(collect_dgt_gather(text=text, phone=phone, sufix='_1')) response.say(phrases.ddnt_rcv_inp) return response.to_xml()
def outboundRepeat(sufix=''): global step, ngrok_url response = VoiceResponse() gather = Gather(action=ngrok_url + str(step) + sufix, input='speech', speechTimeout='auto') gather.say('could you repeat your answer, please') response.append(gather) response.say('We didn\'t receive any input. Goodbye!') return response.to_xml()
def lambda_handler(event, context): logger.info("EVENTS: %s", event) logger.info("ENVIRONMENT VARIABLES: %s", os.environ) response = VoiceResponse() response.say( f"Thanks for calling {COMPANY_NAME}. Please wait while I am connecting.", voice="woman", language="en-US") response.dial(PHONE_NUMBER, action=f"/{ENV}/dial-call-status", timeout=11) return response.to_xml()
def collect_redirect_speech(phone): """ """ response = VoiceResponse() response.say( 'Hi, I am phoning you again to talk about your car. Last time we stoped on ' + subjects_of_stages[out['stage'][out.phone == phone][0] - 1]) response.redirect(qwe_url + str(out['stage'][out.phone == phone][0])) return response.to_xml()
def collect_end_conversation(text): """ функция собирает TwiML в котором бот проговаривает text и ложет трубку. Params: text ==> (str) текст-прощание с абонентом. """ twiml_response = VoiceResponse() twiml_response.say(text) twiml_response.pause() twiml_response.hangup() return twiml_response.to_xml()
def outbound2(): strr = request.form.get('SpeechResult') #работа с вебом print(strr) 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 twiml_xml = twiml_response.to_xml( ) #twiML обязательный перевод в xml поскольку твилио это чистый xml return str( twiml_xml ) #twiML в конце перевожу в строку, потому что так было в примерчике
def outboundP(text, hints, sufix='', add_step=True): global step, ngrok_url if add_step: step += 1 twiml_response = VoiceResponse() gather = Gather(action=ngrok_url + str(step) + sufix, input='speech', speechTimeout='auto', hints=hints) gather.say(text) twiml_response.append(gather) twiml_response.say('We didn\'t receive any input. Goodbye!') return twiml_response.to_xml()
def TwiMLResponse(texto): #voices = ['man', 'woman', 'alice'] voices = ['alice'] selectedvoice = random.choice(voices) if selectedvoice == 'alice': lang = 'es-MX' else: lang = 'es' tr = VoiceResponse() tr.pause(length=1) tr.say(message=texto, voice=selectedvoice, loop=1, language=lang) tr.hangup() return tr.to_xml()
def receber(): query = "SELECT id,url,materia,assunto FROM aulas ORDER BY id DESC LIMIT 1" 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=' + str(linhas[0]['id'])) response = response.to_xml() return response, 200, {'Content-Type': 'text/xml; charset=utf-8'} return 'error'
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'
def send_data_to_client(self, lex_response): self.logger.info("sending data to client {0}".format(lex_response)) response = VoiceResponse() response.say(lex_response.get("Message")) dialog_state = lex_response.get("DialogState") intent_name = lex_response.get("IntentName") if intent_name is not None and intent_name == "GoodbyeIntent" and dialog_state == "Fulfilled": # hang up the call after this response.hangup() else: response.pause(40) self.logger.info("response is {0}".format(response)) self.twilio_call.persist(response.to_xml()) self.twilio_call.update()
def lambda_handler(event, context): logger.info("EVENTS: %s", event) response = VoiceResponse() status = event.get("DialCallStatus") or "completed" if status in ["busy", "no-answer"]: response.say( "Sorry, our team could not answer your call. Please stay on the line to leave a message.", voice="woman", language="en-US", ) response.record(timeout=10, transcribe=True, max_length=300) email = Email(context_data=event) email_response = email.send() logger.info("EMAIL RESPONSE: %s", email_response) return response.to_xml()
from twilio.twiml.voice_response import Gather, VoiceResponse, Say response = VoiceResponse() gather = Gather(input='speech dtmf', timeout=3, num_digits=1) gather.say('Premi 1 per anar a on vulgui', voice='woman', language='ca-ES') response.append(gather) print(response) file = open('prueba1.xml', 'w') file.write(response.to_xml()) file.close()
def outboundN(text): twiml_response = VoiceResponse() twiml_response.say(text) # twiML текст2спич twiml_response.hangup() return twiml_response.to_xml()
response.append(gather) gather = Gather(action='https://71dd78c8.ngrok.io/outbound1', input='speech', speechTimeout=2) #twiML текст2спич gather.say('could you reapeat your answer, please') #twiML добавить гезер в респонс response.append(gather) #twiML текст2спич response.say('We didn\'t receive any input. Goodbye!') # twiML обязательный перевод в xml поскольку твилио это чистый xml twiml_xml = response.to_xml() # инициализировать звонок используя начало url и twiML переделаный в url адресс call = client.calls.create( url=echo_ur + urlencode({'Twiml': twiml_xml}), to='+380959293096', from_='+14302058972') """ https://www.twilio.com/docs/voice/tutorials/ivr-phone-tree-python-flask https://www.twilio.com/docs/voice/twiml/record?code-sample=code-transcribe-a-recording&code-language=Python&code-sdk-version=6.x