def tropo_view(request): if request.method == "POST": data = json.loads(request.raw_post_data) session = data["session"] if "parameters" in session: params = session["parameters"] if ("_send_sms" in params) and ("numberToDial" in params) and ("msg" in params): numberToDial = params["numberToDial"] msg = params["msg"] t = Tropo() t.call(to=numberToDial, network="SMS") t.say(msg) log("OUT", "TEXT", numberToDial, "TROPO", request.raw_post_data, msg) return HttpResponse(t.RenderJson()) if "from" in session: caller_id = session["from"]["id"] channel = session["from"]["channel"] msg = None if "initialText" in session: msg = session["initialText"] log("IN", channel, caller_id, "TROPO", request.raw_post_data, msg) if channel == "VOICE": send_sms_tropo(caller_id, "Callback received.") t = Tropo() t.hangup() return HttpResponse(t.RenderJson()) else: return HttpResponseBadRequest()
def post(self): print "processing incoming request" # Initialize a tropo object t = Tropo() # Deserialize the request s = Session(json.dumps(request.json)) if hasattr(s, 'parameters'): # Handle the case where this is a new visitor to the site, we will initiate an outbound # SMS session to the visitor number = s.parameters['numberToDial'] print "sending welcome msg to {}".format(number) t.call(number, network="SMS") t.say( 'Welcome to the Giant Ball of String! Please respond with "fact" for additional information' ) else: # Handle other scenarios if s.initialText: # Handle the case where the user sends us a text message if 'fact' in s.initialText.lower(): t.say(get_fact()) else: t.say([ 'Welcome to the Giant Ball of String', 'You can request facts by responding with the keyword "fact"' ]) return make_response(t.RenderJson())
def sms_in(request): """ Handles tropo messaging requests """ if request.method == "POST": data = json.loads(request.body) session = data["session"] # Handle when Tropo posts to us to send an SMS if "parameters" in session: params = session["parameters"] if ("_send_sms" in params) and ("numberToDial" in params) and ("msg" in params): numberToDial = params["numberToDial"] msg = params["msg"] t = Tropo() t.call(to=numberToDial, network="SMS") t.say(msg) return HttpResponse(t.RenderJson()) # Handle incoming SMS phone_number = None text = None if "from" in session: phone_number = session["from"]["id"] if "initialText" in session: text = session["initialText"] if phone_number is not None and len(phone_number) > 1: if phone_number[0] == "+": phone_number = phone_number[1:] incoming_sms(phone_number, text, TropoBackend.get_api_id()) t = Tropo() t.hangup() return HttpResponse(t.RenderJson()) else: return HttpResponseBadRequest("Bad Request")
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): 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 sms_in(request): """ Handles tropo messaging requests """ if request.method == "POST": data = json.loads(request.body) session = data["session"] # Handle when Tropo posts to us to send an SMS if "parameters" in session: params = session["parameters"] if ("_send_sms" in params) and ("numberToDial" in params) and ("msg" in params): numberToDial = params["numberToDial"] msg = params["msg"] t = Tropo() t.call(to = numberToDial, network = "SMS") t.say(msg) return HttpResponse(t.RenderJson()) # Handle incoming SMS phone_number = None text = None if "from" in session: phone_number = session["from"]["id"] if "initialText" in session: text = session["initialText"] if phone_number is not None and len(phone_number) > 1: if phone_number[0] == "+": phone_number = phone_number[1:] incoming_sms(phone_number, text, SQLTropoBackend.get_api_id()) t = Tropo() t.hangup() return HttpResponse(t.RenderJson()) else: return HttpResponseBadRequest("Bad Request")
def tropo_view(request): if request.method == "POST": data = json.loads(request.raw_post_data) session = data["session"] if "parameters" in session: params = session["parameters"] if ("_send_sms" in params) and ("numberToDial" in params) and ("msg" in params): numberToDial = params["numberToDial"] msg = params["msg"] t = Tropo() t.call(to = numberToDial, network = "SMS") t.say(msg) log("OUT", "TEXT", numberToDial, "TROPO", request.raw_post_data, msg) return HttpResponse(t.RenderJson()) if "from" in session: caller_id = session["from"]["id"] channel = session["from"]["channel"] msg = None if "initialText" in session: msg = session["initialText"] log("IN", channel, caller_id, "TROPO", request.raw_post_data, msg) if channel == "VOICE": send_sms_tropo(caller_id, "Callback received.") t = Tropo() t.hangup() return HttpResponse(t.RenderJson()) else: return HttpResponseBadRequest()
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 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): 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.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): 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): #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 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() 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 index(request): t = Tropo() t.call("sip:[email protected]:5678", say = "ha ha ha ha ha ah ah ah ah") t.say("a b c d e f g h i j k") on = On("connect", say = "emily", next = "http://freewavesamples.com/files/Kawai-K5000W-AddSquare-C4.wav", post = "http://192.168.26.88:8080/FileUpload/receiveJson").json t.transfer(TO_NUMBER, _from= FROM_NUMBER, on=on, callbackUrl="http://192.168.26.88:8080/FileUpload/receiveJson", label="erthnbvc") t.say("Hi. I am a robot q a z w s x e d c") 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): t = Tropo() t.call("sip:[email protected]:5678", say = "ha ha ha ha ha ah ah ah ah") t.say("ah ah ah ah ah uh uh uh uh ha ha ha") on1 = On("connect", ask = Ask(Choices("[5 DIGITS]")).json).json on2 = On("ring", say = "emily2").json t.transfer(TO_NUMBER, _from= FROM_NUMBER, on=[on1,on2], choices = TransferOnChoices(terminator = '#').json) t.say("Hi. I am a robot") json = t.RenderJson() print json return json
def index(request): t = Tropo() t.call("+8613466549249") #t.startRecording('http://12b12d1b.ngrok.io/FileUpload/uploadFile', formamt = 'audio/wav', transcriptionID = "20170601startRecording", transcriptionEmailFormat = "plain", transcriptionOutURI = "http://12b12d1b.ngrok.io/FileUpload/receiveJson") t.startRecording('http://12b12d1b.ngrok.io/FileUpload/uploadFile', formamt = 'audio/wav', transcriptionID = "20170601startRecording", transcriptionEmailFormat = "plain", transcriptionLanguage = "en-usa", transcriptionOutURI = "http://12b12d1b.ngrok.io/FileUpload/receiveJson") t.say("a b c d e f g h i j k l m n o p q r s t u v w x y z @ # $ % & ") t.say(" I love my daughter") t.say("1 2 3 4 5 6 7 8 9 0 A B C D E F G") t.say("today is Thursday 2017-06-01") t.stopRecording() return t.RenderJson()
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 index(request): session = Session(request.body) print 'request.body begin' print request.body print 'request.body end' t = Tropo() #t.call(to=session.parameters['callToNumber'], network='SIP') dhhm = session.parameters['callToNumber'] say_obj = session.parameters['message252121'] #t.message(say_obj, to=dhhm, network="SMS", _from="+17754641173", channel = "TEXT") #t.call(dhhm, network="SMS", _from="+17754641173", channel = "TEXT") t.call(dhhm) t.say(say_obj) print t.RenderJson() return t.RenderJson()
def do_POST(self): 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() s = Session(post_body.decode('utf-8')) t = Tropo() t.call(to="+8618801428848", network="SMS") t.say(['Hi,Patient', 'Time to take aspilin!']) message = t.RenderJson() self.wfile.write(bytes(message, "utf8")) return
def index(request): t = Tropo() t.call("sip:[email protected]:5678", say="ha ha ha ha ha ah ah ah ah") t.say("ah ah ah ah ah uh uh uh uh ha ha ha") on1 = On("connect", ask=Ask(Choices("[5 DIGITS]")).json).json on2 = On("ring", say="emily2").json t.transfer(TO_NUMBER, _from=FROM_NUMBER, on=[on1, on2], choices=TransferOnChoices(terminator='#').json) t.say("Hi. I am a robot") json = t.RenderJson() print json return json
def tropo_index(request): '''initiates requests with tropo service''' if request.POST: # parse passed in parameters session = Session(request.body) t = Tropo() t.call('17174138746') # http://www.freesound.org/data/previews/51/51710_113976-lq.mp3 t.say('http://audiomicro-dev.s3.amazonaws.com/preview/20017/571436cb23f5955') t.say("Hi, it's Pearl!") t.say("time to start your next task") t.say(session.parameters['msg']) return HttpResponse(t.RenderJson(), mimetype='application/json')
def test_call(self): """ Test the "call" Tropo class method. """ tropo = Tropo() tropo.call(self.MY_PHONE, channel='TEXT', network='SMS', label='labelofcall', voice = 'Tian-tian', callbackUrl = 'foourl', promptLogSecurity = 'suppress') tropo.say ("Wish you were here") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print ("============test_call=============") print "render json: %s" % pretty_rendered rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"call": {"to": "%s", "network": "SMS", "channel": "TEXT", "label": "labelofcall", "voice": "Tian-tian", "callbackUrl": "foourl", "promptLogSecurity": "suppress"}}, {"say": {"value": "Wish you were here"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) # print "test_call: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def test_call(self): """ Test the "call" Tropo class method. """ tropo = Tropo() tropo.call(self.MY_PHONE, channel='TEXT', network='SMS') tropo.say("Wish you were here") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print("============test_call=============") print "render json: %s" % pretty_rendered rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"call": {"to": "%s", "network": "SMS", "channel": "TEXT"}}, {"say": {"value": "Wish you were here"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) # print "test_call: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def test_call(self): """ Test the "call" Tropo class method. """ tropo = Tropo() tropo.call(self.MY_PHONE, channel='TEXT', network='SMS') tropo.say ("Wish you were here") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print ("============test_call=============") print "render json: %s" % pretty_rendered rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"call": {"to": "%s", "network": "SMS", "channel": "TEXT"}}, {"say": {"value": "Wish you were here"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) # print "test_call: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
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 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 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(request): ''' The tropo webservice calls this after dispatcher.py initiates a call ''' if request.method == 'POST': json_data = simplejson.loads(request.raw_post_data) # Tropo embeds JSON in the POST parameters try: t = Tropo() t.call(to=json_data['session']['parameters']['numberToDial']) # Call the user # Greet them and tell them what they need to do t.say(grammar.greeting('Brad')) t.say("<break time='0.75s' />") t.say("Hopefully you finished %s" % json_data['session']['parameters']['endMsg']) t.say("<break time='1s' />") t.say("Time to start %s" % json_data['session']['parameters']['startMsg']) except KeyError: print 'Error: Key not present in JSON' print "Sending: %s" % t.RenderJson() return HttpResponse(t.RenderJson(), mimetype='application/json')
def index(request): t = Tropo() # s = Session(request.get_json(force=True)) sys.stderr.write("Incoming Request: \n") sys.stderr.write(to_unicode(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.parameters["numberToDial"] reply = s.parameters["line"] t.call(to=number, network="SMS") else: reply = ["You have reached the Haciendo demo application. " ] t.say(reply) response = t.RenderJson() sys.stderr.write(response + "\n") return response
import sys sys.path = ['..'] + sys.path from tropo import Choices, MachineDetection, JoinPrompt, LeavePrompt, On, Ask, Say, Tropo t = Tropo() #CPA mc = MachineDetection(introduction="THis is a CPA test", voice="Victor").json t.call("+14071234321", machineDetection=mc) #CPA with Boolean value which will detect CPA with 30 seconds of silence. t.call("+14071234321", machineDetection=True) #Conference with join/leave prompts jp = JoinPrompt(value="Someone just joined the conference", voice="Victor").json lp = LeavePrompt(value="Someone just left the conference", voice="Victor").json t.conference(id="1234", joinPrompt=jp, leavePrompt=lp) whisper = {} c = Choices(value="1", mode="dtmf") ask = Ask(say="Press 1 to accept this call", choices=c).json whisper["ask"] = ask say = Say("You are now being connected to the call").json whisper["say"] = say say1 = Say("http://www.phono.com/audio/holdmusic.mp3").json whisper["ring"] = say1
""" 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) tropo.stopRecording() tropo.transfer(TO)
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) tropo.stopRecording() tropo.transfer(TO)
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
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)
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)
def index(request): session = Session(request.body) t = Tropo() t.call(to=session.parameters['numberToDial'], network='JABBER') t.say(session.parameters['message']) return t.RenderJson()