Example #1
0
    def post(self, request):
        t = Tropo()
        r = Result(request.body)
        log.debug('PlayCode got: %s', request.body.__repr__())

        session = m.Session.objects.get(identifier=r._sessionId)
        player = session.player

        if r._state == 'DISCONNECTED':
            log.info('player %s disconnected', session.player)
            return HttpResponse(t.RenderJson())
            
        # see if there's a user-entered code
        try:
            code = r.getValue()
        except KeyError:
            t.say("Please try again.")
            code = None

        # if there's a code, try changing the station
        if code:
            try:
                song = m.SongStation.objects.get(select_code=code)
                player.completed_stations.add(song)
                player.current_station = song
                player.save()
            except ObjectDoesNotExist:
                t.say("Sorry, %s is invalid" % code)

        prompt_player(t, player)

        tropo_response = t.RenderJson()
        log.debug('PlayCode returning %s', tropo_response)
        return HttpResponse(tropo_response)
Example #2
0
def license(request):
    r = Result(request.body)
    t = Tropo()

    answer = r.getInterpretation()

    u = current[r._sessionId]
    current[r._sessionId]["last_name"] = answer

    db = MySQLdb.connect(host="localhost", user="******", passwd="globalhack", db="globalhackv")
    cur = db.cursor()

    cur.execute(
        "SELECT first_name, last_name FROM good_data_fixed WHERE date_of_birth = %s AND last_name LIKE %s AND status <> 'CLOSED' AND status <> 'DISMISS WITHOUT COSTS'",
        (u["birthday"], answer),
    )
    result = cur.fetchall()

    cur.close()
    db.close()

    t.say("Hello %s %s," % (result[0][0], result[0][1]))

    choices = Choices("[4 DIGITS]", mode="dtmf", attempts=3)
    t.ask(
        choices,
        timeout=15,
        name="last_drivers",
        say="As a final validation, please enter the last four digits of your driver's license I D",
    )

    t.on(event="continue", next="/results")

    return t.RenderJson()
def index(request):

	r = Result(request.body)        
        print "request.body : %s" % request.body

	t = Tropo()

	answer = r.getInterpretation()
	value = r.getValue()
        
	t.say("You said " + answer + ", which is a " + value)
        
        actions_options_array = ['name', 'attempts', 'disposition', 'confidence', 'interpretation', 'utterance', 'value', 'concept', 'xml', 'uploadStatus']
        actions = r.getActions()
	if (type (actions) is list):
	     for item in actions:
		for opt in actions_options_array:
                    print 'action object filed %(actionfieldname)s\'s value is %(vaalue)s' % {'actionfieldname':opt, "vaalue":item.get(opt,'NoValue')}
                print '------------------------------'
             
       	else:
            dict = actions
	    for opt in actions_options_array:
                print 'action object filed %(actionfieldname)s\'s value is %(vaalue)s' % {'actionfieldname':opt, "vaalue":dict.get(opt,'NoValue')}
        
        json = t.RenderJson()
        print json
	return json
Example #4
0
def talkto(request):
    r = Result(request.body)
    t = Tropo()

    answer = r.getInterpretation()

    if answer == "goodbye":
        t.say("Thank you for calling, have a good day")

        return t.RenderJson()

    t.say("As we currently do not have transfer abilites, here is the phone number: ")

    db = MySQLdb.connect(host="localhost", user="******", passwd="globalhack", db="globalhackv")
    cur = db.cursor()

    cur.execute(
        "SELECT `Court Clerk Phone Number` as `phone` from `munipality` where `Municipality` = UPPER(%s)", (answer,)
    )
    result = cur.fetchone()

    cur.close()
    db.close()

    if result[0] == "":
        t.say("We are sorry, we do not have a phone number for this court.")

        return t.RenderJson()

    t.say(result[0])

    return t.RenderJson()
Example #5
0
def language_select():
    r = Result(request.data)
    s = CallSession(r)

    answer = r.getInterpretation()

    s.set('language', answer)

    return redirect(url_for('phone.hello'))
