def index(request):
    s = Session(request.body)
    t = Tropo()
    t.setVoice('dave')
    # we use what has been set in Tropo object
    t.say(['hello world!'])
    # we use what is set in the method call
    t.say(['hello world!'], voice="allison")

    # we use the voice that has been set in Tropo object
    choices = Choices("[5 digits]").obj
    t.ask(choices,
              say="Please enter your 5 digit zip code.",
              attempts=3, bargein=True, name="zip", timeout=5)

    # we use the voice passed in the method call.
    choices = Choices("[5 digits]").obj
    t.ask(choices,
              say="Please enter your 5 digit zip code.",
              attempts=3, bargein=True, name="zip", timeout=5, voice="allison")


    json = t.RenderJson()
    print json
    return json
Esempio n. 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()
Esempio n. 3
0
def index(request):
    s = Session(request.body)
    t = Tropo()
    t.setVoice('dave')
    # we use what has been set in Tropo object
    t.say(['hello world!'])
    # we use what is set in the method call
    t.say(['hello world!'], voice="allison")

    # we use the voice that has been set in Tropo object
    choices = Choices("[5 digits]").obj
    t.ask(choices,
          say="Please enter your 5 digit zip code.",
          attempts=3,
          bargein=True,
          name="zip",
          timeout=5)

    # we use the voice passed in the method call.
    choices = Choices("[5 digits]").obj
    t.ask(choices,
          say="Please enter your 5 digit zip code.",
          attempts=3,
          bargein=True,
          name="zip",
          timeout=5,
          voice="allison")

    json = t.RenderJson()
    print json
    return json
Esempio n. 4
0
 def index(self):
     t = Tropo()
     t.say("Welcome to Pitchlift")
     choices = Choices(self.choices())
     t.ask(choices, say=self.prompt())
     t.on(event="continue", next="/menu/cont")
     return t.RenderJson()
Esempio n. 5
0
def speak_webpage():
    print "speak_webpage"
    t = Tropo()
    userid = request.args.get('userid', None)
    if userid is None:
        t.say("No user specified. Error.")
        t.on(event='continue', next='/home')
        return t.RenderJson()
    userid = int(userid)
    user = User.query.filter_by(userid=userid).first()

    url = im_feeling_lucky(user.voice_query)

    webpage = extract.ParsedWebpage(url)
    page_n = int(request.args['page'])
    if page_n >= len(webpage.chunks):
        t.say("End of document.")
        t.on(event='continue', next='/home')
        return t.RenderJson()

    # Deal with the variety of commands you can use to navigate.
    t.ask(
        choices='link([1-4 DIGITS]), command(next, home)',
        say=webpage.chunks[page_n],
        bargein=False,
    )
    t.on(event='continue', next='/deal_with_links?userid={0}&page={1}'
        .format(userid, page_n))
    return t.RenderJson()
def index(request):
	t = Tropo()
	t.ask(choices = "yes(yes,y,1), no(no,n,2)", timeout=60, name="reminder", say = "Hey, did you remember to take your pills?")	
	t.on(event = "continue", next ="/continue")
	t.on(event = "incomplete", next ="/incomplete")
	json = t.RenderJson()
	print(json)
	return json
Esempio n. 7
0
def index(request):
	t = Tropo()
	t.call(to = "*****@*****.**", _from = "*****@*****.**", channel = "TEXT", network = "JABBER")
	t.ask(choices = "yes(yes,y,1), no(no,n,2)", timeout=60, name="reminder", say = "Hey, did you remember to take your pills?")	
	t.on(event = "continue", next ="verify_yes")
	t.on(event = "incomplete", next ="verify_no")
	json = t.RenderJson()
	print json
	return HttpResponse(json)
Esempio n. 8
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
Esempio n. 9
0
def index(request):
    t = Tropo()
    t.on("continue", next="/continue.json", post = 'http://192.168.26.88:8080/FileUpload/receiveJson', say = "this is say in on function")
    t.on("error", next = "/error.json")
    t.on("hangup", next = "/hangup.json")
    t.on("incomplete", next = "/incomplete.json")
    t.ask(say = "Welcome to Tropo.  What's your birth year?", name = "year", require = "true", choices = "[4 DIGITS]")
    json = t.RenderJsonSDK()
    print json
    return json
