Пример #1
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)
Пример #2
0
    def call(self, messages: list):
        """ Make a call with a TTS made from a list of strings

        Args:
            messages (list): A list of strings to say over the phone call

        Returns:
            twilio.calls.Call: Information about the call made
        """
        number_of_calls = len(messages)
        # Just as a saftey measure - don't make a call if there aren't any messages
        if number_of_calls < 1:
            return None
        logging.info(f'Making a call with {number_of_calls} messages')
        response = VoiceResponse()
        # Wait for one second for better understanding
        response.pause(length=1)
        for message in messages:
            response.say(message)
            response.pause(length=1)
        response.say('That will be all, bye bye!')
        # If the config states that this is a debug mode, only print the content of the TTS input
        logging.debug(response)
        if self.debug_mode:
            return None
        else:
            return self.twilio.calls.create(twiml=response, to=self.receiver, from_=self.caller)
Пример #3
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)
Пример #4
0
def live():
    twiml = VoiceResponse()

    speech_result = request.values.get("SpeechResult", None).lower()
    print('SpeechResult:' + speech_result)
    if any(c in speech_result for c in endcallarr):

        twiml.say("ok i will end the call now",
                  voice="Polly.Raveena",
                  language="en-IN")
        twiml.redirect('/hangup')
    elif 'return' in speech_result:
        twiml.say("ok", voice="Polly.Raveena", language="en-IN", rate='75%')
        twiml.redirect('/incoming')

    twiml.pause(length=1)
    ai = requests.get(
        'http://api.brainshop.ai/get?bid=154407&key=EH62f6jeFRu7e6RO&uid=2&msg='
        + speech_result)
    data = ai.json()['cnt']
    print(data)
    twiml.say(
        data,
        voice="Polly.Aditi",
        language="en-IN",
    )

    twiml.redirect('/chat')
    #twiml.say('You Said' + speech_result, voice="Polly.Aditi", language="en-IN")
    return str(twiml)
Пример #5
0
    def _build_twilio_voice_response(
            self, messages: List[Dict[Text, Any]]) -> VoiceResponse:
        """Builds the Twilio Voice Response object."""
        voice_response = VoiceResponse()
        gather = Gather(
            input="speech",
            action=f"/webhooks/{self.name()}/webhook",
            actionOnEmptyResult=True,
            speechTimeout=self.speech_timeout,
            speechModel=self.speech_model,
            enhanced=self.enhanced,
        )

        # Add pauses between messages.
        # Add a listener to the last message to listen for user response.
        for i, message in enumerate(messages):
            msg_text = message["text"]
            if i + 1 == len(messages):
                gather.say(msg_text, voice=self.assistant_voice)
                voice_response.append(gather)
            else:
                voice_response.say(msg_text, voice=self.assistant_voice)
                voice_response.pause(length=1)

        return voice_response
Пример #6
0
    def on_post(self, req, resp):
        """
        Echo gather instruction in TwiML:

        Example:
            Query strings:

            content: Your alert has been fired.
            instruction: Press 1 to claim alert.
            message_id: 123


            TwiML:

            <?xml version="1.0" ?>
            <Response>
                <Pause length="2"/>
                <Say language="en-US" voice="alice">Press pound for menu.</Say>
                <Gather timeout="0" finishOnKey="#">
                    <Say language="en-US" voice="alice">Your alert has been fired.</Say>
                </Gather>
                <Gather action="http://$endpoint_domain/iris/api/v0/twilio/calls/relay?message_id=123" numDigits="1">
                    <Say language="en-US" voice="alice">Press 1 to claim alert.</Say>
                </Gather>
            </Response>
        """
        content = req.get_param('content', required=True)
        instruction = req.get_param('instruction', required=True)
        message_id = req.get_param('message_id', required=True)
        loop = req.get_param('loop')

        if not message_id.isdigit() and not uuid4hex.match(message_id):
            raise falcon.HTTPBadRequest('Bad message id',
                                        'message id must be int/hex')

        action = self.get_api_url(req.env, 'v0',
                                  'twilio/calls/relay?') + urlencode({
                                      'message_id':
                                      message_id,
                                  })

        r = VoiceResponse()
        if req.get_param('AnsweredBy') == 'machine':
            logger.info("Voice mail detected for message id: %s", message_id)
            r.say(content, voice='alice', language="en-US", loop=loop)
        else:
            r.pause(length=2)
            r.say('Press pound for menu.', voice='alice', language="en-US")

            with r.gather(timeout=0, finishOnKey="#") as g:
                g.say(content, voice='alice', language="en-US")

            with r.gather(numDigits=1, action=action) as g:
                g.say(instruction, voice='alice', loop=loop, language="en-US")

        resp.status = falcon.HTTP_200
        resp.body = str(r)
        resp.content_type = 'application/xml'
