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_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 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): 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 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): 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 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 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 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 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 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.say('12345', _as='DIGITS', voice='allison') 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 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.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 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 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): 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): 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.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 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() 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() 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): 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 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() t.message("Hello World from tylor", TO_NUMBER, channel='VOICE', _from='' + FROM_NUMBER, promptLogSecurity='sss') json = t.RenderJson() print json return json
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 __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(): 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()