Esempio n. 10
0
def index(request):
    t = Tropo()
    t.ask(choices="yes(yes,y,1), no(no,n,2)",
          timeout=60,
          name="reminder",
          say="Hey, did you remember to take your pills?")
    t.on(event="continue", next="/continue")
    t.on(event="incomplete", next="/incomplete")
    json = t.RenderJson()
    print json
    return json
Esempio n. 11
0
def index():
    t = Tropo()
    t.ask(
        choices='[1-3 DIGITS]',
        name='code',
        say=_('Please enter your country code if you know it.'),
        timeout=2,
    )
    t.on(event='continue', next=url_for('phone.country'))
    t.on(event='incomplete', next=url_for('phone.language'))
    return t.RenderJson()
Esempio n. 12
0
    def do_listen(self):
        prompt = """
        If you know the five digit pitch eye dee
        you want to listen to, please enter it now.
        If you want to hear a random pitch,
        press zero or say random"""

        t = Tropo()
        choices = Choices("0, random, [5 DIGITS]")
        t.ask(choices, say=prompt)
        t.on(event="continue", next="/listen")
        return t.RenderJson()
Esempio n. 13
0
def index(request):

	t = Tropo()

	t.ask(choices = "yes(yes,y,1), no(no,n,2)", timeout = 15, name = "directory", minConfidence = 1, attempts = 3, say = "Are you trying to reach the sales department??")

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

        json = t.RenderJson()

        print json
	return json
def index(request):

	t = Tropo()

	t.ask(choices = "yes(yes,y,1), no(no,n,2)", timeout = 15, name = "directory", minConfidence = 1, attempts = 3, say = "Are you trying to reach the sales department??")

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

        json = t.RenderJson()

        print(json)
	return json
Esempio n. 15
0
    def do_response(self):
        answer = self.get_answer()
        candidate = models.find_candidate_by_code(answer)

        if not candidate:
            return self.do_bad_choice()
        else:
            t = Tropo()
            prompt = "You chose %s, is that correct? " % candidate['name']
            choices = self.confirm_choices()
            t.ask(choices, say=prompt + self.confirm_prompt())
            t.on(event="continue", next=self.confirm_url(candidate['id']))
            return t.RenderJson()
Esempio n. 16
0
    def do_menu(self):
        t = Tropo()
        prompt = """
        You will shortly be prompted to enter the two digit code for the
        company you want to vote for.  If you already know the code, you can
        enter it at any time using your phone's keypad.
        """
        for candidate in models.get_candidates():
            prompt += "For %s, enter %s. " % (candidate['name'], candidate['vote_code'])

        t.ask(Choices("[2 DIGITS]", mode="dtmf"), say=prompt)
        t.on(event="continue", next=self.response_url())
        return t.RenderJson()
Esempio n. 17
0
    def do_response(self):
        song_id = self.get_answer()
        song_title = models.songs.song_title(song_id)

        if not song_id:
            return self.do_bad_choice()
        else:
            t = Tropo()
            prompt = "You chose %s, is that correct? " % song_title
            choices = self.confirm_choices()
            t.ask(choices, say=prompt + self.confirm_prompt())
            t.on(event="continue", next=self.confirm_url(song_id))
            return t.RenderJson()
Esempio n. 18
0
def index(request):

	t = Tropo()

        choices = Choices("[4-5 DIGITS]", mode="dtmf", terminator = "#")
	t.ask(choices, timeout=15, name="digit", say = "What's your four or five digit pin? Press pound when finished.", asrLogSecurity="mask", maskTemplate="XDXD-")

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

        json = t.RenderJson()

        print json
	return json
def index(request):

	t = Tropo()

        choices = Choices("[4-5 DIGITS]", mode="dtmf", terminator = "#")
	t.ask(choices, timeout=15, name="digit", say = "What's your four or five digit pin? Press pound when finished.")

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

        json = t.RenderJson()

        print json
	return json
Esempio n. 20
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()
Esempio n. 21
0
    def do_menu(self):
        t = Tropo()
        t.say("hello, thank you for helping us choose the music")

        prompts = []
        choices = []
        for title, keyword, number, votes_cache in models.songs.songs_array():
            choices.append("%s(%s,%s)" % (number, keyword, number))
            prompts.append("For %(title)s, say %(keyword)s or press %(number)s." % locals())
        prompt = " ".join(prompts)

        t.ask(Choices(",".join(choices)), say=prompt)
        t.on(event="continue", next=self.response_url())
        return t.RenderJson()