Example #6
0
    def do_POST(self):
        if "/continue" in self.path:
            content_len = int(self.headers['content-length'])
            post_body = self.rfile.read(content_len)
            print("IN CONTINUE")
            print(post_body)
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            r = Result(post_body.decode('utf-8'))

            t = Tropo()
            answer = r.getValue()

            if int(answer) == 1:
                t.say(
                    "We are now transferring you to a Charlie Hospital phone operator!   Please wait a moment..."
                )

            elif int(answer) == 2:
                t.say(
                    "Please provide your information:  Your name, ID card, hospital department and doctor!!  We will make the appointment for you!"
                )

            else:
                t.say(
                    "We see from your phone number you have an appointment with Dr.Green on Friday May 5th at 2:30PM."
                )

            print("ANSWER " + answer)

            message = t.RenderJson()
            self.wfile.write(bytes(message, "utf8"))
            return

        else:
            content_len = int(self.headers['content-length'])
            post_body = self.rfile.read(content_len)
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            print(post_body)
            s = Session(post_body.decode('utf-8'))
            t = Tropo()
            t.ask(
                choices="1,2,3",
                timeout=60,
                name="digit",
                say=
                "Welcome to Charlie Hospital!!  Please press one to speak to phone operator;   Press two to make a new appointment; Press three to check your appointment"
            )
            t.on(event="continue", next=("/continue"))
            message = t.RenderJson()
            self.wfile.write(bytes(message, "utf8"))
            return
def index(request):

  r = Result(request.body)
  t = Tropo()

  userType = r.getUserType()

  t.say("You are a " + userType)

  return t.RenderJson()
Example #8
0
def index(request):

    r = Result(request.body)
    t = Tropo()

    userType = r.getUserType()

    t.say("You are a " + userType)

    return t.RenderJson()
Example #9
0
def birthday_day(request):
    r = Result(request.body)
    t = Tropo()

    answer = r.getInterpretation()

    current[r._sessionId]["birthday"]["month"] = answer

    choices = Choices("[1-2 DIGITS]", mode="dtmf")
    t.ask(choices, timeout=15, name="birthday_day", say="Please enter your date of birth", attempts=3)

    t.on(event="continue", next="/name")

    return t.RenderJson()
Example #10
0
def discern_intention_to_connect_from_answerer(request, provider):
    '''
    Figures out if an answerer wants to answer a call.
    '''
    intends_to_answer = False #Assume that they don't want to answer unless they affirmatively indicate that they do.
    result = Result(request.raw_post_data)  # TODO: Uncouple from tropo
    try:
        if result._actions['disposition'] == "SUCCESS": #If we've found a match....
            vocal_response = result.getValue() #...then grab that match and see.....
            if vocal_response in ["0","1","2","3","4","5","6","7","8","9",SLASHROOT_EXPRESSIONS['phrase_to_answer_call']]: #....if it matches the phrase we're looking for.
                intends_to_answer = True
    except AttributeError:
        return False
    return intends_to_answer
Example #11
0
def index(request):

    r = Result(request.body)
    print "Result : %s" % r
    #        dump(r)
    t = Tropo()

    answer = r.getInterpretation()

    t.say("You said ")
    t.say(answer, _as="DIGITS")

    json = t.RenderJson()
    print json
    return json
def index(request):

	r = Result(request.body)        
        print "Result : %s" % r
#        dump(r)
	t = Tropo()

	answer = r.getInterpretation()

	t.say("You said ")
	t.say (answer, _as="DIGITS")

        json = t.RenderJson()
        print json
	return json
def index(request):

	r = Result(request.body)        
        print("Result : %s" % r)

	t = Tropo()

	answer = r.getInterpretation()
	value = r.getValue()

	t.say("You said " + answer + ", which is a " + value)

        json = t.RenderJson()
        print(json)
	return json
Example #14
0
def birthday_month(request):
    r = Result(request.body)
    print r._sessionId
    t = Tropo()

    answer = r.getInterpretation()

    current[r._sessionId] = {"birthday": {"year": answer}}

    choices = Choices("[1-2 DIGITS]", mode="dtmf")
    t.ask(choices, timeout=15, name="birthday_month", say="Please enter your month of birth as a number", attempts=3)

    t.on(event="continue", next="/birthday_day")

    return t.RenderJson()
Example #15
0
def index(request):

	r = Result(request.body)        
        print "Result : %s" % r

	t = Tropo()

	answer = r.getInterpretation()
	value = r.getValue()

	t.say("You said " + answer + ", which is a " + value)

        json = t.RenderJson()
        print json
	return json
Example #16
0
def verify_yes(request):
	r = Result(request.body)
	t = Tropo()

	answer = r.getValue()

	t.say("You said " + str(answer))

	if answer == "yes" :
		t.say("Ok, just checkin.")
	else :
		t.say("What are you waiting for?")

	json = t.RenderJson()
	print json
	return HttpResponse(json)