Пример #7
0
def pause():

    session['wavUrl'] = request.form['RecordingUrl']
    session['callSid'] = request.form['CallSid']

    resp = VoiceResponse()
    resp.pause(length=30)
    resp.redirect('/record', method='POST')
    return str(resp)
Пример #8
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)
Пример #9
0
def phone_buzz():
    response = VoiceResponse()
    gather = Gather(action='/process_gather')
    response.say("Welcome to Phone Buzz", voice='alice')
    response.pause(1)
    gather.say("Please Enter a number and press pound to submit",
               voice='alice')
    response.append(gather)
    response.redirect('/voice')
    return str(response)
Пример #10
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)
Пример #11
0
def handle_incoming_call():
    print('call received')
    response = VoiceResponse()
    response.say("Hi, I can't come to the phone right now, please leave a message after the beep")
    response.pause(length=3)

    response.record(
        recording_status_callback='/recording_status_callback',
        recording_status_callback_event='completed')

    response.hangup()
    return str(response)
Пример #12
0
def voice():
    #Respond to incoming phone calls with a brief message.
    # Start TwiML response
    resp = VoiceResponse()

    # Read a message aloud to the caller
    message = "Welcome to the Fortune teller line, Here is your fortune."
    resp.say(message, voice='alice')
    resp.pause(length=1)
    message2 = get_fortune() + ".  Thank you, have a great day!"
    resp.say(message2, voice='alice')
    return str(resp)
Пример #13
0
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()
Пример #14
0
def make_call(message, _to, _from):
    account_sid = twilio_cred['account_sid']
    auth_token = twilio_cred['auth_token']
    response = VoiceResponse()
    response.pause(length=10)
    response.say(message, voice='woman', language='es')
    client = Client(account_sid, auth_token)
    call = client.calls.create(
        twiml=response,
        to=_to,
        from_=_from,
        timeout=120,
    )
Пример #15
0
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()
Пример #16
0
def amazon_voice_request():
    pin = request.values["AmazonPinCode"]
    topic = request.values["Topic"]
    word = request.args.get("word")
    speech_result = request.form.get("SpeechResult")

    response = VoiceResponse()

    if word:
        if speech_result:
            if word.lower() in filter(
                    None, re.split(r"[^a-z']", speech_result.lower())):
                response.say(
                    f"Correct! Please press the button that says Ready for Step {'3' if topic == 'none' else '4'}."
                )
                response.redirect(
                    url_for("amazon_voice_request_pin",
                            AmazonPinCode=pin,
                            Topic=topic))
                return twiml_response(response)
            else:
                response.say("Incorrect word. Try again.")
        else:
            response.say(
                "Incorrect. Are you sure that your microphone is working? Try again."
            )
    else:
        word = random.choice(GATHER_WORDS)
        response.say(f"Step {'2' if topic == 'none' else '3'}!")
        response.pause(1)

    response.say(f"Your word is {word}.")

    gather = response.gather(
        action_on_empty_result=True,
        action=url_for("amazon_voice_request",
                       AmazonPinCode=pin,
                       Topic=topic,
                       word=word),
        hints=", ".join(GATHER_WORDS),
        input="speech",
        speech_model="numbers_and_commands",
        speech_timeout="auto",
        timeout=4,
    )
    gather.say(f"After the tone, please say the word {word}.")
    gather.play(audio_url(AUDIO_BEEP))

    return twiml_response(response)
Пример #17
0
def voice(request):
    resp = VoiceResponse()

    resp.say("Connecting you to a safeguarding lead...", **VOICE_ARGS)
    resp.pause()

    for number in NUMBERS.values():
        resp.say("Please hold.", **VOICE_ARGS)
        resp.dial(number)

    resp.say("Couldn't connect you to a member of our safeguarding team.",
             **VOICE_ARGS)
    resp.say("Please try again soon.", **VOICE_ARGS)

    return str(resp)
