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): 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 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): 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 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 standardize_call_info(request, provider=None): ''' Takes a provider object, figures out the important details of the call (you know, caller id and whatnot) and return it as a dictionary.s ''' if not provider: pass #TODO: Some logic to detect the provider. if provider.name == "Twilio": account_id = request.POST['AccountSid'] call_id = request.POST['CallSid'] from_caller_id = request.POST['From'] to_caller_id = request.POST['To'] status = request.POST['CallStatus'] if provider.name == "Tropo": ''' Tropo is kinda funny - it doesn't always let us grab the session info via their Session object (which we probably can help them fix). ''' try: s = Session(request.raw_post_data) call_id = s.id account_id = s.accountId from_caller_id = s.dict['from']['id'] to_caller_id = s.dict['to']['id'] status = s.state if "state" in s.dict else "ringing" except KeyError: ''' e.message has been deprecated in lieu of wrapping a str() around KeyError ''' if str(KeyError) == "session": json_post_data = json.loads(request.raw_post_data) call_id = json_post_data['result']['sessionId'] try: phone_call = PhoneCall.objects.get(call_id = call_id) call_object = phone_call from_caller_id = phone_call.from_number.number except PhoneCall.DoesNotExist: #This is a major bummer. call_object = None from_caller_id = None else: #We had a session, but we didn't have the keys we were looking for. s = Session(request.raw_post_data) number_id = s.parameters['number_to_call'] return locals() #Don't forget, we're returning a dict.
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 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 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) 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): 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.say("Hello. , , , Transferring") # t.transfer(to="sip:[email protected]", headers={"x-callername":"Kevin Bond"}) t.transfer(TO_NUMBER, headers={"x-callername": "Kevin Bond"}) 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() #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 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
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
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
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()
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): s = Session(request.body) t = Tropo() t.say(['hello world!', 'how are you doing?']) return t.RenderJson()