Exemplo n.º 1
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,
           hangupOnStar=hangup_on_star,
           timeLimit=time_limit,
           callerId=caller_id)
    return r
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
def route_hotline_forward1(api_version, language, call_id):

    resp = VoiceResponse()

    if language not in ["de", "en-gb"]:
        resp.redirect('/v1/hotline/error/language')
        return str(resp)

    if api_version == "v1":
        forward_helper_query_result = forwarding.find_forward_helper(call_id)

        if forward_helper_query_result["status"] == "ok":
            resp.say(hotline_translation['forward_successful'][language],
                     voice='woman',
                     language=language)

            phone_number = forward_helper_query_result["phone_number"]
            helper_id = forward_helper_query_result['helper_id']
            resp.dial(
                phone_number,
                action=
                f"/{api_version}/hotline/{language}/forward2/{call_id}/{helper_id}",
                timeout=15)

        else:
            resp.say(hotline_translation['forward_not_successful'][language],
                     voice='woman',
                     language=language)
            enqueue.enqueue(call_id)

    else:
        resp.redirect('/v1/hotline/error/api_version')

    return str(resp)
Exemplo n.º 4
0
def getResponseUber():
    print request.form
    #print("POSTED TO GET RESPONSE")
    print("User Said: " + request.form['SpeechResult'])
    try:
        if CALL_LOGS[ALL_INFO[-1]['CallSid']] != request.form['SpeechResult']:
            CALL_LOGS[ALL_INFO[-1]['CallSid']].append(
                request.form['SpeechResult'])
    except:
        pass
    resp = VoiceResponse()
    #print("DONE WITH RESP")
    question = ""
    print('Saying: "Alexa, book an uber {}" to the Alexa Emulator'.format(
        request.form['SpeechResult']))
    question += "ask book an uber " + request.form['SpeechResult'].replace(
        "Global", "").replace("global", "")
    question = ' '.join(re.findall("\w+", str(question)))
    a = requests.post("http://127.0.0.1:8001/interact",
                      data={"question": question})
    print("D8ONE WITH A: {}".format(a))
    interaction = a.json()['response']
    print(interaction)
    print("ask book an uber " + question + "!!!!!!!!!")
    resp.say(interaction[0]['answer'])
    CALL_LOGS[ALL_INFO[-1]['CallSid']].append(interaction[0]['answer'])
    print CALL_LOGS[ALL_INFO[-1]['CallSid']]
    if 'Your driver' in interaction[0]['answer']:
        ite = str(CALL_LOGS[ALL_INFO[-1]['CallSid']][-3]).partition(
            "from ")[2].partition(", is that")[0].replace("bring you to ",
                                                          "").replace(
                                                              ", USA", "")
        fromVal, toVal = ite.split(" to ")
        lat1, lng1 = get_address(fromVal)
        lat2, lng2 = get_address(toVal)
        print("http://127.0.0.1:8011/options?lat1={}&lng1={}&lat2={}&lng2={}".
              format(lat1, lng1, lat2, lng2))
        res = requests.get(
            "http://127.0.0.1:8011/options?lat1={}&lng1={}&lat2={}&lng2={}".
            format(lat1, lng1, lat2, lng2))
        g = res.json()['prices'][0]
        price = g['low_estimate'] + round(random.uniform(1.1, 1.9), 2)
        newTimeVal = datetime.datetime.now() + datetime.timedelta(
            minutes=random.randint(1, 10) + (g['duration'] / 60))
        newTimeVal = newTimeVal.strftime('%I:%M %p')
        send_message(
            request.form.get("From"),
            """Thank you for using RideCaring!  Your {} mile trip from {} will cost ${}.  Your {} driver will arrive by {}."""
            .format(g['distance'], ite, price, g['display_name'], newTimeVal))
        send_message(
            request.form.get("From"),
            "To cancel this trip respond with the word: 'cancel' or call us at (888) 250-4319"
        )
    print(resp)
    if 'absolutely' in str(interaction).lower():
        resp.dial('864-567-4106')
    if 'absolutely' not in str(interaction).lower():
        #print("HOPEFULLY THIS IS STILL WORKING")
        resp.redirect('/anyThingElseUber', method='POST')
    return str(resp)
