def default(self, message): # In the default phase, after everyone has had a chance to deal # with this message, check if it might be a response to a previous # blast, and if so pass along to the original sender if message.contact: window = datetime.utcnow() - timedelta(hours=self.BLAST_RESPONSE_WINDOW_HOURS) broadcasts = BroadcastMessage.objects.filter\ (date__gte=window, recipients=message.contact) if broadcasts.count() > 0: latest_broadcast = broadcasts.order_by("-date")[0] if not latest_broadcast.contact.default_connection: self.info("Can't send to %s as they have no connections" % \ latest_broadcast.contact) message.respond(NO_CONTACT, sender=message.contact.name, recipient=latest_broadcast.contact) else: response = OutgoingMessage(latest_broadcast.contact.default_connection, "%(text)s [from %(user)s]", **{"text": message.text, "user": message.contact.name}) response.send() logger_msg = getattr(response, "logger_msg", None) if not logger_msg: self.error("No logger message found for %s. Do you have the message log app running?" %\ message) BroadcastResponse.objects.create(broadcast=latest_broadcast, contact=message.contact, text=message.text, logger_message=logger_msg) return True
def send_notifications(self): """ send queued for delivery messages """ notifications = reminders.SentNotification.objects.filter( status="queued", date_to_send__lt=datetime.datetime.now() ) count = notifications.count() if count > 0: self.info("found {0} notification(s) to send".format(count)) for notification in notifications: connection = notification.recipient.default_connection if not connection: self.debug("no connection found for recipient {0}, unable " "to send".format(notification.recipient)) continue msg = OutgoingMessage(connection=connection, template=notification.message) success = True try: msg.send() except Exception, e: self.exception(e) success = False if success and (msg.sent or msg.sent is None): self.debug("notification sent successfully") notification.status = "sent" notification.date_sent = datetime.datetime.now() else: self.debug("notification failed to send") notification.status = "error" notification.save()
def reimburse(): ''' Start reimbursement process, entailing interaction with special numbers ''' counter = 0 network_name_map = dict([(v, k) for k, v in NAME_NETWORK_MAP.items()]) reimbursements = ReimbursementRecord.objects.exclude( status__in=(ReimbursementRecord.COMPLETED, ReimbursementRecord.ERROR) ) #import pdb;pdb.set_trace() for network, _ in Subscriber.NETWORKS: print 'network: %s'%network if reimbursements.filter( status__in=( ReimbursementRecord.IN_PROGRESS, ReimbursementRecord.QUEUED), subscriber__network=network): continue else: #there is no reimbursement in progress for "network" subscribers = Subscriber.objects.filter(balance__gt=0, network=network) min_time = settings.REIMBURSEMENT_MIN_TIME qualified = qualify(subscribers, min_time) if qualified: subscriber = qualified[0] else: continue network_name = network_name_map.get(network) _amount = max(subscriber.balance, settings.MINIMUM_TRANSFERS.get(network_name)) backend_name = subscriber.get_backend() backend, _ = Backend.objects.get_or_create(name=backend_name) text = subscriber.first_message % { 'number': '0%s'%subscriber.number[-10:], 'amount': _amount, 'pin': settings.NETWORK_PINS.get(network_name) } logging.info('message to send is %s'%text) to_number = REIMBURSEMENT_NUMBERS.get(network_name) if len(to_number) < 11:#If it is a short-code, prefix with 's' to_number = 's%s'%to_number connection, _ = Connection.objects.get_or_create( backend=backend, identity=to_number) msg = OutgoingMessage(connection=connection, template=text) try: msg.send() except: router = Router() #router.start() router.outgoing(msg) ReimbursementRecord.objects.create( subscriber=subscriber, amount=_amount, status=ReimbursementRecord.IN_PROGRESS) counter += 1 return counter
def fake_pending_results(self, clinic): """Notifies clinic staff that results are ready via sms, except this is fake!""" contacts = Contact.active.filter(types=const.get_clinic_worker_type()).location(clinic) results = get_fake_results(3, clinic) for contact in contacts: msg = OutgoingMessage(connection=contact.default_connection, template=RESULTS_READY, name=contact.name, count=len(results)) msg.send() self._mark_results_pending(results, msg.connection)
def fake_pending_results(self, clinic): """Notifies clinic staff that results are ready via sms, except this is fake!""" contacts = Contact.active.filter( types=const.get_clinic_worker_type()).location(clinic) results = get_fake_results(3, clinic) for contact in contacts: msg = OutgoingMessage(connection=contact.default_connection, template=RESULTS_READY, name=contact.name, count=len(results)) msg.send() self._mark_results_pending(results, msg.connection)
def process_queue(router): logger.debug('processing queue') # queued messages messages = OutgoingLog.objects.filter(status=OutgoingLog.QUEUED)[:10] for message in messages: logger.debug('Processing message: %s', message) conn, _ = Connection.objects.get_or_create(identity=message.identity, backend=message.backend) msg = OutgoingMessage(conn, message.text) msg.send() message.status = str(OutgoingLog.DELIVERED) message.save()
def send_appointment_reminder(patient, default_conn=None, pronouns=None): if pronouns is None: pronouns = {} logger.info('Sending appointment reminder for %s' % patient) if patient.location: logger.debug('using patient location (%s) to find CBAs' % patient.location) # if the cba was registered, we'll have a location on # the patient and can use that information to find the CBAs to whom # we should send the appointment reminders # TODO: also check child locations? connections = list(Connection.objects.filter( contact__types__slug=const.CBA_SLUG, contact__location=patient.location, contact__is_active=True)) logger.debug('found %d CBAs to deliver reminders to' % len(connections)) elif default_conn: logger.debug('no patient location; using default_conn') # if the CBA was not registered, just send the notification to the # CBA who logged the event connections = [default_conn] else: logger.debug('no patient location or default_conn; not sending any ' 'reminders') for connection in connections: if connection.contact: cba_name = ' %s' % connection.contact.name else: cba_name = '' if patient.location: if patient.location.type == const.get_zone_type() and\ patient.location.parent: clinic_name = patient.location.parent.name else: clinic_name = patient.location.name else: clinic_name = 'the clinic' msg = OutgoingMessage(connection, _("Hello%(cba)s. %(patient)s is due " "for their next clinic appointment. Please " "deliver a reminder to this person and ensure " "they visit %(clinic)s within 3 days."), cba=cba_name, patient=patient.name, clinic=clinic_name) msg.send() return connections
def _send_message(self, contact, text): """Send message through connection associated with this contact""" if not contact.default_connection: return False message = OutgoingMessage(contact.default_connection,text) return message.send()
def ajax_POST_test(self, get, post): form = MessageForm(post) if form.is_valid(): contact = form.cleaned_data["contact"] message = form.cleaned_data["message"] phone = form.cleaned_data["phone"] backend = Backend.objects.get(name="clickatell") connection, _ = Connection.objects.get_or_create(contact=contact, identity=phone, backend=backend) message = OutgoingMessage(connection, message) return message.send()
def ajax_POST_test(self, get, post): form = MessageForm(post) if form.is_valid(): contact = form.cleaned_data['contact'] message = form.cleaned_data['message'] phone = form.cleaned_data['phone'] backend = Backend.objects.get(name='clickatell') connection, _ = Connection.objects.get_or_create(contact=contact, identity=phone, backend=backend) message = OutgoingMessage(connection, message) return message.send()
def default(self, message): # In the default phase, after everyone has had a chance to deal # with this message, check if it might be a response to a previous # blast, and if so pass along to the original sender if message.contact: window = datetime.utcnow() - timedelta( hours=self.BLAST_RESPONSE_WINDOW_HOURS) broadcasts = BroadcastMessage.objects.filter\ (date__gte=window, recipients=message.contact) if broadcasts.count() > 0: latest_broadcast = broadcasts.order_by("-date")[0] if not latest_broadcast.contact.default_connection: self.info("Can't send to %s as they have no connections" % \ latest_broadcast.contact) message.respond(NO_CONTACT, sender=message.contact.name, recipient=latest_broadcast.contact) else: response = OutgoingMessage( latest_broadcast.contact.default_connection, "%(text)s [from %(user)s]", **{ "text": message.text, "user": message.contact.name }) response.send() logger_msg = getattr(response, "logger_msg", None) if not logger_msg: self.error("No logger message found for %s. Do you have the message log app running?" %\ message) BroadcastResponse.objects.create( broadcast=latest_broadcast, contact=message.contact, text=message.text, logger_message=logger_msg) return True
def _send_message(self, connection, message_body): '''Attempts to send a message through a given connection''' # attempt to send the message # TODO: what could go wrong here? msg = OutgoingMessage(connection, message_body) return msg.send()