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 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 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 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 do_POST(self): if "/continue" in self.path: content_len = int(self.headers['content-length']) post_body = self.rfile.read(content_len) print("IN CONTINUE") print(post_body) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() r = Result(post_body.decode('utf-8')) t = Tropo() answer = r.getValue() if int(answer) == 1: t.say( "We are now transferring you to a Charlie Hospital phone operator! Please wait a moment..." ) elif int(answer) == 2: t.say( "Please provide your information: Your name, ID card, hospital department and doctor!! We will make the appointment for you!" ) else: t.say( "We see from your phone number you have an appointment with Dr.Green on Friday May 5th at 2:30PM." ) print("ANSWER " + answer) message = t.RenderJson() self.wfile.write(bytes(message, "utf8")) return else: content_len = int(self.headers['content-length']) post_body = self.rfile.read(content_len) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() print(post_body) s = Session(post_body.decode('utf-8')) t = Tropo() t.ask( choices="1,2,3", timeout=60, name="digit", say= "Welcome to Charlie Hospital!! Please press one to speak to phone operator; Press two to make a new appointment; Press three to check your appointment" ) t.on(event="continue", next=("/continue")) message = t.RenderJson() self.wfile.write(bytes(message, "utf8")) return
def index(request): 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 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): s = Session(request.body) t = Tropo() t.say('12345', _as='DIGITS', voice='allison') json = t.RenderJson() print json return json
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 verify_no(request): t = Tropo() t.say("Sorry, that wasn't on of the options.") json = t.RenderJson() print json return HttpResponse(json)
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 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)
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
def sessiontest(request): session = Session(request.body) print 'request.body is ' + request.body accountId = session.accountId callId = session.callId fromm = session.fromaddress headers = session.headers idd = session.id initialText = session.initialText if hasattr(session, 'parameters'): parameters = session.parameters else: parameters = '' timestamp = session.timestamp too = session.to userType = session.userType t = Tropo() t.say('accountId is ' + accountId) t.say('callId is ' + callId) fromid = fromm['id'] frome164Id = fromm['e164Id'] fromname = fromm['name'] fromchannel = fromm['channel'] fromnetwork = fromm['network'] t.say('from id is ' + fromid) t.say('from e164Id ' + frome164Id) t.say('from name ' + fromname) t.say('from channel ' + fromchannel) t.say('from network ' + fromnetwork) t.say('id is ' + idd) t.say('initialText is ' + str(initialText)) t.say('headers is ' + str(headers)) t.say('parameters is ' + parameters) t.say('timestamp is ' + timestamp) tooid = too['id'] too164Id = too['e164Id'] tooname = too['name'] toochannel = too['channel'] toonetwork = too['network'] t.say('to id is ' + tooid) t.say('to e164Id ' + too164Id) t.say('to name ' + tooname) t.say('to channel ' + toochannel) t.say('to network ' + toonetwork) t.say('userType is ' + userType) if ("frank" in fromname): t.say('hello frank ') else: t.say('sorry you are not frank') json = t.RenderJson() print json return json
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("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 test_hangup(self): """ Test the "hangup" Tropo class method. """ tropo = Tropo() tropo.hangup() rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_hangup=================" print "render json: %s" % pretty_rendered # print "test_hangup: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"hangup": null}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_message(self): """ Test the "message" Tropo class method. """ tropo = Tropo() tropo.message("Hello World", self.MY_PHONE, channel='TEXT', network='SMS', timeout=5, promptLogSecurity = 'suppress') rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_message=================" print "render json: %s" % pretty_rendered # print "test_message: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = ' {"tropo": [{"message": {"to": "%s", "say": {"value": "Hello World"}, "promptLogSecurity": "suppress", "network": "SMS", "timeout": 5, "channel": "TEXT"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
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 test_startRecording(self): """ Test the "startRecording" Tropo class method. """ tropo = Tropo() tropo.startRecording(self.RECORDING_URL) rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_startRecording=================" print "render json: %s" % pretty_rendered # print "test_startRecording: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"startRecording": {"url": "/receive_recording.py"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_stopRecording(self): """ Test the "stopRecording" Tropo class method. """ tropo = Tropo() tropo.stopRecording() rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_stopRecording=================" print "render json: %s" % pretty_rendered # print "test_stopRecording: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = ' {"tropo": [{"stopRecording": null}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_list_say(self): """ Test the "say" Tropo class method, when a list of Strings is passed to it. """ tropo = Tropo() tropo.say(["Hello, World", "How ya doing?"], promptLogSecurity = "suppredd") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_list_say=================" print "render json: %s" % pretty_rendered # print "test_say: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": [{"value": "Hello, World", "promptLogSecurity": "suppredd"}, {"value": "How ya doing?", "promptLogSecurity": "suppredd"}]}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_say(self): """ Test the "say" Tropo class method. """ tropo = Tropo() tropo.say("Hello, World", promptLogSecurity='soppress') rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_say=================" print "render json: %s" % pretty_rendered # print "test_say: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": {"value": "Hello, World", "promptLogSecurity": "soppress"}}]}' wanted_obj = jsonlib.loads(wanted_json) 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', 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 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 test_reject(self): """ Test the "reject" Tropo class method. """ tropo = Tropo() tropo.reject() rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_reject=================" print "render json: %s" % pretty_rendered print "Want %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"reject": null}]}' wanted_obj = jsonlib.loads(wanted_json) # print "test_reject: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
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() 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 test_redirect(self): """ Test the "redirect" Tropo class method. """ tropo = Tropo() tropo.redirect(self.MY_PHONE, "fakeredirectname") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_redirect=================" print "render json: %s" % pretty_rendered print "Wanted_Json %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"redirect": {"name": "fakeredirectname", "to": "%s"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) # print "test_redirect: %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)