def switchboard(): data = request.form.to_dict() sender = normalize_phonenumber(urllib.unquote(data['From'])) message = urllib.unquote_plus(data['Body']).strip().lower() # Get the users with the provided phone number and sort based # on the last time they posted a message users = cdw.users.with_fields( phoneNumber=sender).order_by('-lastPostDate') if len(users) == 0: msg = "SMS from unregistered phone number: %s" % sender current_app.logger.error(msg) abort(400, description=msg) def handle_message(user, message): if message in ['stop','unsubscribe']: cdwapi.stop_sms_updates(user) elif message in ['start','resume', 'subscribe']: cdwapi.resume_sms_updates(user) elif message in ['undo','stay']: cdwapi.revert_sms_updates(user) else: cdwapi.post_via_sms(user, message) return jsonify({ "success": True }) for user in users: if user.threadSubscription != None: return handle_message(user, message) abort(400, description="A user with this phone number was found " "but they did not have a subscription")
class TwilioService(object): def get_cv(self, key): return current_app.config['CDW']['twilio'][key] def send_message(self, message, sender, recipients=[], raise_queue_errors=False): if not current_app.config['CDW']['smsqueue']['use']: return self._do_send_message(message, sender, recipients) # Quick msg validation message = message.strip() if len(message) == 0: raise Exception("Message length must be greater than 0") try: host = current_app.config['CDW']['beanstalk']['host'] port = current_app.config['CDW']['beanstalk']['port'] beanstalk = beanstalkc.Connection(host=host, port=port) beanstalk.use(current_app.config['CDW']['smsqueue']['tube_name']) except Exception, e: current_app.logger.error('Could not connect to beanstalk at ' '%s:%s' % (host, port)) return msg_amt = 0 for recipient in recipients: try: beanstalk.put( str({ "account_id": self.get_cv('account_sid'), "auth_token": self.get_cv('auth_token'), "app_id": self.get_cv('app_id'), "sender": normalize_phonenumber(sender), "recipient": normalize_phonenumber(recipient), "message": message, })) msg_amt += 1 except Exception, e: current_app.logger.error('Could not add SMS message into ' 'beanstalk queue: %s' % e)
def kiosk_handler_post(id): try: # TODO: Add Twilio Validator kiosk_number = current_app.config['CDW']['kiosks']['kiosk_%s' % id] data = request.form.to_dict() phone = normalize_phonenumber(urllib.unquote(data['From'])) message = urllib.unquote_plus(data['Body']).strip() msg = cdwapi.save_incoming_sms(kiosk_number, phone, message) return jsonify(msg) except Exception, e: current_app.logger.error("Error receiving message from " "Twilio: %s" % e) raise e