Пример #18
0
def amazon_voice_request_pin():
    pin = request.args["AmazonPinCode"]
    topic = request.values["Topic"]

    response = VoiceResponse()
    if not request.args.get("said_step_four"):
        response.say(f"Step {'3' if topic == 'none' else '4'}!")

    response.say(f'Your pin is {", ".join(pin)}.')
    response.pause(2)
    response.redirect(
        url_for("amazon_voice_request_pin",
                AmazonPinCode=pin,
                Topic=topic,
                said_step_four="1"))
    return twiml_response(response)
Пример #19
0
    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()
Пример #20
0
def record():
    r = VoiceResponse()
    r.say(
        "Welcome to the Hell Site Hotline! Leave your message after the beep and hangup when done!"
    )
    r.pause()
    r.say("beep")

    r.record(playBeep=False,
             recordingStatusCallbackEvent='completed',
             recordingStatusCallback=ngrokaddress + '/recording',
             method='GET',
             trim='do-not-trim',
             timeout=0)

    r.hangup()

    return str(r)
Пример #21
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
Пример #22
0
async def call():
    form_data = await request.form
    call_sid = form_data['CallSid']

    # The file we want the final .wav file to be saved to.
    output_file = '{}/{}.wav'.format(UPLOAD_FOLDER, call_sid)

    # Spin up an async task to generate the music.
    # After this task is completed, the phone call will be updated.
    # asyncio.get_running_loop().run_in_executor(None, generate_nes_music(call_sid, output_file))
    asyncio.ensure_future(generate_nes_music(call_sid, output_file))

    resp = VoiceResponse()
    resp.pause()
    resp.say('Please wait while we generate some new Nintendo music for you.')

    # Wait until we asynchronously update the call after music is generated.
    resp.pause(length=100)

    return str(resp)
Пример #23
0
def gather():
    resp = VoiceResponse()
    # If digits were included
    if 'Digits' in request.values:
        choice = request.values['Digits']
        # If correct code
        if choice == '965312':
            resp.say('Identification code for Manager Mark. The flag is.')
            resp.pause(length=1)
            resp.say(
                'C.T.F. Curly brace. D.T.M.F. underscore. I. s. underscore. A.w.e.s.o.m.e. Curly brace.'
            )
            resp.pause(length=2)
            resp.say(
                'That is. C.T.F Curly brace. D.T.M.F. underscore. I.s. underscore. A.w.e.s.o.m.e. Curly brace.'
            )
            resp.pause(length=1)
            resp.say('Goodbye.')
            return str(resp)
        else:
            resp.say('Incorrect identification code. Goodbye!')
            return str(resp)
    # No digits
    resp.redirect('/voice')
    return str(resp)
Пример #24
0
def welcome():
    response = VoiceResponse()
    print(str(session.items()))
    if session.get('welcome') is None:
        # Set Session Variables
        caller = request.form.get('Caller')
        call_sid = request.form.get('CallSid')
        session['caller'] = caller
        session['call_sid'] = call_sid
        session['welcome'] = False
        session['loops'] = 0

        # Greet Caller
        response.say('Welcome! What would you like to talk about today?')
        response.record(max_length=15,
                        recording_status_callback_event="completed",
                        recording_status_callback=url_for('process_recording'),
                        play_beep=False)
        session['welcome'] = True

        # add callsid to redis set so we know that the welcome is complete
        # but we don't have anything to say back to the caller yet
        red.sadd("waiting", call_sid)
    elif red.sismember("waiting", session['call_sid']):
        # there's probably a better way to do this rather than the call looping
        print("Waiting for Assembly AI to return text")
        response.pause(1)
        response.redirect(url_for('welcome'))
    else:
        # there is something to say to the caller
        # fetch it from redis and <Say> it
        text = red.get(session['call_sid']).decode("utf-8")
        response.say(text)
        response.hangup()

    session['loops'] = session.get('loops') + 1
    print(f"LOOPS: {session['loops']}")
    return str(response)
