def fakeIncoming(self, message, connection=None): if connection is None: connection = Connection.objects.all()[0] # if so, process it incomingmessage = IncomingMessage(connection, message) incomingmessage.db_message = Message.objects.create(direction='I', connection=connection, text=message) return incomingmessage
def fake_incoming_message(message, connection): incomingmessage = IncomingMessage(connection, message) #router = get_router() #router.handle_incoming(connection.backend.name, connection.identity, message) incomingmessage.db_message = Message.objects.create(direction='I', connection=connection, text=message) incomingmessage.db_message.handled_by = 'poll' return incomingmessage
def fakeIncoming(self, message, connection=None): if connection is None: connection = Connection.objects.all()[0] # if so, process it incomingmessage = IncomingMessage(connection, message) incomingmessage.db_message = Message.objects.create( direction='I', connection=connection, text=message) return incomingmessage
def test_outgoing_message_link(self): """Extra data should be attached to response (OutgoingMessage).""" connection = self.create_connection() fields = {'extra-field': 'extra-value'} message = IncomingMessage(connection, 'test incoming message', fields=fields) response = message.respond('response') self.assertEqual(message, response['in_response_to']) self.assertIn('extra-field', response['in_response_to'].fields)
def spoof_incoming_obj(self, message, connection=None): if connection is None: connection = Connection.objects.all()[0] incomingmessage = IncomingMessage(connection, message) incomingmessage.db_message = Message.objects.create( direction='I', connection=Connection.objects.all()[0], text=message) return incomingmessage
def test_outgoing_message_link(self): """Extra data should be attached to response (OutgoingMessage).""" connection = self.create_connection() fields = {'extra-field': 'extra-value'} message = IncomingMessage(connection, 'test incoming message', fields=fields) response = message.respond('response') self.assertEqual(message, response.in_reply_to) self.assertTrue('extra-field' in response.in_reply_to.fields)
def fake_error_submission(self, message, connection=None): form = XForm.find_form(message) if connection is None: connection = Connection.objects.all()[0] # if so, process it incomingmessage = IncomingMessage(connection, message) incomingmessage.db_message = Message.objects.create(direction='I', connection=Connection.objects.all()[0], text=message) if form: submission = form.process_sms_submission(incomingmessage) self.failUnless(submission.has_errors) return
def sendMessage(self, num, txt, date=None): if date is None: date = datetime.now() connection, _ = Connection.objects.get_or_create(backend=self.backend, identity=num) msg = IncomingMessage(connection, txt, date) self.router.receive_incoming(msg)
def fake_submission(self, message, connection=None): form = XForm.find_form(message) if connection is None: try: connection = Connection.objects.all()[0] except IndexError: backend, created = Backend.objects.get_or_create(name='test') connection, created = Connection.objects.get_or_create(identity='8675309', backend=backend) # if so, process it incomingmessage = IncomingMessage(connection, message) incomingmessage.db_message = Message.objects.create(direction='I', connection=connection, text=message) if form: submission = form.process_sms_submission(incomingmessage) return submission return None
def build(self, **kwargs): message_info = {'text': 'connect', 'connection': web_connection} incoming_message = IncomingMessage(**message_info) return incoming_message
def test_message_id(self): """All message objects should have IDs.""" connections = [self.create_connection()] msg = MessageBase(text="test", connections=connections) self.assertIsNotNone(msg.id) msg = IncomingMessage(text="test", connections=connections) self.assertIsNotNone(msg.id) msg = OutgoingMessage(text="test", connections=connections) self.assertIsNotNone(msg.id)
def test_saved_message_fields(self): """Extra data should be attached to IncomingMessage.""" connection = self.create_connection() fields = {'extra-field': 'extra-value'} message = IncomingMessage(connection, 'test incoming message', fields=fields) self.assertTrue('extra-field' in message.fields) self.assertEqual(message.fields['extra-field'], fields['extra-field'])
def create_incoming_message(self, data={}): """Create and return RapidSMS IncomingMessage object.""" defaults = { 'text': self.random_string(10), } defaults.update(data) if 'connections' not in defaults: defaults['connections'] = [self.create_connection()] return IncomingMessage(**defaults)
def test_backend_route(): router = MockRouter() backend = TwilioBackend(name="twilio", router=router, **basic_conf) router.start() Connection.objects.all().delete() conn = Connection.objects.create(backend=backend.model, identity='1112229999') message = IncomingMessage(conn, 'Hi', datetime.datetime.now()) assert_true(backend.route(message), True)
def handle(self, **options): if not options['poll_name']: poll_name = raw_input('Name of poll: ') if not options['group_name']: group_name = raw_input('Name of group: ') if not options['script_slug']: script_slug = raw_input('Script slug: ') try: poll = Poll.objects.get(name=poll_name) script = Script.objects.get(slug=script_slug) conns = EmisReporter.objects.filter(groups__name=group_name).\ filter(connection__identity__in=ScriptSession.objects.filter(script=script, end_time=None).\ values_list('connection__identity',flat=True)).\ values_list('connection__identity',flat=True) count = Message.objects.filter( direction='I', poll__responses=None, connection__identity__in=conns).count() reg_no = '^\\s*(no|nope|nah|nay|n)(\\s|[^a-zA-Z]|$)' regex_no = re.compile(reg_no, re.IGNORECASE) reg_yes = '^\\s*(yes|yeah|yep|yay|y)(\\s|[^a-zA-Z]|$)' regex_yes = re.compile(reg_yes, re.IGNORECASE) for m in Message.objects.filter(direction='I', poll__responses=None, connection__identity__in=conns): if regex_no.search(m.text.lower()) or regex_yes.search( m.text.lower() ): # brutally make sure YES or No is some variant of text _incoming_message = IncomingMessage(m.connection, m.text, received_at=m.date) self.process_response(poll, _incoming_message, m) count -= 1 if count % 20 == 0: #just for reporting purposes in terminal self.stdout.write( '\n%r - %r - %r (%r left) ' % (m.text, m.connection.identity, m.date, count)) self.stdout.write('\ndone correcting the response!!!') except MultipleObjectsReturned, DoesNotExist: raise DoesNotExist
def post(self, request, *args, **kwargs): backend, _ = Backend.objects.get_or_create(name='fake-backend') identity = 'web-{}'.format(request.session.session_key) connection, _ = Connection.objects.get_or_create(identity=identity, backend=backend) user_input = request.POST.get('user_input') msg = IncomingMessage(text=user_input, connection=connection) message_from_ben, answers = self.web_router.create_msg_from_ben(msg) return HttpResponse( json.dumps({ "text": message_from_ben, 'answers': answers }), content_type="application/json", )
def make_fake_message(request, patient_id): """Make up a message for the patient's wisepill device and fake it coming in""" logger.debug('make_fake_message') patient = get_object_or_404(Patient, pk=patient_id) msisdn = patient.wisepill_msisdn if not msisdn: messages.error(request, "Must set patient's MSISDN before we can fake a wisepill message from them") return redirect('patient-list') timestamp = datetime.datetime.now() # 50-50 whether to make a delayed message is_delayed = random.randint(0,99) > 50 if is_delayed: timestamp -= datetime.timedelta(minutes=10) delay_value = "03" if is_delayed else "02" # DDMMYYHHMMSS time_value = timestamp.strftime("%d%m%y%H%M%S") # 50-50 old format or new format new_format = random.randint(0,99) > 50 if new_format: start = "AT={delay_value},".format(**locals()) else: start = "@={delay_value},".format(**locals()) text = start + "CN={msisdn},SN=fake,T={time_value},S=20,B=3800,PC=1,U=fake,M=1,CE=0".format(**locals()) connection = patient.contact.default_connection msg = IncomingMessage(connection=connection, text=text) router = Router() router.incoming(msg) messages.info(request, "Sent fake wisepill message from %s" % patient) return redirect('patient-list')
def sms(self, number, text, success=True, response=None, backend=None): form = XForm.find_form(text) self.assertTrue(form) if not backend: backend, created = Backend.objects.get_or_create(name='tns') connection, created = Connection.objects.get_or_create(backend=backend, identity=number) message = IncomingMessage(connection, text) submission = form.process_sms_submission(message) if success: self.assertFalse(submission.has_errors, "SMS had errors: %s" % submission.response) else: self.assertTrue( submission.has_errors, "SMS did not have any errors: %s" % submission.response) if response: self.assertEquals(response, submission.response) return submission
def spoof_incoming_obj(self, message, connection=None): if connection is None: connection = Connection.objects.all()[0] incomingmessage = IncomingMessage(connection, message) incomingmessage.db_message = Message.objects.create(direction='I', connection=Connection.objects.all()[0], text=message) return incomingmessage
def handle_incoming(router,backend, sender, text,ignore_result=True,**kwargs): """ Handles an incoming message. """ # create our db message for logging db_message = router.add_message(backend, sender, text, 'I', 'R') # and our rapidsms transient message for processing msg = IncomingMessage(db_message.connection, text, db_message.date) # add an extra property to IncomingMessage, so httprouter-aware # apps can make use of it during the handling phase msg.db_message = db_message router.info("SMS[%d] IN (%s) : %s" % (db_message.id, msg.connection, msg.text)) try: for phase in router.incoming_phases: router.debug("In %s phase" % phase) if phase == "default": if msg.handled: router.debug("Skipping phase") break for app in router.apps: router.debug("In %s app" % app) handled = False try: func = getattr(app, phase) handled = func(msg) except Exception, err: import traceback traceback.print_exc(err) app.exception() # during the _filter_ phase, an app can return True # to abort ALL further processing of this message if phase == "filter": if handled is True: router.warning("Message filtered") raise(StopIteration) # during the _handle_ phase, apps can return True # to "short-circuit" this phase, preventing any # further apps from receiving the message elif phase == "handle": if handled is True: router.debug("Short-circuited") # mark the message handled to avoid the # default phase firing unnecessarily msg.handled = True db_message.application = app db_message.save() break elif phase == "default": # allow default phase of apps to short circuit # for prioritized contextual responses. if handled is True: router.debug("Short-circuited default") break except StopIteration: pass db_message.status = 'H' db_message.save() db_responses = [] # now send the message responses while msg.responses: response = msg.responses.pop(0) router.handle_outgoing(response, db_message, db_message.application) # we are no longer interested in this message... but some crazy # synchronous backends might be, so mark it as processed. msg.processed = True return db_message
def handle_incoming(self, backend, sender, text): """ Handles an incoming message. """ global outgoing_db_lock # create our db message for logging db_message = self.add_message(backend, sender, text, 'I', 'R') # and our rapidsms transient message for processing msg = IncomingMessage(db_message.connection, text, db_message.date) # add an extra property to IncomingMessage, so httprouter-aware # apps can make use of it during the handling phase msg.db_message = db_message self.info("SMS[%d] IN (%s) : %s" % (db_message.id, msg.connection, msg.text)) try: for phase in self.incoming_phases: self.debug("In %s phase" % phase) if phase == "default": if msg.handled: self.debug("Skipping phase") break for app in self.apps: self.debug("In %s app" % app) handled = False try: func = getattr(app, phase) handled = func(msg) except Exception, err: import traceback traceback.print_exc(err) app.exception() # during the _filter_ phase, an app can return True # to abort ALL further processing of this message if phase == "filter": if handled is True: self.warning("Message filtered") raise (StopIteration) # during the _handle_ phase, apps can return True # to "short-circuit" this phase, preventing any # further apps from receiving the message elif phase == "handle": if handled is True: self.debug("Short-circuited") # mark the message handled to avoid the # default phase firing unnecessarily msg.handled = True break elif phase == "default": # allow default phase of apps to short circuit # for prioritized contextual responses. if handled is True: self.debug("Short-circuited default") break except StopIteration: pass outgoing_db_lock.acquire() db_message.status = 'H' db_message.save() outgoing_db_lock.release() db_responses = [] # now send the message responses while msg.responses: response = msg.responses.pop(0) self.handle_outgoing(response, db_message) # we are no longer interested in this message... but some crazy # synchronous backends might be, so mark it as processed. msg.processed = True return db_message
def _send(self, text): msg = IncomingMessage([self.connection], text) self.app.handle(msg) return msg
def _send(self, text): msg = IncomingMessage([self.connection], text) handler = ResultsHandler(self.router, msg) handler.handle(msg.text) return handler
def _send(self, conn, text): msg = IncomingMessage(conn, text) self.app.filter(msg) return msg
def _get_incoming_message(connection, message): incoming_message = IncomingMessage(connection, message) incoming_message.db_message = Message.objects.create(direction='I', connection=connection, text=message) return incoming_message
def _send(self, conn, text): msg = IncomingMessage(conn, text) self.app.handle(msg) return msg