Exemplo n.º 5
0
def init_automated_call(request):
    """ initial end point called by twilio on making a phone call to your twilio number"""
    response = VoiceResponse()
    response.dial()

    # HttResponse will return xml response object for twilio api to process
    return HttpResponse(str(response), content_type='application/xml')
Exemplo n.º 6
0
def get_cur():
    global index, choice
    response = VoiceResponse()
    n = current
    if n["option"] == "speak":
        response.say(message=n["message"])
    elif n["option"] == "directory":
        response.say(message="Directory: ")
        for key, value in n.items():
            if key != "option":
                response.say(message=key + " at " + value)
    elif n["option"] == "end":
        response.hangup()
    elif n["option"] == "redirect":
        response.dial(n['redirect'])
    elif n["option"] == "choice":
        choice = True
        choices = n['choices']
        with response.gather(numDigits=1, action="/gather") as gather:
            for i in range(len(choices)):
                gather.say(message="Press" + str(i) + " to " + choices[i])
        response.redirect("/cur")

    response.redirect('/next')
    return str(response)
Exemplo n.º 7
0
def voice():
    """Respond to incoming requests."""
    resp = VoiceResponse()
    resp.say("Hello.  Thank you for calling Chuck Underwood. It will be just a moment while you are connected.")
    resp.dial("+15416391136")

    return str(resp)
Exemplo n.º 8
0
def _call_redirect():
    response = VoiceResponse()

    response.say("Redirecting to our agent. Please hold.")
    response.dial(SMS_DESTINATION)

    return twiml(response)
Exemplo n.º 9
0
def join_conference(request, conference_name):
    """
    If request comes in join coinference
    """
    resp = VoiceResponse()
    resp.dial(hangupOnStar=True).conference(conference_name)
    return HttpResponse(str(resp))
def call(forward_to_number):
    """Respond to incoming phone calls with a message."""
    # Start our TwiML response / forward call
    resp = VoiceResponse()
    resp.dial(forward_to_number)

    return str(resp)
Exemplo n.º 11
0
def getResponseNCR():
    print request.form
    print("POSTED TO GET RESPONSE")
    print("User Said: " + request.form['SpeechResult'])
    try:
        if CALL_LOGS[ALL_INFO[-1]['CallSid']] != request.form['SpeechResult']:
            CALL_LOGS[ALL_INFO[-1]['CallSid']].append(
                request.form['SpeechResult'])
    except:
        pass
    resp = VoiceResponse()
    print("DONE WITH RESP")
    question = ""
    if 'global' not in request.form['SpeechResult'].lower():
        print('Saying: "Alexa, Ask NCR store {}" to the Alexa Emulator'.format(
            request.form['SpeechResult']))
        question += "ask ncr store "
    else:
        print('Saying: "Alexa, {}" to the Alexa Emulator'.format(
            request.form['SpeechResult']))
    question += request.form['SpeechResult'].replace("Global",
                                                     "").replace("global", "")
    a = requests.post("http://127.0.0.1:8001/interact",
                      data={"question": question})
    print("DONE WITH A: {}".format(a))
    interaction = a.json()['response']
    resp.say(interaction[0]['answer'])
    CALL_LOGS[ALL_INFO[-1]['CallSid']].append(interaction[0]['answer'])
    print(resp)
    if 'absolutely' in str(interaction).lower():
        resp.dial('864-567-4106')
    if 'absolutely' not in str(interaction).lower():
        print("REDIRECTING TO ANYTHIGN ELSE")
        resp.redirect('/anyThingElse', method='POST')
    return str(resp)
Exemplo n.º 12
0
def outbound():
    response = VoiceResponse()
    response.say(
        'This call is in regards to your callback request. Please hold while we transfer your call to an agent',
        voice='alice')
    response.dial('+13026606019')
    response.redirect('/process_close')
    return str(response)