Esempio n. 22
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()
Esempio n. 23
0
def language():
    supported_languages = ', '.join(['english'])

    t = Tropo()

    t.ask(
        choices=supported_languages,
        name='language',
        say=_('Which of the following languages would you prefer? %s') %
        supported_languages,
        timeout=10,
    )
    t.on(event='continue', next=url_for('phone.language_select'))

    return t.RenderJson()
Esempio n. 24
0
 def test_ask(self):
     """
     Test the "ask" Tropo class method.
     """
     tropo = Tropo()
     tropo.ask("[5 digits]",
               say = Say("Please enter a 5 digit zip code").json)
     rendered = tropo.RenderJson()
     pretty_rendered = tropo.RenderJson(pretty=True)
     print "===============test_ask================="
     print "render json: %s" % pretty_rendered
     rendered_obj = jsonlib.loads(rendered)
     wanted_json = '{"tropo": [{"ask": {"say": {"value": "Please enter a 5 digit zip code"}, "choices": {"value": "[5 digits]"}}}]}'
     wanted_obj = jsonlib.loads(wanted_json)
     # print "test_ask: %s" % tropo.RenderJson()
     self.assertEqual(rendered_obj, wanted_obj)
Esempio n. 25
0
def index(request):
    t = Tropo()
    t.on("continue",
         next="/continue.json",
         post='http://192.168.26.88:8080/FileUpload/receiveJson',
         say="this is say in on function")
    t.on("error", next="/error.json")
    t.on("hangup", next="/hangup.json")
    t.on("incomplete", next="/incomplete.json")
    t.ask(say="Welcome to Tropo.  What's your birth year?",
          name="year",
          require="true",
          choices="[4 DIGITS]")
    json = t.RenderJsonSDK()
    print json
    return json
Esempio n. 26
0
 def test_ask(self):
     """
     Test the "ask" Tropo class method.
     """
     tropo = Tropo()
     tropo.ask("[5 digits]",
               say = Say("Please enter a 5 digit zip code").json)
     rendered = tropo.RenderJson()
     pretty_rendered = tropo.RenderJson(pretty=True)
     print "===============test_ask================="
     print "render json: %s" % pretty_rendered
     rendered_obj = jsonlib.loads(rendered)
     wanted_json = '{"tropo": [{"ask": {"say": {"value": "Please enter a 5 digit zip code"}, "choices": {"value": "[5 digits]"}}}]}'
     wanted_obj = jsonlib.loads(wanted_json)
     # print "test_ask: %s" % tropo.RenderJson()
     self.assertEqual(rendered_obj, wanted_obj)
Esempio n. 27
0
    def POST(self, pitch_id):
        t = Tropo()

        t.say("here is your pitch")
        print self.s3_url(pitch_id)
        url = self.s3_url(pitch_id)
        t.say(url)

        choices = Choices("happy (1, happy), redo (2, redo)")
        prompt = "If you are happy with this pitch"
        prompt += "press 1 or say happy now."
        prompt += "If you would like to redo this pitch,"
        prompt += "press 2 or say redo now."
        t.ask(choices, say=prompt)

        t.on(event="continue", next="/record/after/cont/%s" % pitch_id)
        return t.RenderJson()
Esempio n. 28
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()
Esempio n. 29
0
def index(request):
    t = Tropo()

    t.say(
        "Welcome to the automated voice driving citations checker, a free service to find where and when you need to appear in court."
    )

    choices = Choices("[2-4 DIGITS]", mode="dtmf", attempts=3)
    t.ask(
        choices,
        timeout=15,
        name="birthday_year",
        say="To verify who you are, please start by entering your four digit year of birth",
    )

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

    return t.RenderJson()
def index(request):
    t = Tropo()
    t.ask(
        choices="[4 DIGITs]",
        timeout=5,
        bargein="true",
        name="year",
        attempts=3,
        required="true",
        say=[
            {"event": "timeout", "value": "Sorry, I did not hear anything"},
            {"event": "nomatch:1", "value": "Don't think that was a year."},
            {"event": "nomatch:2", "value": "Nope, still not a year."},
            {"value": "What is your birth year?"},
        ],
    )

    json = t.RenderJson()
    print(json)
    return json