Example #17
0
def name(request):
    r = Result(request.body)
    t = Tropo()

    answer = r.getInterpretation()

    current[r._sessionId]["birthday"]["day"] = answer

    b = current[r._sessionId]["birthday"]

    if len(b["month"]) == 1:
        b["month"] = "0" + b["month"]
    if len(b["day"]) == 1:
        b["day"] = "0" + b["day"]

    formatted_birthday = "%s-%s-%s" % (b["year"], b["month"], b["day"])
    current[r._sessionId]["birthday"] = formatted_birthday

    db = MySQLdb.connect(host="localhost", user="******", passwd="globalhack", db="globalhackv")
    cur = db.cursor()

    cur.execute("SELECT COUNT(*) AS count FROM good_data_fixed WHERE date_of_birth = %s", (formatted_birthday,))
    result = cur.fetchone()

    cur.execute("SELECT last_name FROM good_data_fixed WHERE date_of_birth = %s", (formatted_birthday,))
    people = cur.fetchall()

    cur.close()
    db.close()

    if int(result[0]) == 0:
        t.say("We have found zero results, have a good day!")
        return t.RenderJson()

    choices = []
    for row in people:
        print row[0]
        choices.append(row[0])
    names = ",".join(choices)

    t.ask(choices=names, say="Please say your last name", attempts=3)

    t.on(event="continue", next="/license")

    return t.RenderJson()
Example #18
0
def country_select():
    r = Result(request.data)
    s = CallSession(r)

    answer = r.getInterpretation()

    s.set('country', answer)

    s_language = s.get('language')
    if not s_language:
        countries = data.get_countries()
        for s_country in countries:
            if s_country['name'].lower() == answer.lower():
                s.set('language', s_country['languages'][0]['name'])

    t = Tropo()
    t.on(event='continue', next=url_for('phone.hello'))

    return t.RenderJson()
Example #19
0
def member_question():
    tropo_core = setup_tropo()
    result = TropoResult(request.data)
    session = models.TropoSession.get_session_with_tropo_id(result._sessionId)
    conference = session.conference_call

    selection = int(result.getValue())

    if selection == 1:
        tropo_core.say("Please wait while we join you to the conference")
        tropo_core.conference(id=str(conference.tropo_conference_id), name=str(conference.tropo_conference_id), allowSignals=True, required=True)
        tropo_core.on(event='continue', next=url_for('member_joined'))
    elif selection == 2:
        tropo_core.say("Thank you.  Goodbye.")
        tropo_core.hangup()
    else:
        tropo_core.on(event='continue', next=url_for('member_answered'))

    response = tropo_core.RenderJson(pretty=True)
    return response
Example #20
0
def country():
    r = Result(request.data)
    s = CallSession(r)

    answer = r.getInterpretation()

    countries = data.country_for_code(answer)

    t = Tropo()

    if not countries:
        t.ask(
            choices='[1-3 DIGITS]',
            name='code',
            say=_('Invalid country code, please try again.'),
            timeout=5,
        )
        t.on(event='continue', next=url_for('phone.country'))
    elif len(countries) == 1:
        t.say(_('You selected'))
        t.say(countries[0]['name'])
        s.set('country', countries[0]['name'])

        t.on(event='continue', next=url_for('phone.hello'))
    else:
        country_list = ', '.join(
            list(map(lambda country: country['name'], countries)))

        t.ask(
            choices=country_list,
            name='country',
            say=_('Please select one of the following countries. %s') %
            country_list,
            timeout=5,
        )
        t.on(event='continue', next=url_for('phone.country_select'))

    return t.RenderJson()
Example #21
0
def member_question():
    tropo_core = setup_tropo()
    result = TropoResult(request.data)
    session = models.TropoSession.get_session_with_tropo_id(result._sessionId)
    conference = session.conference_call

    selection = int(result.getValue())

    if selection == 1:
        tropo_core.say("Please wait while we join you to the conference")
        tropo_core.conference(id=str(conference.tropo_conference_id),
                              name=str(conference.tropo_conference_id),
                              allowSignals=True,
                              required=True)
        tropo_core.on(event='continue', next=url_for('member_joined'))
    elif selection == 2:
        tropo_core.say("Thank you.  Goodbye.")
        tropo_core.hangup()
    else:
        tropo_core.on(event='continue', next=url_for('member_answered'))

    response = tropo_core.RenderJson(pretty=True)
    return response