Exemplo n.º 13
0
def voice():
    """Respond to incoming phone calls with a 'Hello world' message"""
    resp = VoiceResponse()

    resp.dial(to_number)
    resp.say('Bye-bye')
    print(resp)
    return ('', 204)
Exemplo n.º 14
0
def forward():
    if os.environ.get('FLASK_ENV') != 'development':
        if not validate_request():
            logging.info('Request failed validation')
            return abort(400)
    resp = VoiceResponse()
    resp.dial(os.environ['PHONE_FORWARD_NUMBER'])
    return str(resp)
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)
Exemplo n.º 16
0
def outbound():
    script = "We're connecting you right now."
    dial_to = "+15555555555"

    response = VoiceResponse()
    response.say(script, voice='alice')
    response.dial(dial_to)
    return str(response)
Exemplo n.º 17
0
    def test_dial(self):
        """ should redirect the call """
        r = VoiceResponse()
        r.dial("1231231234")

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Dial>1231231234</Dial></Response>'
        )
Exemplo n.º 18
0
def forward():
    """Forward a buzzer request to a designated phone number"""

    resp = VoiceResponse()

    # Dial the designated phone number
    resp.dial(request.args.get('to'))

    return Response(str(resp), mimetype='text/xml')
Exemplo n.º 19
0
def handle_key():
    """Handle key press from a user."""
    resp = VoiceResponse()
    # Dial (310) 555-1212 - connect that number to the incoming caller.
    resp.dial(available_numbers[-1])
    # If the dial fails:
    resp.say("The call failed, or the remote party hung up. Goodbye.")

    return str(resp)
Exemplo n.º 20
0
def threewaycall():
    """Make a three-way call."""

    print(request.get_data())
    response = VoiceResponse()
    response.say("Connecting, please hold", voice='alice')
    response.dial(PHONE_NUMBER)

    return str(response)
Exemplo n.º 21
0
def forward_call():
    """Forward incoming phone calls to the certain number."""
    forward_to = '+' + request.values.get('forward_to')
    response = VoiceResponse()
    response.dial(forward_to,
                  action=url_for('log_to_googlesheet',
                                 forward_to=forward_to,
                                 spread_sheet=request.values.get('sheet')))
    return Response(str(response), 200, mimetype="application/xml")
Exemplo n.º 22
0
def agent():
    response = VoiceResponse()
    response.say(
        "Thanks for your patience!, You'll be redirected to the next available agent"
    )
    agents = ["+16139810982"]
    available = agents[0]
    response.dial(available)
    return twiml_resp(response)
Exemplo n.º 23
0
def outbound():
    response = VoiceResponse()

    response.say(
        'Now connecting you to LEGO consumer service. An agent will be there shortly',
        voice='Polly.Amy',
        language='en-GB')
    response.dial('+4588915109')
    return str(response)
Exemplo n.º 24
0
def handle_key():

    # Get the digit pressed by the user
    digits_pressed = request.values.get('Digits', None)
    resp = VoiceResponse()
    resp.say("Calling now, player.")
    resp.dial(digits_pressed, callerId=caller_id)

    return str(resp)