def index (request):
    t = Tropo()
    t.ask(choices = "[4 DIGITs]", 
          timeout=5,
          bargein="true",
          name="year",
          attempts=3,
          required="true",
          say = [{'event':'timeout',
                  'value':"Sorry, I did not hear anything"},
                 {'event':'nomatch:1',
                  'value':"Don't think that was a year."},
                 {'event':'nomatch:2',
                  'value':"Nope, still not a year."},
                 {'value': "What is your birth year?"}
                 ])   

    json = t.RenderJson()
    print json
    return json
Esempio n. 32
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()
Esempio n. 33
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
Esempio n. 34
0
def index(request):
    t = Tropo()
    t.ask(choices="[4 DIGITs]",
          timeout=5,
          bargein="true",
          name="year",
          attempts=3,
          required="true",
          say=[{
              'event': 'timeout',
              'value': "Sorry, I did not hear anything"
          }, {
              'event': 'nomatch:1',
              'value': "Don't think that was a year."
          }, {
              'event': 'nomatch:2',
              'value': "Nope, still not a year."
          }, {
              'value': "What is your birth year?"
          }])

    json = t.RenderJson()
    print json
    return json
Esempio n. 35
0
class CallResponse(object):
    '''
    A response to a request from a voip provider such as twilio or tropo.  
    Abstracts common verbs such as .say() and .ask() and .conference() and provides the appropriate command for the provider.
    '''
    def __init__(self, provider, *args, **kwargs):
        '''
        Takes a PhoneProvider object, sets the provider for this response to that provider.
        '''
        self.provider = provider
        if provider.name == "Twilio":
            self.response_object = twiml.Response()
        if provider.name == "Tropo":
            self.response_object = Tropo()
        super(CallResponse, self).__init__()

    def render(self):
        if self.provider.name == "Twilio":
            return HttpResponse(self.response_object, mimetype='text/xml')
        if self.provider.name == "Tropo":
            return HttpResponse(self.response_object.RenderJson(),
                                mimetype='text/json')

    def say(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            if kwargs['voice'] == 'Allison' or kwargs[
                    'voice'] == 'Susan' or kwargs['voice'] == 'Vanessa':
                kwargs['voice'] = 'woman'
            else:
                kwargs['voice'] = 'man'
            return self.response_object.addSay(*args, **kwargs)
        if self.provider.name == "Tropo":
            return self.response_object.say(*args, **kwargs)

    def transfer(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            return self.response_object.addDial(*args, **kwargs)
        if self.provider.name == "Tropo":
            return self.response_object.transfer(*args, **kwargs)

    def conference(self, start_recording=False, *args, **kwargs):
        if self.provider.name == "Twilio":
            if start_recording:
                dial = self.response_object.addDial(
                    record=True,
                    action='%s/comm/recording_handler/call/%s/' %
                    (resources.COMM_DOMAIN, kwargs['conference_id']))
            else:
                dial = self.response_object.addDial()
            startConferenceOnEnter = True if 'start_now' in kwargs and kwargs[
                'start_now'] else False  #Sometimes we want this joiner to start the conference.  Sometimes not.
            command = dial.addConference(
                kwargs['conference_id'],
                startConferenceOnEnter=startConferenceOnEnter)
            comm_logger.info('Telling Twilio: %s' % dial)
            return command
        if self.provider.name == "Tropo":
            self.response_object.on(
                "hangup",
                next="/comm/handle_hangup/%s/%s/" %
                (kwargs['conference_id'], kwargs['number'].id))
            if 'record' in kwargs and kwargs['record']:
                self.response_object.startRecording(
                    '%s/comm/recording_handler/call/%s/' %
                    (resources.COMM_DOMAIN, kwargs['conference_id']),
                    format="audio/mp3")
            return self.response_object.conference(kwargs['conference_id'],
                                                   allowSignals=[
                                                       'leaveConference',
                                                   ],
                                                   *args,
                                                   **kwargs)

    def conference_holding_pattern(self, conference_id, number_object,
                                   hold_music):
        '''
        Put someone on hold, perparing them for a conference.  During their hold, play the hold music.
        '''
        if self.provider.name == "Twilio":
            dial = self.response_object.addDial()
            reactor.callFromThread(twilio_deferred_voicemail_determination,
                                   conference_id, 30)
            return dial.addConference(
                conference_id)  #TODO: waitUrl=hold_music)

        if self.provider.name == "Tropo":
            #First we add the hold music, allowing for the "exithold" signal to end it.
            self.response_object.say(
                hold_music,
                allowSignals=["joinConference", "goToVoiceMail", "incomplete"])
            self.response_object.on("hangup",
                                    next="/comm/handle_hangup/%s/%s/" %
                                    (conference_id, number_object.id))
            self.response_object.on(
                'joinConference',
                next="/comm/simply_join_conference/%s/%s/" %
                (conference_id, number_object.id))
            self.response_object.on('goToVoiceMail', next="/comm/voicemail/")
            reactor.callFromThread(send_deferred_tropo_signal, conference_id,
                                   'goToVoiceMail', 40)  #How to test this?

    def join_and_begin_conference(self, conference_id, number, *args,
                                  **kwargs):
        '''
        Join the user to a conference that started with a holding pattern and begin the conference.
        '''
        comm_logger.info('%s is beginning conference %s', number,
                         conference_id)
        conference_kwargs = {'conference_id': conference_id, 'number': number}
        if self.provider.name == "Twilio":
            conference_kwargs['start_now'] = True
        if self.provider.name == "Tropo":
            reactor.callFromThread(send_deferred_tropo_signal, conference_id,
                                   'joinConference', 0)

        self.conference(start_recording=True, **conference_kwargs)
        return True  #We can't know anything meaningful because we aren't going to wait around for the signal.

    def on(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            raise NotImplementedError(
                "Twilio does not offer an equivalent to Tropo's .on() method.")
        if self.provider.name == "Tropo":
            return self.response_object.on(*args, **kwargs)

    def call(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            raise NotImplementedError(
                "Twilio does not offer an equivalent to Tropo's .call() method."
            )
        if self.provider.name == "Tropo":
            if 'caller_id' in kwargs:
                kwargs['from'] = kwargs[
                    'caller_id']  #Why Tropo, do you think it's acceptable to use a python command (from) in your lib?
            return self.response_object.call(*args, **kwargs)

    def ask(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            raise NotImplementedError("We're getting there..")
        if self.provider.name == "Tropo":
            return self.response_object.ask(*args, **kwargs)

    def prompt_and_record(self,
                          recording_object=None,
                          prompt=None,
                          transcribe=False,
                          *args,
                          **kwargs):

        recording_url_args = ("recording" if recording_object else "call",
                              recording_object.id
                              if recording_object else int(kwargs['call_id']))

        if self.provider.name == "Twilio":
            self.response_object.say(prompt)
            recording_kwargs = {}
            recording_kwargs['action'] = "%s/comm/recording_handler/%s/%s/" % (
                (resources.COMM_DOMAIN, ) + recording_url_args)
            recording_kwargs['timeout'] = 20
            if transcribe:
                recording_kwargs['transcribe'] = True
                recording_kwargs[
                    'transcribeCallback'] = "%s/comm/transcription_handler/%s/%s/" % (
                        (resources.COMM_DOMAIN, ) + recording_url_args)
            self.response_object.record(**recording_kwargs)

        if self.provider.name == "Tropo":
            recording_kwargs = {}
            recording_kwargs['say'] = prompt
            recording_kwargs['url'] = "%s/comm/recording_handler/%s/%s/" % (
                (resources.COMM_DOMAIN, ) + recording_url_args)
            if transcribe:
                recording_kwargs['transcription'] = {
                    'id':
                    kwargs['call_id'],
                    "url":
                    "%s/comm/transcription_handler/%s/%s/" %
                    ((resources.COMM_DOMAIN, ) + recording_url_args)
                }
            self.response_object.record(**recording_kwargs)

    def reject(self):
        if self.provider.name == "Twilio":
            self.response_object.reject()
        else:
            raise NotImplementedError("Twilio only for the moment.")

    def hangup(self, *args, **kwargs):
        self.response_object.hangup(*args, **kwargs)
Esempio n. 36
0
if __name__ == '__main__':
    """
    Unit tests.
    """
    if (0):
        TO = "8005551212"

        ID = "foo"
        URL = "http://s3.amazonaws.com/xxx_s3_bucket/hello.wav"



        tropo = Tropo()

        tropo.ask("[5 digits]",
                  say = Say("Please enter a 5 digit zip code").json)


        tropo.call (TO)
        tropo.conference(ID)
        tropo.hangup()
        tropo.message ("Hello, World", TO)
        tropo.on(event="continue", 
             next="http://example.com/weather.py",
             say="Please hold.")

        tropo.record(say="Please say something for posterity", 
                     url=URL, 
                     choices = Choices("", terminator="#").json)
        tropo.redirect(ID)
        tropo.reject(ID)
Esempio n. 37
0
if __name__ == '__main__':
    """
    Unit tests.
    """
    if (0):
        TO = "8005551212"

        ID = "foo"
        URL = "http://s3.amazonaws.com/xxx_s3_bucket/hello.wav"



        tropo = Tropo()

        tropo.ask("[5 digits]",
                  say = Say("Please enter a 5 digit zip code").json)

        tropo.call (TO)
        tropo.conference(ID)
        tropo.hangup()
        tropo.message ("Hello, World", TO)
        tropo.on(event="continue", 
             next="http://example.com/weather.py",
             say="Please hold.")

        tropo.record(say="Please say something for posterity", 
                     url=URL, 
                     choices = Choices("", terminator="#").json)
        tropo.redirect(ID)
        tropo.reject(ID)
        tropo.startRecording(URL)
Esempio n. 38
0
class CallResponse(object):
    '''
    A response to a request from a voip provider such as twilio or tropo.  
    Abstracts common verbs such as .say() and .ask() and .conference() and provides the appropriate command for the provider.
    '''
    
    def __init__(self, provider, *args, **kwargs):
        '''
        Takes a PhoneProvider object, sets the provider for this response to that provider.
        '''
        self.provider = provider
        if provider.name == "Twilio":
            self.response_object = twiml.Response()
        if provider.name == "Tropo":
            self.response_object = Tropo()
        super(CallResponse, self).__init__()
        
    def render(self):
        if self.provider.name == "Twilio":
            return HttpResponse(self.response_object, mimetype='text/xml')
        if self.provider.name == "Tropo":
            return HttpResponse(self.response_object.RenderJson(), mimetype='text/json')
    
    def say(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            if kwargs['voice'] == 'Allison' or kwargs['voice'] == 'Susan' or kwargs['voice'] == 'Vanessa':
                kwargs['voice'] = 'woman'
            else:
                kwargs['voice'] = 'man'
            return self.response_object.addSay(*args, **kwargs)
        if self.provider.name == "Tropo":
            return self.response_object.say(*args, **kwargs)

    def transfer(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            return self.response_object.addDial(*args, **kwargs)
        if self.provider.name == "Tropo":
            return self.response_object.transfer(*args, **kwargs)
        
    def conference(self, start_recording=False, *args, **kwargs):
        if self.provider.name == "Twilio":
            if start_recording:
                dial = self.response_object.addDial(record=True, action='%s/comm/recording_handler/call/%s/' % (resources.COMM_DOMAIN, kwargs['conference_id']))
            else:
                dial = self.response_object.addDial()
            startConferenceOnEnter = True if 'start_now' in kwargs and kwargs['start_now'] else False #Sometimes we want this joiner to start the conference.  Sometimes not.
            command = dial.addConference(kwargs['conference_id'], startConferenceOnEnter=startConferenceOnEnter)
            comm_logger.info('Telling Twilio: %s' % dial)
            return command
        if self.provider.name == "Tropo":
            self.response_object.on("hangup", next="/comm/handle_hangup/%s/%s/" % (kwargs['conference_id'], kwargs['number'].id))
            if 'record' in kwargs and kwargs['record']:
                self.response_object.startRecording('%s/comm/recording_handler/call/%s/' % (resources.COMM_DOMAIN, kwargs['conference_id']), format="audio/mp3")
            return self.response_object.conference(kwargs['conference_id'], allowSignals=['leaveConference',], *args, **kwargs)
    
    def conference_holding_pattern(self, conference_id, number_object, hold_music):
        '''
        Put someone on hold, perparing them for a conference.  During their hold, play the hold music.
        '''
        if self.provider.name == "Twilio":
            dial = self.response_object.addDial()
            reactor.callFromThread(twilio_deferred_voicemail_determination, conference_id, 30)
            return dial.addConference(conference_id)#TODO: waitUrl=hold_music)
         
        if self.provider.name == "Tropo":
            #First we add the hold music, allowing for the "exithold" signal to end it.
            self.response_object.say(hold_music, allowSignals=["joinConference", "goToVoiceMail", "incomplete"])
            self.response_object.on("hangup", next="/comm/handle_hangup/%s/%s/" % (conference_id, number_object.id))
            self.response_object.on('joinConference', next="/comm/simply_join_conference/%s/%s/" % (conference_id, number_object.id))
            self.response_object.on('goToVoiceMail', next="/comm/voicemail/")
            reactor.callFromThread(send_deferred_tropo_signal, conference_id, 'goToVoiceMail', 40) #How to test this?

    def join_and_begin_conference(self, conference_id, number, *args, **kwargs):
        '''
        Join the user to a conference that started with a holding pattern and begin the conference.
        '''
        comm_logger.info('%s is beginning conference %s', number, conference_id)
        conference_kwargs = {'conference_id':conference_id, 'number':number}
        if self.provider.name == "Twilio":
            conference_kwargs['start_now'] = True
        if self.provider.name == "Tropo":
            reactor.callFromThread(send_deferred_tropo_signal, conference_id, 'joinConference', 0)
            
        self.conference(start_recording=True, **conference_kwargs)
        return True #We can't know anything meaningful because we aren't going to wait around for the signal.
    
    def on(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            raise NotImplementedError("Twilio does not offer an equivalent to Tropo's .on() method.")
        if self.provider.name == "Tropo":
            return self.response_object.on(*args, **kwargs)
        
    def call(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            raise NotImplementedError("Twilio does not offer an equivalent to Tropo's .call() method.")
        if self.provider.name == "Tropo":
            if 'caller_id' in kwargs:
                kwargs['from'] = kwargs['caller_id'] #Why Tropo, do you think it's acceptable to use a python command (from) in your lib?
            return self.response_object.call(*args, **kwargs)
    
    def ask(self, *args, **kwargs):
        if self.provider.name == "Twilio":
            raise NotImplementedError("We're getting there..")
        if self.provider.name == "Tropo":
            return self.response_object.ask(*args, **kwargs)
        
    def prompt_and_record(self, recording_object=None, prompt=None, transcribe=False, *args, **kwargs):
        
        recording_url_args = ("recording" if recording_object else "call", recording_object.id if recording_object else int(kwargs['call_id']))
        
        if self.provider.name == "Twilio":
            self.response_object.say(prompt)
            recording_kwargs = {}
            recording_kwargs['action'] = "%s/comm/recording_handler/%s/%s/" % ((resources.COMM_DOMAIN,) + recording_url_args)
            recording_kwargs['timeout'] = 20
            if transcribe:
                recording_kwargs['transcribe'] = True
                recording_kwargs['transcribeCallback'] = "%s/comm/transcription_handler/%s/%s/" % ((resources.COMM_DOMAIN,) + recording_url_args)
            self.response_object.record(**recording_kwargs)
            
        if self.provider.name == "Tropo":
            recording_kwargs = {}
            recording_kwargs['say'] = prompt
            recording_kwargs['url'] = "%s/comm/recording_handler/%s/%s/" % ((resources.COMM_DOMAIN,) + recording_url_args)
            if transcribe:
                recording_kwargs['transcription'] = {'id':kwargs['call_id'], "url":"%s/comm/transcription_handler/%s/%s/" % ((resources.COMM_DOMAIN,) + recording_url_args)}
            self.response_object.record(**recording_kwargs)
    
    def reject(self):
        if self.provider.name == "Twilio":
            self.response_object.reject()
        else:
            raise NotImplementedError("Twilio only for the moment.")
            
        
    
    def hangup(self, *args, **kwargs):
        self.response_object.hangup(*args, **kwargs)
Esempio n. 39
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()