Example #22
0
def index(request):

    r = Result(request.body)
    print "request.body : %s" % request.body

    t = Tropo()

    answer = r.getInterpretation()
    value = r.getValue()

    t.say("You said " + answer + ", which is a " + value)

    actions_options_array = [
        'name', 'attempts', 'disposition', 'confidence', 'interpretation',
        'utterance', 'value', 'concept', 'xml', 'uploadStatus'
    ]
    actions = r.getActions()
    if (type(actions) is list):
        for item in actions:
            for opt in actions_options_array:
                print 'action object filed %(actionfieldname)s\'s value is %(vaalue)s' % {
                    'actionfieldname': opt,
                    "vaalue": item.get(opt, 'NoValue')
                }
            print '------------------------------'

    else:
        dict = actions
        for opt in actions_options_array:
            print 'action object filed %(actionfieldname)s\'s value is %(vaalue)s' % {
                'actionfieldname': opt,
                "vaalue": dict.get(opt, 'NoValue')
            }

    json = t.RenderJson()
    print json
    return json
Example #23
0
    def do_POST(self):
        if "/continue" in self.path:
            content_len = int(self.headers['content-length'])
            post_body = self.rfile.read(content_len)
            print("IN CONTINUE")
            print(post_body)
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            r = Result(post_body.decode('utf-8'))
            t = Tropo()
            answer = r.getValue()
            print("ANSWER " + answer)
            t.say("You chose " + answer)
            t.transfer("+14075550100")
            message = t.RenderJson()
            self.wfile.write(bytes(message, "utf8"))
            return
        else:
            content_len = int(self.headers['content-length'])
            post_body = self.rfile.read(content_len)
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            print(post_body)
            s = Session(post_body.decode('utf-8'))
            t = Tropo()
            t.ask(choices="0,1,2,3,4,5,6,7,8,9",
                  timeout=60,
                  name="digit",
                  say="Pick a number from 0 to 9")
            t.on(event="continue", next=("/continue"))
            message = t.RenderJson()
            self.wfile.write(bytes(message, "utf8"))
            return
Example #24
0
def hello():
    r = Result(request.data)
    s = CallSession(r)

    t = Tropo()

    s_country = s.get('country')
    s_language = s.get('language')

    if s_country:
        t.say('Country set to %s' % s_country)

    if s_language:
        t.say('Language set to %s' % s_language)

    return t.RenderJson()
Example #25
0
def deal_with_links():
    print "dealing with link"
    t = Tropo()
    # Load up everything the stupid way.
    userid = int(request.args['userid'])
    page_n = int(request.args['page'])
    user = User.query.filter_by(userid=userid).first()
    url = im_feeling_lucky(user.voice_query)
    webpage = extract.ParsedWebpage(url)

    # Get the action from last time.
    result = Result(request.data)
    try:
        result.getValue()
    except KeyError:
        t.say("Going to next page.")
        t.on(event='continue', next='/speak_webpage?userid={0}&page={1}'
            .format(userid, page_n + 1))
        return t.RenderJson()

    if result.getValue() == 'link':
        link_num = int(result.getInterpretation())
        print "Link number: ", link_num
        if link_num >= len(webpage.links):
            t.say("Invalid link")
            t.on(event='continue', next='/speak_webpage?userid={0}&page={1}'
                .format(userid, page_n))
            return t.RenderJson()
        t.say("Following link.")
        print "New url: ", webpage.links[link_num][1]
        user.voice_query = webpage.links[link_num][1]
        db.session.commit()
        t.on(event='continue', next='/speak_webpage?userid={0}&page={1}'
            .format(userid, 0))

    elif result.getInterpretation() == 'next':
        t.say("Going to next page.")
        t.on(event='continue', next='/speak_webpage?userid={0}&page={1}'
            .format(userid, page_n + 1))
    elif result.getInterpretation() == 'home':
        t.say("Going home.")
        t.on(event='continue', next='/home')
    else:
        t.say("Unknown command")
        t.on(event='continue', next='/speak_webpage?userid={0}&page={1}'
            .format(userid, page_n))
    return t.RenderJson()
def index(request):

    r = Result(request.body)
    print "request.body : %s" % request.body

    t = Tropo()

    answer = r.getInterpretation()
    value = r.getValue()

    answer1 = r.getNamedActionInterpretation("directory")
    value1 = r.getNamedActionValue("directory")
    t.say("You said " + answer1 + ", which is a " + value1)

    answer2 = r.getNamedActionInterpretation("color")
    value2 = r.getNamedActionValue("color")
    t.say("You also said " + answer2 + ", which is a " + value2)

    count = r.getActionsCount()
    t.say("actions count is  " + str(count))
    for i in range(count):
        answer = r.getIndexdedInterpretation(i)
        value = r.getIndexedValue(i)
        t.say("You said " + answer + ", which is a " + value)

    actions_options_array = [
        'name', 'attempts', 'disposition', 'confidence', 'interpretation',
        'utterance', 'value', 'concept', 'xml', 'uploadStatus'
    ]
    actions = r.getActions()
    if (type(actions) is list):
        for item in actions:
            for opt in actions_options_array:
                print 'action object filed %(actionfieldname)s\'s value is %(vaalue)s' % {
                    'actionfieldname': opt,
                    "vaalue": item.get(opt, 'NoValue')
                }
            print '------------------------------'

    else:
        dict = actions
        for opt in actions_options_array:
            print 'action object filed %(actionfieldname)s\'s value is %(vaalue)s' % {
                'actionfieldname': opt,
                "vaalue": dict.get(opt, 'NoValue')
            }

    json = t.RenderJson()
    print json
    return json