Пример #25
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)
Пример #26
0
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(
        "Hola. Bienvenido al servicio de intercambio de informacion de Pedacito de La Tierra. Por favor, no nos de su nombre ni ninguna informacion confidencial en su historia y al utilizar este servicio, acepta que lo que comparte se haga publico. Despues del pitido, espere unos segundos y luego podra comenzar a grabar. Puede colgar una vez que haya terminado. Gracias por tu tiempo.",
        language='es-MX')
    response.pause(length=3)
    response.say(
        "Hello. Welcome to Pedacito de La Tierra information sharing service. Please do not give us your name or any confidential information in your story and by using this service you agree to have what you share made public. After the beep, wait for a few seconds then you can start recording. You can Hang up once you are done. Thank you for your time"
    )

    # Use <Record> to record the caller's message
    response.record(
        action=
        "https://handler.twilio.com/twiml/EH5d4dd437b6a62a4a4413954e680a282a",
        timeout=7,
        transcribe=True)

    response.say(
        "Thank you for being a part of our community and sharing your story, your light and motivating and inspiring others. We hope you are well and if you need assistance with anything, feel free to call us on 1 800 875 7060. Have a good day."
    )

    # End the call with <Hangup>
    response.hangup()

    print("Updating Latest Recording")

    recordURL = accessAPI.downloadRecording()
    # recordText = transcribeCall.transcribeRecording(audioFile)
    recordText = "No Transciption Available Yet"
    saveToFirebase.pushRecording(recordURL, recordText)

    print("Recording Updated")
    return str(response)
Пример #27
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")
Пример #28
0
def inbound_call():
    #response = twiml.Response()
    response = VoiceResponse()
    #Once the call is received, respond with the below message to the caller
    response.say(u'曾經年少愛追夢', voice="alice", language='zh-TW')
    response.pause(length=0.5)
    response.say(u'一心只想往前飛', voice="alice", language='zh-TW')
    response.pause(length=0.5)
    response.say(u'行遍千山和萬水', voice="alice", language='zh-TW')
    response.pause(length=0.5)
    response.say(u'一路走來不能回', voice="alice", language='zh-TW')
    #response.say("Thanks for being a loyal member of South Bay Taiwanese People Meetup. President Charles appreicates your particiaption. Have a nice day. Bond. James Bond.", voice="man")
    return Response(str(response), 200, mimetype="application/xml")
Пример #29
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)
Пример #30
0
def joke():

    speech_result = request.values.get("SpeechResult", None).lower()
    print('SpeechResult:' + speech_result)
    twiml = VoiceResponse()
    if 'hindi' in speech_result:
        s = random.randint(0, len(loop) - 1)
        joke = data = response.json()['result'][s]['joke']
        twiml.say(joke, voice="Polly.Aditi", language="hi-IN")
        twiml.say('चुटकुले ख़तम',
                  voice="Polly.Aditi",
                  language="hi-IN",
                  rate='90%')
        print(joke)
        print(sms_reply.z)

    elif 'english' in speech_result:
        j = Jokes()
        joke = j.get_joke()
        if joke["type"] == "single":
            twiml.pause(length=1)
            twiml.say(joke["joke"],
                      voice="Polly.Aditi",
                      language="en-IN",
                      rate='95%')  # Print the joke
            print(joke["joke"])
        else:
            twiml.pause(length=1)
            twiml.say(joke["setup"],
                      voice="Polly.Aditi",
                      language="en-IN",
                      rate='85%')
            twiml.pause(length=1)
            twiml.say(joke["delivery"],
                      voice="Polly.Aditi",
                      language="en-IN",
                      rate='85%')
            print(joke["setup"])
            print(joke["delivery"])

    twiml.redirect('/incoming')

    #twiml.say('You Said' + speech_result, voice="Polly.Aditi", language="en-IN")
    return str(twiml)
Пример #31
0
from twilio.twiml.voice_response import Pause, VoiceResponse, Say

response = VoiceResponse()
response.pause(length=5)
response.say('Hi there.')

print(response)
Пример #32
0
from twilio.twiml.voice_response import Pause, VoiceResponse, Say

response = VoiceResponse()
response.say('I will pause 10 seconds starting now!')
response.pause(length=10)
response.say('I just paused 10 seconds')

print(response)