def verify_no(request): t = Tropo() t.say("Sorry, that wasn't on of the options.") json = t.RenderJson() print json return HttpResponse(json)
def index(request): t = Tropo() t.call("+xxx") t.record(name = "recording", timeout = 10, maxSilence = 7, maxTime = 60, choices = {"terminator": "#"}, transcription = {"id":"1234", "url":"mailto:[email protected]", "language":"de_DE"}, say = {"value":"Willkommen zur Abfage! Sag uns bitte, wie es dir geht!"}, url = "http://www.example.com/recordings.py", voice =" Katrin") return t.RenderJson()
def tropo(): """ Receive a JSON POST from the Tropo WebAPI @see: https://www.tropo.com/docs/webapi/newhowitworks.htm """ # Stored in modules/tropo.py from tropo import Tropo, Session try: s = Session(request.body.read()) t = Tropo() # This is their service contacting us, so parse their request try: row_id = s.parameters["row_id"] # This is an Outbound message which we've requested Tropo to send for us table = s3db.msg_tropo_scratch query = (table.row_id == row_id) row = db(query).select().first() # Send the message #t.message(say_obj={"say":{"value":row.message}},to=row.recipient,network=row.network) t.call(to=row.recipient, network=row.network) t.say(row.message) # Update status to sent in Outbox outbox = s3db.msg_outbox db(outbox.id == row.row_id).update(status=2) # Set message log to actioned log = s3db.msg_log db(log.id == row.message_id).update(actioned=True) # Clear the Scratchpad db(query).delete() return t.RenderJson() except: # This is an Inbound message try: message = s.initialText # This is an SMS/IM # Place it in the InBox uuid = s.id recipient = s.to["id"] try: fromaddress = s.fromaddress["id"] except: # SyntaxError: s.from => invalid syntax (why!?) fromaddress = "" s3db.msg_log.insert(uuid=uuid, fromaddress=fromaddress, recipient=recipient, message=message, inbound=True) # Send the message to the parser reply = msg.parse_message(message) t.say([reply]) return t.RenderJson() except: # This is a Voice call # - we can't handle these yet raise HTTP(501) except: # GET request or some random POST pass
def index(request): currenttime = datetime.datetime.now() t = Tropo() sayobjOutbound = "Now is " + str(currenttime) t.message(sayobjOutbound, to="+1 725-419-2113", network="SMS") print t.RenderJson() return t.RenderJson()
def index(request): t = Tropo() t.answer(headers={"P-Header":"value goes here","Remote-Party-ID":"\"John Doe\"<sip:[email protected]>;party=calling;id-type=subscriber;privacy=full;screen=yes"}) t.say('This is your mother. Did you brush your teeth today?') json = t.RenderJson() print json return json
def setup_tropo(): tropo_core = Tropo() tropo_core.on(event='hangup', next=url_for('handle_hangup')) tropo_core.on(event='error', next=url_for('handle_error')) return tropo_core
def do_confirm_ok(self, candidate_id): caller_id = models.caller_id_if_valid(self.call_id()) models.record_vote(caller_id, candidate_id) t = Tropo() t.say("Great, your vote has been counted. Goodbye.") t.message("Thanks for voting! Tropo <3 you!", channel="TEXT", to=caller_id) return t.RenderJson()
def index(request): s = Session(request.body) t = Tropo() t.say('12345', _as='DIGITS', voice='dave') 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() 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 do_confirm_ok(self, song_id): caller_id = models.votes.caller_id_if_valid(self.call_id()) models.votes.vote_for_song(song_id, caller_id) t = Tropo() t.say("Great, your vote has been counted. Goodbye.") t.message("Thanks for voting!", channel="TEXT", to=caller_id) return t.RenderJson()
def index(request): s = Session(request.body) t = Tropo() t.say('12345', _as='DIGITS', voice='allison') json = t.RenderJson() print json return json
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)
def ivr_in(request): """ Handles tropo call requests """ if request.method == "POST": data = json.loads(request.body) phone_number = data["session"]["from"]["id"] # TODO: Implement tropo as an ivr backend. In the meantime, just log the call. if phone_number: cleaned_number = strip_plus(phone_number) v = VerifiedNumber.by_extensive_search(cleaned_number) else: v = None # Save the call entry msg = CallLog( phone_number=cleaned_number, direction=INCOMING, date=datetime.utcnow(), backend_api=SQLTropoBackend.get_api_id(), ) if v is not None: msg.domain = v.domain msg.couch_recipient_doc_type = v.owner_doc_type msg.couch_recipient = v.owner_id msg.save() t = Tropo() t.reject() return HttpResponse(t.RenderJson()) else: return HttpResponseBadRequest("Bad Request")
def ivr_in(request): """ Handles tropo call requests """ if request.method == "POST": data = json.loads(request.body) phone_number = data["session"]["from"]["id"] # TODO: Implement tropo as an ivr backend. In the meantime, just log the call. if phone_number: cleaned_number = strip_plus(phone_number) v = VerifiedNumber.by_extensive_search(cleaned_number) else: v = None # Save the call entry msg = CallLog( phone_number=cleaned_number, direction=INCOMING, date=datetime.utcnow(), backend_api=TropoBackend.get_api_id(), ) if v is not None: msg.domain = v.domain msg.couch_recipient_doc_type = v.owner_doc_type msg.couch_recipient = v.owner_id msg.save() t = Tropo() t.reject() return HttpResponse(t.RenderJson()) else: return HttpResponseBadRequest("Bad Request")
def ivr_in(request): """ Handles tropo call requests """ from tropo import Tropo if request.method == "POST": data = json.loads(request.body.decode('utf-8')) phone_number = data["session"]["from"]["id"] if phone_number: cleaned_number = strip_plus(phone_number) v = PhoneNumber.by_extensive_search(cleaned_number) else: v = None # Save the call entry msg = Call( phone_number=cleaned_number, direction=INCOMING, date=datetime.utcnow(), backend_api=SQLTropoBackend.get_api_id(), ) if v is not None: msg.domain = v.domain msg.couch_recipient_doc_type = v.owner_doc_type msg.couch_recipient = v.owner_id msg.save() t = Tropo() t.reject() return HttpResponse(t.RenderJson()) else: return HttpResponseBadRequest("Bad Request")
def index(request): t = Tropo() VOICE = 'Grace' t.record(name='voicemail.mp3', say='Your call is important. Please leave a short message after the tone: ', url = 'http://www.example.com', beep = True, format = 'audio/mp3', voice = VOICE) return t.RenderJson()
def index(request): t = Tropo() t.call(to="+17326820887", network = "SMS") t.say("Tag, you're it!") return t.RenderJson()
def index(request): s = Session(request.body) t = Tropo() t.call(to=' ' + TO_NUMBER, _from=' ' + FROM_NUMBER, label='xiangwyujianghu', voice='Tian-tian', callbackUrl='http://192.168.26.88:8080/FileUpload/receiveJson', promptLogSecurity='suppress') t.say('This is your mother. Did you brush your teeth today?') json = t.RenderJson() print json return json
def index(request): s = Session(request.body) t = Tropo() t.call(to='tel:+' + TO_NUMBER, _from='tel:+' + FROM_NUMBER) t.say('This is your mother. Did you brush your teeth today?') json = t.RenderJson() print(json) return json
def index(request): t = Tropo() t.message("Hello World", TO_NUMBER, channel='VOICE', _from='tel:+' + FROM_NUMBER) json = t.RenderJson() print json return json
def index(request): t = Tropo() # s = Session(request.get_json(force=True)) sys.stderr.write(str(request.body) + "\n") s = Session(request.body) message = s.initialText # print("Initial Text: " + initialText) # Check if message contains word "results" and if so send results if not message: # number = s["session"]["parameters"]["numberToDial"] number = s.parameters["numberToDial"] reply = "Would you like to vote?" t.call(to=number, network="SMS") # t.say(reply) elif message.lower().find("results") > -1: results = get_results() reply = ["The current standings are"] for i, result in enumerate(results): if i == 0: reply.append(" *** %s is in the lead with %s percent of the votes.\n" % (result[0], str(round(result[2])))) elif i <= 3: reply.append(" - %s has %s percent of the votes.\n" % (result[0], str(round(result[2])))) # Check if message contains word "options" and if so send options elif message.lower().find("options") > -1: options = get_options() reply = ["The options are..."] msg = "" for option in options: msg += "%s, " % (option) msg = msg[:-2] + "" reply.append(msg) # Check if message contains word "vote" and if so start a voting session elif message.lower().find("vote") > -1: # reply = "Let's vote! Look for a new message from me so you can place a secure vote!" reply = [process_incoming_message(message)] # If nothing matches, send instructions else: # Reply back to message # reply = "Hello, welcome to the MyHero Demo Room.\n" \ # "To find out current status of voting, ask 'What are the results?'\n" \ # "To find out the possible options, ask 'What are the options?\n" \ # '''To place a vote, simply type the name of your favorite Super Hero and the word "vote".''' reply = ["Hello, welcome to the MyHero Demo Room." , "To find out current status of voting, ask 'What are the results?'", "To find out the possible options, ask 'What are the options?", '''To place a vote, simply type the name of your favorite Super Hero and the word "vote".'''] # t.say(["Really, it's that easy." + message]) t.say(reply) response = t.RenderJson() sys.stderr.write(response + "\n") return response
def index(request): t = Tropo() t.message("Hello World from tylor", TO_NUMBER, channel='VOICE', _from='' + FROM_NUMBER, promptLogSecurity='sss') json = t.RenderJson() print json return json
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 index(request): t = Tropo() mc = MachineDetection(introduction="This is a test. Please hold while I determine if you are a Machine or Human. Processing. Finished. THank you for your patience.", voice="Victor").json t.call(to="+14071234321", machineDetection=mc) t.on(event="continue", next="/continue.json") return t.RenderJson()
def continue_conversation(user_id, topics, choice): if choice in topics: response = "You asked for %s: %s" % (topics[choice]["title"], topics[choice]["text"]) else: clear_conversation(user_id) return start_conversation(user_id, choice) phone = Tropo() phone.say(response) return (phone.RenderJson(), 200, {"content-type": "application/json"})
def index(request): r = Result(request.body) t = Tropo() userType = r.getUserType() t.say("You are a " + userType) return t.RenderJson()
def index(request): t = Tropo() VOICE = 'Grace' transcriptionobj = Transcription(id = "tropo-12123", url = "http://192.168.26.88:8080/FileUpload/uploadFile", language = "English").json t.record(transcription = transcriptionobj, name='voicemail.wav', say='Your call is important. Please leave a short message after the tone: ', url = 'http://192.168.26.88:8080/FileUpload/uploadFile', beep = True, formamt = 'audio/wav', sensitivity = 5.3) return t.RenderJson()
def continue_conversation(user_id, topics, choice): if choice in topics: response = "You asked for %s: %s" % (topics[choice]['title'], topics[choice]['text']) else: clear_conversation(user_id) return start_conversation(user_id, choice) phone = Tropo() phone.say(response) return (phone.RenderJson(), 200, {'content-type': 'application/json'})
def hello(request): t = Tropo() #This is the initial text that you want msg = request.POST['msg'] #This sends a text reply back json = t.say("you just said: " + msg) #This renders the reply into JSON so Tropo can read it json = t.RenderJson(json) #This sends the JSON to Tropo return HttpResponse(json)
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()
def index(request): t = Tropo() t.call("sip:[email protected]:5678") t.say("tropo status") t.wait(27222, allowSignals = 'dfghjm') t.say("today is Friday 2017-06-02") return t.RenderJson()
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()
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): s = Session(request.body) t = Tropo() t.say("One moment please.") t.transfer(TO_NUMBER, _from="tel:+" + FROM_NUMBER) t.say("Hi. I am a robot") json = t.RenderJson() print json return json
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)
def index(request): t = Tropo() t.say('12345', _as='DIGITS', voice='dave', promptLogSecurity='suppress') t.say('s s s s f f f ', promptLogSecurity='suppress') t.say(["Hello, World", "How ya doing?"], promptLogSecurity="suppredd") json = t.RenderJson() print json print 'sys.path is %s' % sys.path return json
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()
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()
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()
def index(request): t = Tropo() VOICE = 'Grace' transcriptionobj = Transcription(id = "tropo-12123", url = "http://192.168.26.88:8080/FileUpload/uploadFile", language = "English").json recordURLobj1 = RecordUrlTuple(url = "http://192.168.26.88:8080/FileUpload/uploadFile1", username = "******", password="******", method="POST").json recordURLobj2 = RecordUrlTuple(url = "http://192.168.26.88:8080/FileUpload/uploadFile", username = "******", password="******", method="POST").json recordURLobj3 = RecordUrlTuple(url = "http://192.168.26.88:8080/FileUpload/uploadFile3", username = "******", password="******", method="POST").json recordURLobj4 = RecordUrlTuple(url = "http://192.168.26.88:8080/FileUpload/uploadFile4", username = "******", password="******", method="POST").json t.record(url = [recordURLobj1, recordURLobj2, recordURLobj3, recordURLobj4],transcription = transcriptionobj, name='voicemail.wav', say='Your call is important. Please leave a short message after the tone: ', beep = True, formamt = 'audio/wav', sensitivity = 5.3) return t.RenderJson()
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()
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
def index(request): session = Session(request.body) t = Tropo() #jj = JoinPrompt(value = "who are you who let you come in") jj = JoinPrompt("who are you who let you come in") #ll = LeavePrompt(value = "byebye samsung") ll = LeavePrompt("byebye samsung") t.call(to=session.parameters['callToNumber'], network='SIP') t.conference(id='yuxiangj', joinPrompt=jj.json, leavePrompt=ll.json) t.say(session.parameters['message']) return t.RenderJsonSDK()
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
def index(request): session = Session(request.body) print 'request.body begin' print request.body print 'request.body end' t = Tropo() smsContent = session.initialText #t.call(to=session.parameters['callToNumber'], network='SIP') #t.say(session.parameters['message']) """ t = Tropo() t.call(to="[email protected]:5678") t.say("wo shi yi ke xiao xiao cao") """ #base_url = 'http://192.168.26.21:8080/gateway/sessions' base_url = 'https://api.tropo.com/1.0/sessions' #token = '4c586866434c4c59746f4361796b634477600d49434d434874584d4546496e70536c706749436841476b684371' # Insert your token here Application ID: 301 token = '6c77565670494a6b474f646a5658436b514658724a0055674f4e735041764f665463626b535472616869746768' # Insert your fire-app-with-token.py token here action = 'create' #number = 'sip:[email protected]:5678' # change to the Jabber ID to which you want to send the message #number = 'sip:[email protected]:5678' # change to the Jabber ID to which you want to send the message #number = '+861891020382' # change to the Jabber ID to which you want to send the message number = '+86134766549249' # change to the Jabber ID to which you want to send the message message = 'redirect by Python content is ' + str(smsContent) params = urlencode([('action', action), ('token', token), ('callToNumber', number), ('message252121', message)]) data = urlopen('%s?%s' % (base_url, params)).read() print 'data is ' print data #return t.RenderJson() return "receive SMS successfully"
def get_response_object(self): if self.name == "Twilio": from twilio import twiml return twiml.Response() if self.name == "Tropo": from tropo import Tropo return Tropo()
def hello(request): try: t = Tropo() session = Session(request.body) if ('parameters' in dir(session)): print('Message request') t.call(to="+" + session.parameters['to'].strip(), network="SMS") json = t.say(session.parameters['msg']) json = t.RenderJson(json) return HttpResponse(json) else: msg = request.POST.get('msg', '') s = Session(request.body) cell = s.fromaddress['id'] # lookup patient with this cell # if cell[0] == '1': # trim leading 1 in cell # if there cell = cell[1:] print('Cell #%s' % cell) p = Patient.objects.filter( cell=cell) # all patients with this cell # if p.exists(): # if cell # found then create new entry if p.count() > 1: print('WARNING: Multiple patients with cell # %s' % cell) parent = p[0] # assume first entry = Entry(patient=parent, entry=msg) entry.save() if msg.find('CODE') > -1: json = t.say("Congratulations " + parent.name + " your code qualified you for a prize!") else: json = t.say("Entry saved, thank you " + parent.name) else: # if cell # NOT found then notify json = t.say("Could not find patient with cell # " + cell) json = t.RenderJson(json) return HttpResponse(json) except Exception, err: print('ERROR: %s\n' % str(err))
def ivr_in(request): """ Handles tropo call requests """ if request.method == "POST": data = json.loads(request.raw_post_data) phone_number = data["session"]["from"]["id"] #### # TODO: Implement tropo as an ivr backend. In the meantime, just log the call. cleaned_number = phone_number if cleaned_number is not None and len( cleaned_number) > 0 and cleaned_number[0] == "+": cleaned_number = cleaned_number[1:] # Try to look up the verified number entry v = VerifiedNumber.view("sms/verified_number_by_number", key=cleaned_number, include_docs=True).one() # If none was found, try to match only the last digits of numbers in the database if v is None: v = VerifiedNumber.view("sms/verified_number_by_suffix", key=cleaned_number, include_docs=True).one() # Save the call entry msg = CallLog(phone_number=cleaned_number, direction=INCOMING, date=datetime.utcnow(), backend_api=TROPO_BACKEND_API_ID) if v is not None: msg.domain = v.domain msg.couch_recipient_doc_type = v.owner_doc_type msg.couch_recipient = v.owner_id msg.save() #### t = Tropo() t.reject() return HttpResponse(t.RenderJson()) else: return HttpResponseBadRequest("Bad Request")
def index(request): s = Session(request.body) t = Tropo() t.call(to='tel:+' + TO_NUMBER, _from='tel:+' + FROM_NUMBER) t.say('This is your mother. Did you brush your teeth today?') json = t.RenderJson() print json return json
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()
def test_transfer(self): """ Test the "transfer" Tropo class method. """ tropo = Tropo() tropo.say ("One moment please.") tropo.transfer(self.MY_PHONE, callbackUrl="http://192.168.26.88:8080/FileUpload/receiveJson", label="woshitestlidela") tropo.say("Hi. I am a robot") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_transfer=================" print "render json: %s" % pretty_rendered # print "test_transfer: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": {"value": "One moment please."}}, {"transfer": {"to": "6021234567", "callbackUrl": "http://192.168.26.88:8080/FileUpload/receiveJson", "label": "woshitestlidela"}}, {"say": {"value": "Hi. I am a robot"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_transfer(self): """ Test the "transfer" Tropo class method. """ tropo = Tropo() tropo.say("One moment please.") tropo.transfer(self.MY_PHONE) tropo.say("Hi. I am a robot") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_transfer=================" print "render json: %s" % pretty_rendered # print "test_transfer: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": {"value": "One moment please."}}, {"transfer": {"to": "6021234567"}}, {"say": {"value": "Hi. I am a robot"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
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)
def index(request): #s = Session(request.body) t = Tropo() t.call(to=' ' + TO_NUMBER, _from=' ' + FROM_NUMBER, label='xiangwyujianghu', network = 'MMS') mediaa = ['http://www.gstatic.com/webp/gallery/1.jpg', 'macbook eclipse', 'http://artifacts.voxeolabs.net.s3.amazonaws.com/test/test.png', 1234567890, '0987654321', 'https://www.travelchinaguide.com/images/photogallery/2012/beijing-tiananmen-tower.jpg'] t.say('This is your mother. Did you brush your teeth today?', media = mediaa) json = t.RenderJson() print json return json
def do_POST(self): content_len = int(self.headers['content-length']) post_body = self.rfile.read(content_len) # Send response status code self.send_response(200) # Send headers self.send_header('Content-type', 'text/html') self.end_headers() s = Session(post_body.decode('utf-8')) t = Tropo() t.say(['Hello world!', 'This is a test']) message = t.RenderJson() # Send message back to client # Write content as utf-8 data self.wfile.write(bytes(message, "utf8")) return