def index(request):

    r = Result(request.body)        
    print "request.body : %s" % request.body

    t = Tropo()

    answer = r.getInterpretation()
    value = r.getValue()
    
    answer1 = r.getNamedActionInterpretation("directory")
    value1 = r.getNamedActionValue("directory")
    t.say("You said " + answer1 + ", which is a " + value1)
    
    answer2 = r.getNamedActionInterpretation("color")
    value2 = r.getNamedActionValue("color")
    t.say("You also said " + answer2 + ", which is a " + value2)
    
    
    count= r.getActionsCount()
    t.say("actions count is  " + str(count))
    for i in range(count):
        answer = r.getIndexdedInterpretation(i)
        value = r.getIndexedValue(i)    
        t.say("You said " + answer + ", which is a " + value)
        
    actions_options_array = ['name', 'attempts', 'disposition', 'confidence', 'interpretation', 'utterance', 'value', 'concept', 'xml', 'uploadStatus']
    actions = r.getActions()
    if (type (actions) is list):
        for item in actions:
            for opt in actions_options_array:
                    print 'action object filed %(actionfieldname)s\'s value is %(vaalue)s' % {'actionfieldname':opt, "vaalue":item.get(opt,'NoValue')}
            print '------------------------------'
             
    else:
        dict = actions
        for opt in actions_options_array:
                print 'action object filed %(actionfieldname)s\'s value is %(vaalue)s' % {'actionfieldname':opt, "vaalue":dict.get(opt,'NoValue')}
        
    json = t.RenderJson()
    print json
    return json
Example #28
0
def results(request):
    r = Result(request.body)
    t = Tropo()

    answer = r.getInterpretation()

    u = current[r._sessionId]

    db = MySQLdb.connect(host="localhost", user="******", passwd="globalhack", db="globalhackv")
    cur = db.cursor()

    cur.execute(
        "SELECT court_date, court_location, violation_description, first_name, last_name, warrant_status, fine_amount, court_cost FROM good_data_fixed WHERE date_of_birth = %s AND last_name LIKE %s AND drivers_license_number LIKE %s AND status <> 'CLOSED' AND status <> 'DISMISS WITHOUT COSTS'",
        (u["birthday"], u["last_name"], "%" + answer),
    )
    result = cur.fetchall()

    cur.close()
    db.close()

    total_cost = 0
    total_fees = 0
    courts = []

    dates = {}
    for row in result:
        if row[0] not in dates:
            d = datetime.strptime(row[0], "%Y-%m-%d")
            nice = d.strftime("%A, %B, %-d, %Y")

            dates[row[0]] = {"date": nice, "location": row[1], "events": []}

        if not row[1] in courts:
            courts.append(row[1])

        dates[row[0]]["events"].append({"fine": row[6], "fee": row[7], "description": row[2], "warrant": row[5]})

        total_cost += float(row[6][1:])
        total_fees += float(row[7][1:])

    for date, info in dates.iteritems():
        t.say("You have a court date on %s. This is for the following violations" % (info["date"]))

        for violation in info["events"]:
            t.say("Violation " + violation["description"])

            if violation["fine"] != "":
                t.say("This includes a %s fine and %s court fee" % (violation["fine"], violation["fee"]))
                extra = "also"

            if violation["warrant"] == "TRUE":
                t.say("This %s includes a warrant for your arrest" % (extra))

    if total_cost > 0:
        t.say(
            "Your total fines are $%.2f and your total fees are $%.2f, bringing the total cost to $%.2f."
            % (total_cost, total_fees, total_cost + total_fees)
        )

    say = (
        "If you would like to talk to a court clerk about this, please say any of the following courts, or say goodbye: %s"
        % (", ".join(courts))
    )

    courts.append("goodbye")

    choice = Choices(",".join(courts))

    t.ask(choices=choice, say=say, attempts=3)
    t.on(event="continue", next="/talkto")

    return t.RenderJson()