Exemplo n.º 25
0
def auto_call():

    # Get Emergency Service for location


    # Dial number (Would be emergency service)
    response = VoiceResponse()
    dial = Dial()
    dial.number('470-705-7212')
    response.append(dial)
    print(response)

    # Get pickup status
    response = VoiceResponse()
    response.dial('415-123-4567', action='/handleDialCallStatus', method='GET')
    response.say('I am unreachable')
    # Twilio will submit a request to the action URL with the parameter 'DialCallStatus'.
    # If nobody picks up, 'DialCallStatus' will be 'no-answer'.
    # If the line is busy, 'DialCallStatus' will be 'busy'.
    # If the called party picks up, 'DialCallStatus' will be 'completed'.
    # If a conference is successfully dialed, 'DialCallStatus' will be 'answered'.
    # If an invalid phone number was provided, 'DialCallStatus' will be 'failed'.

    print(response)

    # Automated Voice Intro = "(person's name)"

    # Get information from Smart911Connect Account
    # http://www.smart911connect.com/get-access/
    # Development Block :(
    # no free APIs that send medical info to Emergency Services, however they all return JSON
    # Use Mongoose, JSON -> DB -> JSON

    # Get information as JSON - Python NamedTuple -> String

    # Feed into IBM Watson
    import json
    from watson_developer_cloud import DialogV1 as Dialog

    dialog = Dialog(username='******', password='******')
    dialog_id = 'YOUR_DIALOGID'
    conversation = dialog.conversation(dialog_id)
    client_id = conversation['client_id']
    print dialog.update_profile(dialog_id=dialog_id, client_id=client_id,
                                name_values={"name_values": [{"name": "Product_Name", "value": "Sunglasses"}]})
    print dialog.update_profile(dialog_id=dialog_id, client_id=client_id,
                                name_values=[{"name": "Product_Name", "value": "Sunglasses"}])


    # Operator Interface with Twilio





    return
Exemplo n.º 26
0
def forward():
    resp = VoiceResponse()
    incoming_number = request.values['From']
    send_message("About to forward a call from " + str(incoming_number))

    resp.say(
        "Please note your call may be recorded for the benefit of both parties"
    )
    resp.dial(forward_number, caller_id=forward_number_from)
    return str(resp)
Exemplo n.º 27
0
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')
Exemplo n.º 28
0
def twilioRedirect():
    callerInfo = request.form.to_dict()
    storeVals = search.store_by_zip(callerInfo['FromZip'])
    callerInfo['closed'] = storeVals[0]['hours'][3]["formattedCloses"]
    CALL_LIST.append(callerInfo)
    print("CLOSEST TMOBILE STORE: {}".format(
        storeVals[0]['location']['address']))
    resp = VoiceResponse()
    resp.dial('801-406-1288')
    return str(resp)
Exemplo n.º 29
0
def makeCall():
    response = VoiceResponse()
    to = request.form.get('to')
    if not to or len(to) == 0:
        response.say(
            "Congratulations! You have just made your first call! Good bye.")
    elif to[0] in "+918905796980":
        response.dial(callerId=CALLER_NUMBER).number(to)
    else:
        response.dial(callerId=CALLER_ID).client(to)
    return str(response)
Exemplo n.º 30
0
def makeCall():
  resp = VoiceResponse()
  to = request.values.get("to")

  if to is None or len(to) == 0:
    resp.say("Congratulations! You have just made your first call! Good bye.")
  elif to[0] in "+1234567890" and (len(to) == 1 or to[1:].isdigit()):
    resp.dial(callerId=CALLER_NUMBER).number(to)
  else:
    resp.dial(callerId=CALLER_ID).client(to)
  return str(resp)
Exemplo n.º 31
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
Exemplo n.º 32
0
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("/")
Exemplo n.º 33
0
def conference(request, number, 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()
    r.dial(number=number).conference(name=name, muted=muted, beep=beep,
                                     startConferenceOnEnter=start_conference_on_enter,
                                     endConferenceOnExit=end_conference_on_exit,
                                     waitUrl=wait_url, waitMethod=wait_method,
                                    )
    return r
Exemplo n.º 34
0
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)
Exemplo n.º 35
0
def call():
    resp = VoiceResponse()
    with resp.dial(callerId=caller_id, record='true') as r:
      r.client('TomPY')
    return str(resp)   
Exemplo n.º 36
0
from twilio.twiml.voice_response import Dial, VoiceResponse, Say

response = VoiceResponse()
response.dial('415-123-4567')
response.say('Goodbye')

print(response)
Exemplo n.º 37
0
from twilio.twiml.voice_response import Dial, VoiceResponse, Say

response = VoiceResponse()
response.dial('415-123-4567', action='/handleDialCallStatus.php', method='GET')
response.say('I am unreachable')

print(response)