def text_back(url, phone_number): try: connections = lookup_connections(backend="kannel-gsm-modem", identities=[phone_number]) send(url, connections=connections) except Exception as ex: logger.warn(ex)
def form_valid(self,form): connection = lookup_connections('envaya',[form.cleaned_data['phone_number']])[0], text = form.cleaned_data['message'] send(text,connection) return HttpResponse("<pre>%s</pre>"%(pprint.pformat(form.cleaned_data),))
def forward (message, identity, text): if message.connection: conn = Connection(backend = message.connection.backend, identity = identity) send( text, conn) #print conn, text return True else: return False
def send(self): """ Raises an exception to help developers upgrade legacy code to use the new interface for sending messages. """ # TODO decide if this API is deprecated and add a deprecation warning if so from rapidsms.router import send send(self.text, self.connection) self.sent = True
def forward (message, identity, text): if message.connection: conn, created = Connection.objects.get_or_create(backend = message.connection.backend, identity = identity) send( text, conn) #print conn, text return True else: return False
def forward(message, identity, text): if message.connection: conn, created = Connection.objects.get_or_create( backend=message.connection.backend, identity=identity) send(text, conn) #print conn, text return True else: return False
def forward(message, identity, text): if message.connection: conn = Connection(backend=message.connection.backend, identity=identity) send(text, conn) #print conn, text return True else: return False
def send_batch(self,message,connections,verbose=True): ''' Send a single message to a list of connections ''' self.write("Sending: %s"%self.options['send'],verbose=verbose) self.write("Messages to Send: %i"%len(connections),verbose=verbose) self.write('Message: %s'%message) for i,conn in enumerate(connections): self.write(' %i: %s'%(i+1,conn),verbose=verbose) if self.options['send']: send(message,conn)
def process_incoming(self, msg): """ Process message through incoming phases and pass any generated responses to :func:`send <rapidsms.router.send>`. Called by ``receive_incoming``. :param msg: :class:`IncomingMessage <rapidsms.messages.incoming.IncomingMessage>` object """ from rapidsms.router import send continue_processing = self.process_incoming_phases(msg) if continue_processing: for msg_context in msg.responses: send(**msg_context)
def forward (identity, text): try: if text and identity: try: backend = Backend.objects.filter(name = settings.PRIMARY_BACKEND)[0] except: backend = Backend.objects.filter(name = 'message_tester')[0] #print backend conn = Connection(backend = backend, identity = identity) send(text, conn) return True except: #print e return False pass
def index(request): phone_number = request.GET.get('phone_number', '') message = request.GET.get('message', '') sent_identity = phone_number backend_to_use = choose_backend(phone_number) conn, created = Connection.objects.get_or_create(identity=sent_identity, backend=backend_to_use) send(message, conn) return HttpResponse("Message sent to: %s, Content: %s" % (phone_number, message))
def handle(request): body = json.loads(request.body.decode()) instance_id = int(body['instance_id']) message = str(body['message']) participant = ParticipantModel.objects.get(instance_id=instance_id) send( message, lookup_connections(backend='twilio-backend', identities=[participant.phone_number])) return HttpResponse()
def _split_and_send_messages(self, msg, msg_type): width = settings.MAX_OUTGOING_LENGTH - settings.MSG_ORDER_NUMBER_LENGTH short_msgs = textwrap.wrap(msg.raw_text, width=width) for i, short_msg in enumerate(short_msgs): # format the msg with a paginator syntax at end of msg short_text = u"[%d/%d] %s" % (i + 1, len(short_msgs), short_msg) # RapidSMS has a 'fields' kwarg for extra metadata # Keep track of the fact that this is a split message # Keep track of the sequence of this message # Keep track of the proper msg_type fields = {'split': True, 'order': i + 1, 'msg_type': msg_type} kwargs = {"fields": fields} if i == 0: kwargs['in_response_to'] = msg.in_response_to send(short_text, msg.connections, **kwargs)
def test_outgoing(self): """Sent messages should call _queue_message with incoming=False""" with patch.object(CeleryRouter, '_queue_message') as mock_method: connections = self.lookup_connections(identities=['1112223333']) messages = send("test", connections) mock_method.assert_called_once_with(messages[0], incoming=False)
def test_send_with_connection(self): """Send accepts a single connection.""" connection = self.create_connection() message = send("echo hello", connection) self.assertEqual(message.connection.identity, connection.identity) self.assertEqual(message.connection.backend.name, connection.backend.name)
def test_send_with_connections(self): """Send accepts a list of connections.""" connections = [self.create_connection(), self.create_connection()] message = send("echo hello", connections) self.assertEqual(len(message.connections), 2) self.assertEqual(message.connection.identity, connections[0].identity) self.assertEqual(message.connection.backend.name, connections[0].backend.name)
def send_msg_scheduled_events(): """ Send messages to contacts that are eligible for scheduled events. """ contact_all = Contact.objects.all() scheduled_events_all = ScheduledEvent.objects.all() connections_to_send = Connection.objects.none() for event in scheduled_events_all: connections_to_send = Connection.objects.none() for contact in contact_all: if (event.event_date - contact.date_of_birth).days >= event.days: contact_conn = Connection.objects.filter(contact=contact) connections_to_send = connections_to_send | contact_conn for conn in connections_to_send: send(event.msg_to_send, conn)
def start_survey(plugin_id, owner_id, token, url, survey_id, instance_id): # make call to start survey print("Parameters::", plugin_id, owner_id, token, url, survey_id, instance_id) data = {'action': 'start'} a = owner_id + "-" + plugin_id + ":" + token b64 = base64.b64encode(a.encode()).decode() headers = {"Authorization": "Basic " + b64} requests.post(url + '/instances/' + str(instance_id), json.dumps(data), headers=headers) #get participant for survey params = "?survey_id=" + str(survey_id) + "&instance_id=" + str( instance_id) participant_request = requests.get(url + "/participants" + params, headers=headers) participant = json.loads(participant_request.text) participant_number = participant["participant"] p = ParticipantModel.objects.filter( phone_number=participant_number).first() if p is not None: p.delete() p = ParticipantModel(instance_id=instance_id, phone_number=participant_number, owner_id=int(owner_id)) p.save() first_question = requests.get(url + '/instances/' + str(instance_id) + "/latest", headers=headers) question_text = json.loads(first_question.text)["question_text"] send( question_text, lookup_connections(backend="twilio-backend", identities=[participant_number]))
def send(self, sender=None, group=None): message = self.cleaned_data['message'] text = "{0}: {1}".format(sender, message) recipients = set([contact.default_connection for contact in group.contacts.all()]) sent = send(text, list(recipients)) GroupMessage.objects.create(group=group, message=sent.logger_msg, num_recipients=len(recipients)) return sent
def test_sending_sms(self): """ Tests that SMS-es are actually sent using the Nexmo outgoing backend. """ try: from django.conf import settings except ImportError: self.fail(msg="No TEST_NUMBER found in settings!") from rapidsms.router import send from rapidsms.models import Connection, Backend from random import randint b = Backend.objects.get_or_create(name='envaya_nexmo')[0] c = Connection.objects.get_or_create(identity = settings.TEST_NUMBER, backend = b)[0] msg = "Hey, this is a test message from NexmoOutgoingBackendTest! \n Your Lucky number is %s" % (randint(1,42)) send(msg,[c]) print "Cannot actually verify whether the message was sent or not because of the limitations of rapdisms framework :-/"
def training_materials_assign(request, pk=None): if pk: tm = get_object_or_404(TrainingMaterial, pk=pk) else: tm = TrainingMaterial() tm_form = AssignForm(instance=tm) if request.method == 'POST': data = {} for key in request.POST: val = request.POST[key] if isinstance(val, basestring): data[key] = val else: try: data[key] = val[0] except (IndexError, TypeError): data[key] = val del data if pk: tm_form = AssignForm(request.POST, instance=tm) else: tm_form = AssignForm(request.POST) if tm_form.is_valid(): tm = tm_form.save() assigned_users = tm_form.cleaned_data['assigned_users'] notification = 'You have been assigned %s. To begin, reply with START %s.' % (tm.title, tm.tag) #self.cleaned_data['text'] connections = [] #assigned_users = tm_form.cleaned_data['assigned_users'] for user in assigned_users: connections.append(user.default_connection) #connections = self.cleaned_data['assigned_users'] send(notification, connections) #send(tm, assigned_users) tm.save() messages.add_message(request, messages.INFO, "Saved and sent training material.") return HttpResponseRedirect(reverse(training_materials)) return render(request, 'training_materials/tm_assign1.html', { "tm": tm, "tm_form": tm_form, "range": range(tm.messagenum),#"x"*tm.messagenum, })
def send_occurrence_notifications(days=7): """ Task to send reminders notifications for upcoming Occurrence Arguments: days: The number of upcoming days to filter upcoming Occurrences """ start = datetime.date.today() end = start + datetime.timedelta(days=days) blacklist = [Notification.STATUS_PENDING, Notification.STATUS_COMPLETED, Notification.STATUS_MANUAL] appts = Occurrence.objects.filter( # Join subscriptions that haven't ended Q(Q(subscription__connection__timelines__end__gte=now()) | Q(subscription__connection__timelines__end__isnull=True)), subscription__connection__timelines__timeline=F('milestone__timeline'), # Filter occurrences in range date__range=(start, end), ).exclude(actions__status__in=blacklist) for appt in appts: # TODO allow both static messages AND appointment reminders for a # milestone language = get_language() msg = None translations = appt.milestone.translations.filter( language_code=getattr(settings, 'DEFUALT_LANGUAGE', 'en')) # each Timeline subscription can have a default language if translations: msg = translations[0].message if not msg: try: # if milestone has a default static message, fire away msg = appt.milestone.message except: pass if not msg: # format message as an appointment reminder msg = APPT_REMINDER % {'date': appt.date, 'pin': appt.subscription.pin} send(msg, appt.subscription.connection) Notification.objects.create(occurrence=appt, status=Notification.STATUS_PENDING, attempted=now(), message=msg)
def handle(self,slug,text): """Broadcast message in a village group""" try: group = Group.objects.get(groupname=slug.strip()) except Group.DoesNotExist: self.respond("Group Does not Exist") else: connection = self.msg.connections[0] contacts = Contact.objects.filter(member__group=group) if not contacts.filter(connection__pk=connection.pk): self.respond('You are not a member of this group') else: contact_name = contacts.get(connection__pk=connection.pk) connections = Connection.objects.filter(contact__in=contacts, backend=connection.backend,).exclude(pk=connection.pk) count = connections.count if count: send('From %s(%s): %s' % (contact_name.name,slug,text), connections=connections) else: self.respond('Message was sent to %s member%s.' % (count, count != 1 and 's' or ''))
def send_msg_general_events(): """ Send messages to contacts that become eligible for general events. """ contact_all = Contact.objects.all() gen_events_all = GeneralEvent.objects.all() connections_to_send = Connection.objects.none() curr_date = date.today() for event in gen_events_all: connections_to_send = Connection.objects.none() for contact in contact_all: if (curr_date - contact.date_of_birth).days == event.days: contact_conn = Connection.objects.filter(contact=contact) connections_to_send = connections_to_send | contact_conn for conn in connections_to_send: send(event.msg_to_send, conn)
def handle(self, slug, text): """Broadcast messages to users in a group.""" try: group = Group.objects.get(slug=slug) except Group.DoesNotExist: self.respond('Unknown group id "%s"' % slug.strip()) else: # Check for membership connection = self.msg.connections[0] contacts = Contact.objects.filter(member__group=group) if not contacts.filter(connection__pk=connection.pk): self.respond('You are not a member of this group.') else: connections = Connection.objects.filter( contact__in=contacts, backend=connection.backend, ).exclude(pk=connection.pk) count = connections.count() if count: send('From %s: %s' % (slug, text), connections=connections) self.respond('Message was sent to %s member%s.' % ( count, count != 1 and 's' or ''))
def handle(self, slug, text): """Broadcast messages to users in a group.""" try: group = Group.objects.get(slug=slug) except Group.DoesNotExist: self.respond('Unknown group id "%s"' % slug.strip()) else: # Check for membership connection = self.msg.connections[0] contacts = Contact.objects.filter(member__group=group) if not contacts.filter(connection__pk=connection.pk): self.respond('You are not a member of this group.') else: connections = Connection.objects.filter( contact__in=contacts, backend=connection.backend, ).exclude(pk=connection.pk) count = connections.count() if count: send('From %s: %s' % (slug, text), connections=connections) self.respond('Message was sent to %s member%s.' % (count, count != 1 and 's' or ''))
def send_appointment_notifications(days=7): """ Task to send reminders notifications for upcoming Appointment Arguments: days: The number of upcoming days to filter upcoming Appointments """ start = now() end = (start + datetime.timedelta(days=days)).replace(hour=23, minute=59, second=59) # get all subscriptions that haven't ended query = Q(date__gte=start) & Q(date__lte=end) blacklist = [Notification.STATUS_SENT, Notification.STATUS_CONFIRMED, Notification.STATUS_MANUAL] appts = Appointment.objects.filter(query).exclude(notifications__status__in=blacklist) for appt in appts: msg = APPT_REMINDER % {'date': appt.date} send(msg, appt.connection) Notification.objects.create(appointment=appt, status=Notification.STATUS_SENT, sent=now(), message=msg)
def send_appointment_notifications(days=7): """ Task to send reminders notifications for upcoming Appointment Arguments: days: The number of upcoming days to filter upcoming Appointments """ start = datetime.date.today() end = start + datetime.timedelta(days=days) blacklist = [Notification.STATUS_SENT, Notification.STATUS_CONFIRMED, Notification.STATUS_MANUAL] appts = Appointment.objects.filter( # Join subscriptions that haven't ended Q(Q(subscription__connection__timelines__end__gte=now()) | Q(subscription__connection__timelines__end__isnull=True)), subscription__connection__timelines__timeline=F('milestone__timeline'), # Filter appointments in range date__range=(start, end), ).exclude(notifications__status__in=blacklist) for appt in appts: msg = APPT_REMINDER % {'date': appt.date} send(msg, appt.subscription.connection) Notification.objects.create(appointment=appt, status=Notification.STATUS_SENT, sent=now(), message=msg)
def send_queued_messages(): """ Send messages which have been queued for delivery. """ messages = BroadcastMessage.objects.filter(status="queued")[:50] logger.info("Found {0} message(s) to send".format(messages.count())) for message in messages: connection = message.recipient.default_connection try: msg = send(message.broadcast.body, connection)[0] except Exception, e: msg = None logger.exception(e) if msg: logger.debug("Message sent successfully!") message.status = "sent" message.date_sent = get_now() else: logger.debug("Message failed to send.") message.status = "error" message.save()
def send(self): message = self.cleaned_data['message'] connections = self.cleaned_data['connections'] return send(message, connections)
def send(self): """Send the message. Equivalent to ``rapidsms.router.send(text, connections)``. """ from rapidsms.router import send send(self.text, self.connections)
def send(self, text, connections): """send() API wrapper.""" return send(text, connections)
def send(self): for recipient in self.cleaned_data['recipients']: send(self.cleaned_data['text'], recipient.default_connection) return self.cleaned_data['recipients']
def send(self, text, connections, **kwargs): """A wrapper around the ``send`` API. See :ref:`sending-messages`.""" return send(text, connections, **kwargs)
def send_message(self): investigator = Investigator(mobile_number=self.mobile_number) investigator.backend = Backend.objects.all()[0] send(self.text_message(), [investigator])
def form_valid(self, form): send(form.cleaned_data['message'], Connection.objects.filter(backend=form.cleaned_data['backend'])) messages.success(self.request, "Bulk message sent successfully.") return super(SendBulkMessage, self).form_valid(form)
def handle(self, backend_name, text): connections = Connection.objects.filter(backend__name=backend_name) send(text, connections)
def send(self): """Send the message. Equivalent to ``rapidsms.router.send(text, connections)``. """ from rapidsms.router import send send(self.text, self.connection)
def sms_investigators_in_locations(cls, locations, text): investigators = [] for location in locations: investigators.extend(Investigator.lives_under_location(location)) send(text, investigators)
def lang_broadcast(): connections = Connection.objects.all() for lang, conns in trans_helpers.group_connections(connections): with translation.override(lang): send(_('hello'), conns)