def message(): """ Handle incoming USSD messages, passed as HTTP requests via the vumi HTTP API. """ logger.debug("MESSAGE endpoint called") # TODO: filter out service messages, such as "content": "state: wait_ussrc" if request.method == 'POST': tmp = request.get_json() msg = VumiMessage(tmp) if msg.content == "state: wait_ussrc": logger.debug("End of session message received.") else: logger.debug(msg) try: user_id = msg.from_addr # user's cellphone number content = msg.content # selected menu item, if any mark_online(user_id) selected_item = None try: selected_item = int(content) except (ValueError, TypeError): pass reply_content = generate_output(user_id, selected_item) if app.debug: logger.debug(reply_content) else: msg.reply(reply_content) except Exception as e: logger.exception(e) pass return make_response("OK")
def update_notification_list(number, add_or_remove="add"): """ Add / Remove a user's number from the list of numbers to be notified when sending updates. """ try: # read list from JSON file with app.open_instance_resource('notification_list.json', mode='r') as f: try: notification_list = json.loads(f.read()) except ValueError as e: # start with clean list, if the file does not yet contain a list notification_list = [] pass # add / remove item if add_or_remove == "add": if not number in notification_list: notification_list.append(number) elif add_or_remove == "remove": if number in notification_list: i = notification_list.index(number) notification_list = notification_list[0:i] + notification_list[i+1::] # write updated list to file with app.open_instance_resource('notification_list.json', mode='w') as f: f.write(json.dumps(notification_list, indent=4)) except Exception as e: if add_or_remove == "add": logger.exception("Error saving number to the notification list.") else: logger.exception("Error removing number from the notification list.") return
def on_model_change(self, form, model, is_created): # send SMS notifications before saving message to database msg = VumiMessage({"content": model.content}) count_tot = 0 model.user = current_user try: with app.open_instance_resource('notification_list.json', mode='r') as f: try: notification_list = json.loads(f.read()) except ValueError: # start with clean list, if the file does not yet contain a list notification_list = [] pass for number in notification_list: logger.debug("sending update to: " + number) msg.send(number) count_tot += 1 model.notes = "Update sent to " + str(count_tot) + " user(s)." except Exception: tmp = "Error sending update broadcast via SMS." logger.exception(tmp) model.notes = tmp return
def __init__(self, msg_dict): try: self.msg_type = msg_dict["transport_type"] # either 'ussd' or 'sms' self.content = msg_dict["content"] self.message_id = msg_dict["message_id"] self.conversation_key = msg_dict["helper_metadata"]["go"]["conversation_key"] self.from_addr = msg_dict["from_addr"] self.timestamp = msg_dict["timestamp"] # e.g. "2013-12-02 06:28:07.430549" self.datetime = datetime.strptime(self.timestamp, "%Y-%m-%d %H:%M:%S.%f") except ValueError, e: logger.exception("Could not create VumiMessage instance.")
def get_user_menu(user_id): """ Retrieve stored session info. """ menu_marker = redis.get('user-menu/%s' % user_id) if not menu_marker in [None, 'None']: # the serializer may return a string try: # ensure the retrieved item can be converted to int tmp = int(menu_marker) except Exception: logger.exception("Bad session data encountered.") menu_marker = None pass return menu_marker
def message(): """ Handle incoming messages, passed as HTTP requests via the vumi HTTP API. """ logger.debug("MESSAGE endpoint called") try: tmp = request.get_json() msg = VumiMessage(tmp) if hasattr(msg, 'content') and msg.content == "state: wait_ussrc": logger.debug("End of session message received.") else: logger.debug(msg.msg_type + " message received.") if msg.msg_type == "ussd": user_id = msg.from_addr # user's cellphone number content = msg.content # selected menu item, if any mark_online(user_id) selected_item = None try: selected_item = int(content) except (ValueError, TypeError): pass logger.debug(selected_item) reply_content = generate_output(user_id, selected_item) if "Your number has been added to the list." in reply_content: update_notification_list(msg.from_addr, "add") msg.send_reply(reply_content) elif msg.msg_type == "sms": msg.save_query() tmp = "Thank you for submitting your query. It will be attended to as soon as possible." msg.send_reply(tmp) else: logger.error("Incorrect message type encountered.") except Exception as e: logger.exception(e) raise return make_response("OK")
def __init__(self, msg_dict): # TODO: init an empy object, and populate it in separate methods if msg_dict.get('query_id'): try: qry = Query.query.get(msg_dict['query_id']) self.query_id = qry.query_id self.message_id = qry.vumi_message_id self.msg_type = "sms" self.content = qry.content self.conversation_key = qry.conversation_key self.from_addr = qry.from_addr self.timestamp = datetime.strftime(self.datetime, '%Y-%m-%d %H:%M:%S.%f') self.datetime = qry.datetime except Exception: logger.exception("Could not load specified Query record.") else: try: if msg_dict.get('message_id'): self.message_id = msg_dict['message_id'] if msg_dict.get('transport_type'): self.msg_type = msg_dict['transport_type'] # either 'ussd' or 'sms' if msg_dict.get('content'): self.content = msg_dict['content'] else: self.content = None if msg_dict.get('helper_metadata'): self.conversation_key = msg_dict['helper_metadata']['go']['conversation_key'] else: self.conversation_key = app.config['CONVERSATION_KEY'] if msg_dict.get('from_addr'): self.from_addr = msg_dict['from_addr'] if msg_dict.get('timestamp'): self.timestamp = msg_dict['timestamp'] # e.g. "2013-12-02 06:28:07.430549" self.datetime = datetime.strptime(self.timestamp, '%Y-%m-%d %H:%M:%S.%f') except Exception as e: logger.exception("Could not create VumiMessage instance.") raise return
def __init__(self, msg_dict): # TODO: init an empy object, and populate it in separate methods if msg_dict.get("query_id"): try: qry = Query.query.get(msg_dict["query_id"]) self.query_id = qry.query_id self.message_id = qry.vumi_message_id self.msg_type = "sms" self.content = qry.content self.conversation_key = qry.conversation_key self.from_addr = qry.from_addr self.timestamp = datetime.strftime(self.datetime, "%Y-%m-%d %H:%M:%S.%f") self.datetime = qry.datetime except Exception: logger.exception("Could not load specified Query record.") else: try: if msg_dict.get("message_id"): self.message_id = msg_dict["message_id"] if msg_dict.get("transport_type"): self.msg_type = msg_dict["transport_type"] # either 'ussd' or 'sms' if msg_dict.get("content"): self.content = msg_dict["content"] else: self.content = None if msg_dict.get("helper_metadata"): self.conversation_key = msg_dict["helper_metadata"]["go"]["conversation_key"] else: self.conversation_key = VUMI_CONVERSATION_KEY if msg_dict.get("from_addr"): self.from_addr = msg_dict["from_addr"] if msg_dict.get("timestamp"): self.timestamp = msg_dict["timestamp"] # e.g. "2013-12-02 06:28:07.430549" self.datetime = datetime.strptime(self.timestamp, "%Y-%m-%d %H:%M:%S.%f") except Exception as e: logger.exception("Could not create VumiMessage instance.") raise return