def callback_view(request): response = twiml.Response() twilio_request = decompose(request) message_view(twilio_request) return response
def handle_response_digits(request): twilio_request = decompose(request) digits = twilio_request.digits twilio_response = Response() if digits == '2': # twilio_response.play('http://bit.ly/phaltsw') number = request.POST.get('From', '') twilio_response.say('A text message is on its way. Daaaaaaaaaaaaaaamn Daniel! Peace out yo') twilio_response.sms('Daaaaaaaaaaaaaaamn Daniel!', to=number) elif digits == '1': # twilio_response.play('http://bit.ly/phaltsw') # twilio_response.play('https://p.scdn.co/mp3-preview/934da7155ec15deb326635d69d050543ecbee2b4') # twilio_response.play('https://p.scdn.co/mp3-preview/934da7155ec15deb326635d69d050543ecbee2b4') twilio_response.play('https://demo.twilio.com/hellomonkey/monkey.mp3') # number = request.POST.get('From', '') # twilio_response.say('I got you bruh, sending you a text in a bit. PEACE!') # twilio_response.sms('You looking lovely today!', to=number) elif digits == "3": twilio_response.say("Record your monkey howl after the tone.") twilio_response.record(maxLength="5", action="/handle_recording") # If the caller pressed invalid input else: # twilio_response.say('Incorrect Number Pressed') return redirect("/gather") return twilio_response
def get_blacklisted_response(request): """Analyze the incoming Twilio request to determine whether or not to reject services. We'll only reject services if the user requesting service is on our blacklist. :param obj request: The Django HttpRequest object to analyze. :rtype: HttpResponse. :returns: HttpResponse if the user requesting services is blacklisted, None otherwise. """ try: # get the `From` data from the request's payload. # Only supporting GET and POST. data = request.GET if request.method == 'GET' else request.POST frm = data['From'] caller = Caller.objects.get(phone_number=frm) if caller.blacklisted: twilio_request = decompose(request) if twilio_request.type == 'voice': r = VoiceResponse() r.reject() else: # SMS does not allow to selectively reject SMS. # So, we respond with nothing, and twilio does not forward # the message back to the sender. r = Message() return HttpResponse(str(r), content_type='application/xml') except Exception: pass return None
def answeredby(request): # build validator manually because decorator not working logger.info(request.build_absolute_uri()) twilio_request = decompose(request) validator = RequestValidator(settings.TWILIO_AUTH_TOKEN) # Validate the request using its URL, POST data, # and X-TWILIO-SIGNATURE header request_valid = validator.validate( request.build_absolute_uri(), request.POST, request.META.get('HTTP_X_TWILIO_SIGNATURE', '')) if not request_valid: return HttpResponseForbidden() outbound = Outbound.objects.get(twilio_sid=twilio_request.callsid) response = VoiceResponse() if twilio_request.answeredby in ['human', 'unknown']: response.play(outbound.action.audio_file.url) else: response.hangup() outbound.answered_by = twilio_request.answeredby outbound.save() return HttpResponse(response)
def test_voice_decompose_function(self): request = self.factory.post('/test_app/decorators/verb_view/', self.call_dict) response = decompose(request) self.assertEquals(response.type, 'voice') self.assertEquals(response.accountsid, 'ACXXXX') self.assertEquals(response.from_, '+44123456789')
def respondToTwilioRequest(request): """ (HttpRequest) -> HttpResponse Takes in POST request from Twilio servers and returns the correct action. """ if request.method == "GET": return HttpResponseRedirect('/') # deal with Voice requests twilio_request = decompose(request) if twilio_request.type is 'voice': pokedexVoiceView() message_body = request.POST["Body"] pokemon_name = message_body.strip().lower() # check if pokemon is in pokedex pokedex_entry = check_pokedex(pokemon_name) response = twiml.Response() if pokedex_entry: response.message( "{0} {1}".format(pokemon_name, pokedex_entry['description']) ).media(pokedex_entry['sprite']) else: response.message( "Pokemon not found. Please type the name of pokemon to search." ) return response
def inbound(request): response = twiml.Response() # Create a new TwilioRequest object twilio_request = decompose(request) # Capture the sender and the text from_num = str(twilio_request.from_) text = str(twilio_request.body) # Process the text result = process_sms_text(text, from_num) # Return a response text to the user if not result: if twilio_request.type is 'message': response.message( 'Failed to save run. Must be of the format <Ran 5.6 in h:m:s this is a comment> excluding the angle brackets.' ) return response else: if twilio_request.type is 'message': response.message(result) return response return response
def test_sms_decompose_function(self): request = self.factory.post( '/test_app/decorators/verb_view', self.message_dict ) response = decompose(request) self.assertEquals(response.type, 'message')
def test_voice_decompose_function(self): request = self.factory.post( '/test_app/decorators/verb_view/', self.call_dict ) response = decompose(request) self.assertEquals(response.type, 'voice') self.assertEquals(response.accountsid, 'ACXXXX') self.assertEquals(response.from_, '+44123456789')
def text_message(request): response = twiml.Response() # Create a new TwilioRequest object twilio_request = decompose(request) # See the Twilio attributes on the class sender_phone_number = twilio_request.from_ sent_message_sid = twilio_request.messagesid #if this is from me then redirect to broadcast my_phone_number = os.environ.get('MY_PHONE_NUMBER') if sender_phone_number == my_phone_number: qdict = QueryDict('',mutable=True) qdict.update({'message': twilio_request.body}) redirect_url = reverse('broadcast_message') full_url = "%s?%s" % (redirect_url, qdict.urlencode()) return HttpResponseRedirect( full_url ) #get guest who sent this message guest,guest_created = Guest.objects.get_or_create(phone_number=sender_phone_number) #create message message,message_created = Message.objects.get_or_create(message_sid=sent_message_sid, guest=guest) message.text = twilio_request.body #get photos from message if int(twilio_request.nummedia) > 0 : #if this is the user's first photo, send a reply that we got it if guest.images.count() == 0: response.message("Thanks for sending us an image! This is a confirmation that we got it. We'll only send this once.") #do stuff for i in range(int(twilio_request.nummedia)): key = "{0}{1}".format("mediaurl",i) media_url = getattr(twilio_request, key) message_image,message_image_created = MessageImage.objects.get_or_create( url=media_url, message=message, guest=guest) message_image.save() guest.save() message.save() #if this is an unsubscribe, do it if message.text.lower() == "stop": guest.messaging_enabled = False guest.save() response.message("You've been unsubscribed from wedding updates!") return response return response
def inbound_view(request): response = twiml.Response() twilio_request = decompose(request) if twilio_request.type == 'message': message_obj = message_view(twilio_request) if (getattr(settings, 'DJANGO_TWILIO_SMS_RESPONSE_MESSAGE', False) or getattr(settings, 'DJANGO_TWILIO_RESPONSE_MESSAGE', False)): message_obj.send_response_message() else: response = voice_view(response) return response
def sms_post(request): # try to fake out the request.is_ajax method, so we send twilio better error messages request.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' try: response = twiml.Response() twilio_request = decompose(request) if twilio_request.type is 'message': # check commands first commands = {'CLEAR': clear_cookie} for (cmd, fn) in commands.items(): if twilio_request.body.startswith(cmd): return fn(request, twilio_request, response) # then continuation of existing, set by cookie storyId = None if 'storyId' in request.COOKIES: try: storyId = int(request.COOKIES.get('storyId')) except ValueError: pass if storyId: story = Story.objects.get(id=request.COOKIES.get('storyId')) # check if zipcode location update zipcode_location = match_zipcode(request, twilio_request) if zipcode_location: story.location = zipcode_location story.save() response.message( 'Thank you for adding a location to your story. ' + 'Find it on the map at StoriesOfSolidarity.org/#read/story/%s' % story.id) return response else: # it's a continuation of the previous content story.content = story.content + " " + twilio_request.body story.save() return response # then new story return new_story(request, twilio_request, response) else: return response except Exception: import traceback print traceback.format_exc()
def followup(request): twilio_request = decompose(request) outbound = Outbound.objects.get(twilio_sid=twilio_request.callsid) outbound.duration = twilio_request.callduration outbound.save() if outbound.answered_by in ['human', 'unknown']: outbound.send_followup() else: outbound.send_reprompt() return HttpResponse()
def handle_recording(request): """Play back the caller's recording.""" twilio_request = decompose(request) # recording_url = twilio_request.RecordingUrl # recording_url = request.values.get("RecordingUrl", None) # recording_url = request.POST.get('RecordingUrl', 'no url') # print recording_url # recording_url = request.values.get("RecordingUrl", None) twilio_response = Response() twilio_response.say("Thanks for howling... take a listen to what you howled.") # twilio_response.play(recording_url) twilio_response.say("Goodbye.") return twilio_request
def sms(request): twilio_request = decompose(request) user, created = User.objects.get_or_create(number=twilio_request.from_) twilio_number, created = TwilioNumber.objects.get_or_create( number=twilio_request.to) inbound = Inbound.create_from_twilio_request(twilio_request, twilio_number, user) body = twilio_request.body.lower() if body == 'subscribe': user.subscribe(twilio_number) return HttpResponse() if body == 'yes': outbound = Outbound.find_most_recent_call(user) action = outbound.action action.perform(user) inbound.action = action inbound.save() return HttpResponse() try: action = Action.objects.get(keyword=inbound.body, twilio_number=twilio_number) action.perform(user) inbound.action = action inbound.save() except Action.DoesNotExist: message = client.messages.create(body=twilio_number.fallback.body, to=user.number, from_=twilio_number.number) return HttpResponse()
def receive_twilio_sms(request): twilio_req = decompose(request) if twilio_req.type != 'message': log.warn( 'Unknown request type %s, from %s (Twilio ID: %s)', twilio_req.type, twilio_req.from_, twilio_req.messagesid, ) return HttpResponseNotFound() message = IncomingMessage.objects.create( twilio_id=twilio_req.messagesid, from_number=twilio_req.from_, to_number=twilio_req.to, body=twilio_req.body, ) process_incoming_message.delay(message.id) return HttpResponse(status=204)
def inbound_view(request): response = twiml.Response() # Create a new TwilioRequest object twilio_request = decompose(request) # See the Twilio attributes on the class twilio_request.to # >>> '+44123456789' # Discover the type of request if twilio_request.type is 'message': response.message('Thanks for the message!') return response # Handle different types of requests in a single view if twilio_request.type is 'voice': return voice_view(request) return response
def sms_response(request): """ This is a webhook that recieves text messages. ToDo: new phone numbers are added to database """ # from_number = request.form['From'] # body = request.form['To'] #Start our TwiML response response = MessagingResponse() twilio_request = decompose(request) from_phone_number = twilio_request.from_ #msg = response.message(str(from_phone_number)) #ToDo: see if the phone number is in our database, # if it isnt, ask for their location # when there is a response. Create a new User # tell them how to use the app # if it is, look at the text. Does it say 'Interested Listing_ID' or 'Trading' # if 'trading' ask for them to say item, description etc... in specific format. Create Listing # then calculate their distance to other users. # if a user is within a certain distance, send them a message of the Listing and tell them to send back 'Interested Listing_ID'. # if 'interested Listing_ID': # respond with a message saying 'contact 'the number of the person who made the listing' to negotiate a trade and pickup' # user = User.objects.filter(phoneNumber=from_phone_number) #return HttpResponse(str(response)) if user: #text should look like "Interested in: 17" text_body_split = twilio_request.body.split(':') if text_body_split[0].strip( ) != "Interested in" and text_body_split[0].strip( ) != 'Trading' and text_body_split[0].strip() != "See listings": # NoteToSelf: Does this send a message or does it need to return to send a message? # If the user wants to stop the text conversation # if twilio_request.body.strip() == 'stop': # response.message("Stopped") # return HttpResponse(response) response.message( "Please send a message in the form of 'Interested in: Listing number'. for example 'Interested in: 1'. Or 'Trading: the item: the description' for example 'Trading: Moose : Willing to trade half a moose, shot 2 days ago' To view listings type 'see listings'." ) return HttpResponse(response) # User has succesfully responded elif text_body_split[0].strip() == 'Interested in': listing_id = twilio_request.body.split(':')[1].strip() contactTrader(from_phone_number, listing_id) response.message( "Your contact info has been sent to the owner of this listing") return HttpResponse(response) #text the owner of the listing # ToDo: how to text someone else. (use avkash's code) elif text_body_split[0].strip() == 'Trading': new_listing = Listing(user_id=user[0].id, item=text_body_split[1], description=text_body_split[2], date_added=timezone.now()) new_listing.save() response.message( "Your trade has been sent to locals, you will recieve a message from us when someone wants to Trade!" ) return HttpResponse(response) elif text_body_split[0].strip().lower() == 'see listings': message = Message() message.body("Available listings: ") #response.message("Available listings: ") response.append(message) for listing in Listing.objects.all()[:10]: message = Message() listing_id = listing.id listing_item = listing.item message.body("Listing ID: {}, Item: {}".format( listing_id, listing_item)) response.append(message) response.append( "Please send a message in the form of 'Interested in: Listing number'. for example 'Interested in: 1'If you recieve a messaged about an item being traded in your area, text 'Interested in: listing_id' example 'Interested in: 3'." ) return HttpResponse(response) elif text_body_split[0].strip().lower() == 'remove number': toBeRemoved = User.objects.filter(id=user[0].id) toBeRemoved.delete() response.message("Your number will be removed") return HttpResponse(response) # elif text_body_split[0].strip().lower() == 'remove listing': # listing_id = text_body_split[1].strip().lower() # #user_id = user[0].id # try: # listings=Listing.objects.filter(id=listing_id) # #to_delete = listing.filter(user=user) # except: # response.message("This listing does not exist") # return HttpResponse(response) # for listing in listings: # if listing.user.id == user.id: # listing.delete() else: response.message( "When you have something to Trade, text 'Trading: the item: the description' for example 'Trading: Moose : Willing to trade half a moose, shot 2 days ago' . If you recieve a messaged about an item being traded in your area, text 'Interested in: listing_id' example 'Interested in: 3'. To remove your number fromt TextTrade, send 'remove number'. To see all listings send 'see listings'." ) return HttpResponse(response) else: new_user = User(phoneNumber=from_phone_number, becameMember=timezone.now()) new_user.save() response.message( "You have been added to our trading platform. When you have something to Trade, text 'Trading: the item: the description' for example 'Trading: Moose : Willing to trade half a moose, shot 2 days ago'. If you recieve a messaged about an item being traded in your area, text 'Interested in: listing_id' example 'Interested in: 3'." ) return HttpResponse(response) # Add a text message #msg = response.message(str(phone_number)) return HttpResponse(str(response))
def test_blank_decompose_function(self): request = self.factory.post( '/test_app/decorators/verb_view', ) response = decompose(request) self.assertEquals(response.type, 'unknown')
def sms_choices(request): twilio_request = decompose(request) contact_num = twilio_request.from_ response = twilio_request.body resp = MessagingResponse() contact_info = [ 'Thanks for your subscription, What is your age?', 'What is your annual income?', 'Do you have a vehicle?', 'Is your car insured?', 'Does your whole family have medical insurance?', 'Does your household have dental insurance?', ] # 'Create Contacts object' contact, created = Contacts.objects.get_or_create( customer_number=contact_num) # 'Send and record last sent sms' if created: resp.message(contact_info[0]) contact.last_sms = '0' contact.save() # 'Contact age parameter' elif not created: if contact.last_sms == '0': if response.isnumeric() is True: contact.customer_age = response resp.message(contact_info[1]) contact.last_sms = '1' contact.save() elif response.isnumeric() is False: resp.message('Tell me your age using only numbers') contact.last_sms = '0' contact.save() # 'Contact annual income parameter' elif contact.last_sms == '1': if response.isnumeric() is True: contact.customer_income = response resp.message(contact_info[2]) contact.last_sms = '2' contact.save() elif response.isnumeric() is False: resp.message( 'Give me an estimate of your annual income using only numbers' ) contact.last_sms = '1' contact.save() # 'Contact car parameter' elif contact.last_sms == '2': if response.lower() == 'yes': contact.has_car = True resp.message(contact_info[3]) contact.last_sms = '3' contact.save() elif response.lower() == 'no': contact.has_car = False resp.message(contact_info[4]) contact.last_sms = '4' contact.save() else: resp.message('Please respond with yes or no') contact.last_sms = '2' contact.save() # 'Contact car insurance parameter' elif contact.last_sms == '3': if response.lower() == 'no': contact.car_insurance = False resp.message(contact_info[4]) contact.last_sms = '4' contact.save() elif response.lower() == 'yes': contact.car_insurance = True resp.message(contact_info[4]) contact.last_sms = '4' contact.save() else: resp.message('Please respond with yes or no') contact.last_sms = '3' contact.save() # 'Contact med_insurance parameter' elif contact.last_sms == '4': if response.lower() == 'no': contact.med_insurance = False resp.message(contact_info[5]) contact.last_sms = '5' contact.save() elif response.lower() == 'yes': contact.med_insurance = True resp.message(contact_info[5]) contact.last_sms = '5' contact.save() else: resp.message('Please respond with yes or no') contact.last_sms = '4' contact.save() # 'Contact dental_insurance parameter' elif contact.last_sms == '5': if response.lower() == 'no': contact.dental_insurance = False contact.last_sms = '6' resp.message( 'Thank you for participation. As more services become available, we will be in touch' ) contact.save() elif response.lower() == 'yes': contact.dental_insurance = True contact.last_sms = '6' resp.message( 'Thank you for participation. As more services become available, we will be in touch' ) contact.save() else: resp.message('Please respond with yes or now') contact.last_sms = '5' contact.save() elif contact.last_sms == '6': resp.message( 'Thank you for participation. As more services become available, we will be in touch' ) contact.save() # 'If a number isn't in the database and server cant create object' else: resp.message("Our apologizes, your number isn't registered. " "Please visit www.Glpsmemphis.com to register") print(contact_num, contact.last_sms, response) return resp
def inbound_view(request): response = MessagingResponse() # Create a new TwilioRequest object twilio_request = decompose(request) # See the Twilio attributes on the class twilio_request.to print(twilio_request.__dict__) body_text = twilio_request.body broken_text = body_text.split() print(broken_text[0]) if (broken_text[0] == 'hello') or (broken_text[0] == 'Hello'): NewUser = MandexUser(username=broken_text[-1], phone=twilio_request.from_, time=datetime.datetime.now(), ils_balance=100, gdd_balance=100) NewUser.save() response.message("""Welcome to MandaX!\n Your balance is:\n 100 ils\n 100 gdd\n send 'commands' for commands""") elif (broken_text[0] == 'commands') or (broken_text[0] == 'Commands'): response.message("""Send 'commands' for commands.\n Send 'get balance' to view funds'\n Send 'send <quantity> <currency> to <name>' \n eg. 'send 20 ils to mordechai' \n send 'exchange <quantity> <currency> to <currency>'\n eg. 'exchange 20 ils to gdd'""") elif (broken_text[0] == 'send') or (broken_text[0] == 'Send'): print(twilio_request.__dict__) body_text = twilio_request.body broken_text = body_text.split() print(broken_text[0]) sender_get = MandexUser.objects.filter(phone=twilio_request.from_) for e in sender_get: sender_data = e reciever_get = MandexUser.objects.filter(username=broken_text[4]) for e in reciever_get: reciever_data = e if broken_text[2] == "ils": sender_data.ils_balance -= int(broken_text[1]) reciever_data.ils_balance += int(broken_text[1]) sender_balance = sender_data.ils_balance reciever_balance = reciever_data.ils_balance elif broken_text[2] == "gdd": sender_data.gdd_balance -= int(broken_text[1]) reciever_data.gdd_balance += int(broken_text[1]) sender_balance = sender_data.gdd_balance reciever_balance = reciever_data.gdd_balance sender_data.save() reciever_data.save() NewTransaction = Transaction(sent_from=twilio_request.from_, sent_to=broken_text[4], time=datetime.datetime.now(), quantity=broken_text[1], currency=broken_text[2]) NewTransaction.save() response.message( """you have sent %s %s to %s, your new balance is %s %s""" % (broken_text[1], broken_text[2], broken_text[4], sender_balance, broken_text[2])) client = Client('ACefad70b4197645889c4d677a6510820c', '2cd5a87702b8b85eacfc70a684a5f551') message = client.messages \ .create( body="You have recieved %s %s from %s. Your new balance is %s %s" % (broken_text[1], broken_text[2], twilio_request.from_, reciever_balance, broken_text[2]), from_='+972527288545', to=reciever_data.phone ) print(message.sid) elif (broken_text[0] == 'exchange') or (broken_text[0] == 'Exchange'): #NewTransaction = Transaction(user = twilio_request.from_, #origin_quantity = broken_text[1], #origin_currency = broken_text[2], #destination_quantity = int(broken_text[1]), #destination_currency = broken_text[3]) #NewTransaction.save() sender_get = MandexUser.objects.filter(phone=twilio_request.from_) print(len(sender_get)) for e in sender_get: sender_data = e if broken_text[2] == "ils": sender_data.ils_balance -= int(broken_text[1]) print(sender_data.gdd_balance) sender_data.gdd_balance += int(broken_text[1]) print(sender_data.ils_balance) elif broken_text[2] == "gdd": sender_data.gdd_balance -= int(broken_text[1]) print(sender_data.gdd_balance) sender_data.ils_balance += int(broken_text[1]) print(sender_data.ils_balance) sender_data.save() response.message( """You have exchanged %s %s for %s %s. Your new balance is %s ils and %s gdd""" % (broken_text[1], broken_text[2], broken_text[1], broken_text[4], sender_data.ils_balance, sender_data.gdd_balance)) elif (broken_text[0] == 'get') or (broken_text[0] == 'Get'): data_get = MandexUser.objects.filter(phone=twilio_request.from_) for e in data_get: data_row = e response.message( """hello %s ils balance: %s \n gdd balance: %s""" % (data_row.username, data_row.ils_balance, data_row.gdd_balance)) elif (broken_text[0] == 'thank') or (broken_text[0] == 'Thank'): response.message("You're Welcome!.") else: response.message( "Sorry but your command was not recognized. Send 'Commands' for commands." ) return response
def test_blank_get_decompose_function(self): request = self.factory.get( '/test_app/decorators/verb_view?messageSid=ACXXXX', ) response = decompose(request) self.assertEquals(response.type, 'message')
def test_sms_decompose_function(self): request = self.factory.post('/test_app/decorators/verb_view', self.message_dict) response = decompose(request) self.assertEquals(response.type, 'message')
def test_blank_decompose_function(self): request = self.factory.post('/test_app/decorators/verb_view', ) response = decompose(request) self.assertEquals(response.type, 'unknown')
def parse_sms(request): response = MessagingResponse() twilio_request = decompose(request) print(twilio_request.body) return MessagingResponse()