def sendPressed(self, inp=None): try: text = self.input.get() index = int(self.listbox.curselection()[0]) if (self.checkWhisper.get()): message = Message(text, self.manager.myIp, 'whisper') users = self.manager.contactManager.users user = users[self.usersListBox[index]].nickname() self.manager.messageManager.client.sendTo( self.usersListBox[self.listbox.curselection()[0]], self.manager.messageManager.parser.codeWhisper(message)) self.sendToUI("You -> " + user + ": " + message.content()) else: message = Message(self.input.get(), self.manager.contactManager.mySelf, "say") if (int(self.listbox.curselection()[0]) != 0): message._to = self.usersListBox[ self.listbox.curselection()[0]] self.printMessage(message) self.manager.messageManager.client.sendBroadcast( self.manager.messageManager.parser.codeSay(message)) self.input.delete(0, 'end') except Exception as e: print "Error on sendPressed: ", e
class TestMessageData(TestSuite): message1_dict = { 'message_id': 3, 'username': "******", 'first': "Andrew", 'last': "Jarombek", 'group_name': 'alumni', 'time': datetime.fromisoformat('2019-11-25'), 'content': "Test Message 1", 'deleted': None } message2_dict = { 'message_id': 4, 'username': "******", 'first': "Andrew", 'last': "Jarombek", 'group_name': 'alumni', 'time': datetime.fromisoformat('2019-11-25'), 'content': "Test Message 2", 'deleted': True } message1 = MessageData(Message(message1_dict)) message1copy = MessageData(Message(message1_dict)) message2 = MessageData(Message(message2_dict)) def test_message_data_str(self) -> None: """ Prove that the human readable string representation of a MessageData object is as expected. """ log_str = 'MessageData: [message_id: 3, username: andy, first: Andrew, last: Jarombek, ' \ "group_name: alumni, time: 2019-11-25 00:00:00, content: Test Message 1, deleted: None]" self.maxDiff = None self.assertEquals(str(self.message1), log_str) self.assertEquals(self.message1.__str__(), log_str) def test_message_data_repr(self) -> None: """ Prove that the machine readable string representation of a MessageData object is as expected. """ self.assertEquals(repr(self.message1), "<MessageData 3>") self.assertEquals(self.message1.__repr__(), "<MessageData 3>") def test_message_data_eq(self) -> None: """ Prove that two MessageData objects with the same property values test positive for value equality. """ self.assertTrue(self.message1 == self.message1copy) self.assertTrue(self.message1.__eq__(self.message1copy)) def test_message_data_ne(self) -> None: """ Prove that two MessageData objects with different property values test negative for value equality. """ self.assertTrue(self.message1 != self.message2) self.assertTrue(self.message1.__ne__(self.message2))
def update(self): # If there is any input from network, relay onto message bus try: data = self.sock.recv(256).decode('utf-8') data = data.split('~') if data[0] == "KEYDOWN": msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_KeyPressed, data=data[1]) self.msgBus.postMessage(msg) elif data[0] == "KEYUP": msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_KeyReleased, data=data[1]) self.msgBus.postMessage(msg) except: '''no data yet..'''
def update(self): for event in tdl.event.get(): # Iterate over recent events. if event.type == 'KEYDOWN': if event.keychar not in IGNORED_INPUTS: msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_KeyPressed, data=event.keychar) self.msgBus.postMessage(msg) if event.type == 'KEYUP': if event.keychar not in IGNORED_INPUTS: msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_KeyReleased, data=event.keychar) self.msgBus.postMessage(msg)
def test_to_tuple_with_correct_data(self): message = Message("[21.10.17, 16:19:29] Christian: Hello Testing") self.assertEqual( message.to_tuple(), tuple([ "Christian", "Hello Testing", datetime(2017, 10, 21, 16, 19, 29) ]))
def move(self, entity, vector2D): msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_MoveEntity, data={ "entity": entity, "vector2D": vector2D }) self.msgBus.postMessage(msg)
def test_init_with_correct_data(self): message = Message( "[21.10.17, 16:19:29] Christian: Ähm i büd ma ei i hob gsogt i wü kan tequila mea, oba ds büd i ma wsl nua ei😂🙈" ) self.assertEqual( message.body, "Ähm i büd ma ei i hob gsogt i wü kan tequila mea, oba ds büd i ma wsl nua ei😂🙈" ) self.assertEqual(message.date_time, datetime(2017, 10, 21, 16, 19, 29)) self.assertEqual(message.writer, "Christian")
def keyPressed(self, key): if key.upper() in MOVEMENT_KEYS: self.move(self.player, MOVEMENT_KEYS[key.upper()]) elif key.upper() in ACTION_KEYS: self.action(self.player, ACTION_KEYS[key.upper()]) elif key.upper() == "SHIFT": self.shiftModifier = True elif key.upper() == "Q": msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_Quit) self.msgBus.postMessage(msg)
def decodeTemporaryMessage(dict): message = Message(dict['message_id'],1, dict['intervention_session_id']) message.miniplan_id = dict['miniplan_temporary_id'] message.time = dict['range_hour_start'] message.channel = dict['channel'] message.date = dict['range_day_start'] message.attached_audio = dict['audio'] message.attached_media = dict['media'] message.message_text = dict['text'] message.URL = dict['url'] return message
def init(self): Logic.init(self) # Init state of the game... self.player = Player(50, 50, "@", self.msgBus)#, aiType=AIType.AIType_Zombie) self.addEntity(self.player) # Force camera to follow player entity msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_CameraFollowEntity, data=self.player) self.msgBus.postMessage(msg) self.generateMap(100, 100)
def removeEntityAt(self, x, y): toRemove = [] for entity in self.entities: if entity.x == x and entity.y == y: msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_RemoveEntity, data=entity) self.msgBus.postMessage(msg) # Mark for removal toRemove.append(entity) # Remove all entities from local cache for entity in toRemove: self.entities.remove(entity)
def _send_messages(self, me: Wizard, move: Move): if me.master: teammates = [ w for w in self.W.wizards if w.faction == self.FRIENDLY_FACTION and not w.me ] self.log('found %d teammates' % len(teammates)) if teammates: direction = [ Message(LaneType.MIDDLE, None, None), Message(LaneType.TOP, None, None), Message(LaneType.BOTTOM, None, None) ] index = 0 msgs = [] for i in range(0, len(teammates)): msgs.append(direction[index]) index += 1 if index >= len(direction): index = 0 self.log('send %d msgs' % len(msgs)) move.messages = msgs
def init(self, me, move, world): self.x = me.x self.y = me.y self.target_point_x, self.target_point_y = self.x, self.y self.faction = me.faction if self.faction == Faction.ACADEMY: self.enemy_faction = Faction.RENEGADES else: self.enemy_faction = Faction.ACADEMY if me.master: move.messages = [ Message(LaneType.MIDDLE, None, None), Message(LaneType.BOTTOM, None, None), Message(LaneType.BOTTOM, None, None), Message(LaneType.BOTTOM, None, None) ] self.lane = LaneType.TOP '''Get enemy towers coordinates. Mirror own towers coordinate. for i in world.buildings: if i.faction == self.faction: [world.width - i.x, world.width - i.y]) ''' self.enemy_towers_coordinates = [[1687.8740025771563, 50.0], [2629.339679648397, 350.0], [2070.710678118655, 1600.0], [ 3097.386941332822, 1231.9023805485235 ], [3650.0, 2343.2513553373133], [3950.0, 1306.7422221916627]] for i in range(0, 17): if i <= 8: self.waypoints_TOP.append([200, 4000 - i * 400 - 250]) self.waypoints_BOT.append([i * 400 + 250, 3750]) else: self.waypoints_TOP.append([(i - 8) * 400 + 250, 250]) self.waypoints_BOT.append([3750, 4000 - (i - 8) * 400 - 250]) for i in range(0, 9): self.waypoints_MID.append([i * 400 + 250, 4000 - i * 400 - 250])
def mapMessage(message_dict): message = Message(message_dict['message_id'], message_dict['user_id'], message_dict['intervention_session_id']) message.URL = message_dict['URL'] message.attached_media = message_dict['attached_media'] message.attached_audio = message_dict['attached_audio'] message.channel = message_dict['channel'] message.message_text = message_dict['message_text'] message.miniplan_id = message_dict['miniplan_id'] message.pilot_id = message_dict['pilot_id'] if message_dict['date'] != '': message.date = datetime.strptime(message_dict['date'], '%Y-%m-%d') if message_dict['time'] != '': message.time = datetime.strptime(message_dict['time'], '%H:%M:%S') return message
def __init__(self, initialX, initialY, char, msgBus, aiType=None): self.x = initialX self.y = initialY self.char = char self.aiType = aiType self.msgBus = msgBus self.moves = [[0, 1], [-1, 0], [1, 0], [0, -1]] self.sightRange = 5 if aiType != None: msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_SubscribeAI, data=self) self.msgBus.postMessage(msg)
def decodeMessage(dict): message = Message(dict['message_id'], dict['user_id'], dict['intervention_session_id']) message.miniplan_id = dict['miniplan_id'] message.pilot_id = dict['pilot_id'] message.time_2 = dict['time_2'] message.time_1 = dict['time_1'] message.time = dict['time'] message.channel = dict['channel'] message.date = dict['date'] message.expiration_date = dict['expiration_date'] message.attached_audio = dict['attached_audio'] message.attached_media = dict['attached_media'] message.message_text = dict['message_text'] message.URL = dict['URL'] return message
def get_message(self, msg_id): # possible formats: ['full', 'metadata', 'minimal', 'raw'] subject = None msg = self.service.users().messages().get(userId='me', id=msg_id).execute() # parse date date = float(msg['internalDate']) / 1000 date = datetime.utcfromtimestamp(date) # parse subject headers = msg['payload']['headers'] for header in headers: if header['name'] == 'Subject': subject = header['value'] # parse attachments attachments_raw = [] for part in msg['payload']['parts']: if part['filename']: attachments_raw.append((part['filename'], part['body']['attachmentId'])) attachments = [] for attachment in attachments_raw: att = self.service.users().messages().attachments().get( userId='me', id=attachment[1], messageId=msg_id).execute() data = att['data'] file_data = base64.urlsafe_b64decode(data.encode('UTF-8')) attachments.append(Attachment(attachment[0], file_data)) # parse body parts = msg['payload']['parts'] data = self._get_data(parts) clean = base64.urlsafe_b64decode(data) soup = BeautifulSoup(clean, "lxml") body = soup.find_all('p')[0].text return Message(date, subject, body, attachments)
def schedulePeriodic(request, resource, template, aged): print "Schedule Day" errors = {} if type(request.from_date) is not datetime: times = convertDatetime(request, template, resource) startime = times[0] endtime = times[1] period = times[2] expirationtime = times[3] else: startime = request.from_date endtime = request.to_date period = timedelta(days=template.period * 7) expirationtime = resource.to_date if expirationtime == None: expirationtime = endtime valid_interval = endtime - startime if valid_interval > period: endtime = startime + period if template.nmsgmin != template.nmsgmax: nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1) else: nmsg = template.nmsgmax miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)] channels = getChannelsAvailable(template, aged) with open('csv/prova_import_messages.csv') as csvmessages: messages = csv.DictReader(csvmessages) msgs_tosend = getListMessages(messages, nmsg, resource, channels) er = checkForErrors(errors, endtime, expirationtime, startime, miniplan, nmsg, len(msgs_tosend)) errors = er[0] miniplan = er[1] if er[2]: endtime = er[3] else: return errors, miniplan day_of_event = mapDay(resource.on_day) if day_of_event == None: errors['ErrorNoDay'] = 'Error no day specified for periodic messages' miniplan = [] return errors, miniplan # length of the loop depending on the msgs found if len(msgs_tosend) < nmsg: lenloop = len(msgs_tosend) else: lenloop = nmsg c = 0 i = 0 current_date = startime.date() while current_date < endtime.date(): if current_date.weekday() == day_of_event - 1: if c % int(resource.every) == 0: if i > lenloop: break miniplan[i].date = current_date miniplan[i].time = scheduleHour(aged, None) miniplan[i].attached_audio = msgs_tosend[i]['Audio'] miniplan[i].attached_media = msgs_tosend[i]['Media'] miniplan[i].URL = msgs_tosend[i]['URL'] miniplan[i].channel = msgs_tosend[i]['Channel'] miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'], msgs_tosend[i]['URL']) i += 1 c += 1 current_date += timedelta(days=1) miniplan = checkMsgsOneDay(miniplan, endtime) return errors, miniplan
def scheduleEDPPendulum(request, resource, template, aged): print "_______________SCHEDULEEDPPENDULUM_______________" ''' Returns the miniplan with the temporal interval between the msgs divided equally with Pendulum :param request: a request class :param template: a template class :param aged: a user class :return: a miniplan that is a list of messages class with all the fields completed ''' errors = {} miniplanID = uuid.uuid4() u = generateXMLDoc(aged) r = generateXMLDoc(resource) c = None # per ora non usato #todo: tenuta provvisoria per la demo, bisogna stabilire una struttura standard templateInfo = {} templateInfo['tags'] = template.message_structure templateInfo['tone'] = "Neutral" if type(request.from_date) is not Pendulum: times = convertPendulum(request, template, resource) startime = times[0] endtime = times[1] period = times[2] else: startime = request.from_date endtime = request.to_date period = pendulum.Period(startime, startime.add(weeks=template.period)) valid_interval = endtime - startime if valid_interval > period: errors['Interval changed'] = 'Duration of the template(' + str( period) + ') less than interval set by the care giver' valid_interval = period if template.nmsgmin != template.nmsgmax and template.nmsgmax > template.nmsgmin: nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1) else: nmsg = template.nmsgmax # creates miniplan that is a list of messages miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)] channels = getChannelsAvailable(template, aged) messages = getResourceMessages(resource.resource_id) if messages is None: errors = {'Error': 'Messages not found'} miniplan = {} return errors, miniplan msgs_tosend = selectMessages(messages, nmsg, channels) er = checkForErrors(errors, endtime, None, startime, miniplan, nmsg, len(msgs_tosend)) errors = er[0] miniplan = er[1] if er[2]: endtime = er[3] else: return errors, miniplan # length of the loop depending on the msgs found if len(msgs_tosend) < nmsg: lenloop = len(msgs_tosend) else: lenloop = nmsg step_send_msg = valid_interval / lenloop date = startime + (step_send_msg / 2) for i in range(0, lenloop): miniplan[i].miniplan_id = miniplanID miniplan[i].date = date.date() miniplan[i].time = scheduleHour(aged, None) miniplan[i].message_text = buildMessage(aged, msgs_tosend[i]) message_body = msgs_tosend[i]['Text'] m = createMessageJson(message_body, templateInfo) miniplan[i].message_text = composeMessage(u, r, c, m) miniplan[i].attached_audio = msgs_tosend[i].audio miniplan[i].attached_media = msgs_tosend[i].media miniplan[i].URL = msgs_tosend[i].url miniplan[i].channel = msgs_tosend[i].channels[0]['channel_name'] miniplan[i].time_1 = date.date() miniplan[i].time_2 = date.add(days=1).date() miniplan[i].intervention_session_id = request.intervention_session_id miniplan[i].pilot_id = request.pilot_id date += step_send_msg miniplan = checkMsgsOneDay(miniplan, endtime) return errors, miniplan
def test_replacing_commas_without_commas(self): message = Message("[21.10.17, 16:19:29] Christian: Hello Testing") message.replace_commas() self.assertEqual(message.body, "Hello Testing")
def scheduleLPendulum(request, resource, template, aged): print "_______________SCHEDULEPENDULUM_______________" ''' Returns the miniplan scheduled with more frequency at the end of the interval It divides the interval for every msg with logaritmic growth:1 1/2 1/3 1/4 Check on period(valid weeks): if request interval is larger that period then user period as interval Last message always sent the day before the event With Pendulum :param request: a request class :param template: a template class :param aged: a user class :return: a miniplan that is a list of messages class with all the fields completed ''' errors = {} miniplanID = uuid.uuid4() u = generateXMLDoc(aged) r = generateXMLDoc(resource) c = None # per ora non usato # todo: tenuta provvisoria per la demo, bisogna stabilire una struttura standard templateInfo = {} templateInfo['tags'] = template.message_structure templateInfo['tone'] = "Neutral" if type(request.from_date) is not Pendulum: times = convertPendulum(request, template, resource) startime = times[0] endtime = times[1] period = times[2] expirationtime = times[3] else: startime = request.from_date endtime = request.to_date period = pendulum.Period(startime, startime.add(weeks=template.period)) expirationtime = resource.to_date if expirationtime == None: expirationtime = endtime if template.nmsgmin != template.nmsgmax: nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1) else: nmsg = template.nmsgmax miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)] valid_interval = endtime - startime if valid_interval > period: errors['Interval changed'] = 'Duration of the template(' + str( period) + ') less than interval set by the care giver' valid_interval = period channels = getChannelsAvailable(template, aged) messages = getResourceMessages(resource.resource_id) if messages is None: errors = {'Error': 'Messages not found'} miniplan = {} return errors, miniplan msgs_tosend = selectMessages(messages, nmsg, channels) ''' with open('csv/prova_import_messages.csv') as csvmessages: messages = csv.DictReader(csvmessages) msgs_tosend = getListMessages(messages, nmsg, resource, channels) ''' er = checkForErrors(errors, endtime, expirationtime, startime, miniplan, nmsg, len(msgs_tosend)) errors = er[0] miniplan = er[1] if er[2]: endtime = er[3] else: return errors, miniplan # length of the loop depending on the msgs found if len(msgs_tosend) < nmsg: lenloop = len(msgs_tosend) else: lenloop = nmsg for i in range(0, lenloop): date = endtime - valid_interval miniplan[i].miniplan_id = miniplanID miniplan[i].date = date.date() miniplan[i].time_1 = date.date() miniplan[i].time_2 = date.add(days=1).date() miniplan[i].time = scheduleHourFromDate(aged, date).time() # miniplan[i].message_text = buildMessage(aged, msgs_tosend[i]) message_body = msgs_tosend[i]['Text'] m = createMessageJson(message_body, templateInfo) miniplan[i].message_text = composeMessage(u, r, c, m) miniplan[i].attached_audio = msgs_tosend[i].audio miniplan[i].attached_media = msgs_tosend[i].media miniplan[i].URL = msgs_tosend[i].url miniplan[i].message_id = msgs_tosend[i].message_id miniplan[i].channel = msgs_tosend[i].channels[0]['channel_name'] miniplan[i].intervention_session_id = request.intervention_session_id miniplan[i].pilot_id = request.pilot_id valid_interval = valid_interval / (i + 2) miniplan = checkMsgsOneDayPendulum(miniplan, endtime) return errors, miniplan
def schedule(request, resource, template, aged): print "_______________SCHEDULE_______________" errors = {} if type(request.from_date) is not Pendulum: times = convertPendulum(request, template, resource) startime = times[0] endtime = times[1] period = times[2] expirationtime = times[3] else: startime = request.from_date endtime = request.to_date period = pendulum.Period(startime, startime.add(weeks=template.period)) expirationtime = resource.to_date if expirationtime == None: expirationtime = endtime if template.nmsgmin != template.nmsgmax and template.nmsgmax > template.nmsgmin: nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1) else: nmsg = template.nmsgmax # creates miniplan that is a list of messages miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)] channels = getChannelsAvailable(template, aged) ''' with open('csv/prova_import_messages.csv') as csvmessages: messages = csv.DictReader(csvmessages) msgs_tosend = getListMessages(messages, nmsg, resource, channels) ''' messages = getResourceMessages(resource.resource_id) msgs_tosend = selectMessages(messages, nmsg, channels) er = checkForErrors(errors, endtime, None, startime, miniplan, nmsg, len(msgs_tosend)) errors = er[0] miniplan = er[1] if er[2]: endtime = er[3] else: return errors, miniplan # length of the loop depending on the msgs found if len(msgs_tosend) < nmsg: lenloop = len(msgs_tosend) else: lenloop = nmsg for i in range(0, lenloop): miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'], msgs_tosend[i]['URL']) miniplan[i].attached_audio = msgs_tosend[i]['Audio'] miniplan[i].attached_media = msgs_tosend[i]['Media'] miniplan[i].URL = msgs_tosend[i]['URL'] miniplan[i].channel = msgs_tosend[i]['Channel'] miniplan = ED(miniplan, lenloop, startime, endtime, period, aged) miniplan = checkMsgsOneDay(miniplan, endtime) return errors, miniplan
def test_to_tuple_with_empty_body(self): message = Message("[21.10.17, 16:19:29] Christian:") self.assertEqual( message.to_tuple(), tuple(["Christian", "", datetime(2017, 10, 21, 16, 19, 29)]))
def test_init_with_empty_message_line(self): message = Message("") self.assertEqual(message.body, "") self.assertEqual(message.date_time, None) self.assertEqual(message.writer, "")
def schedulePPendulum(request, resource, template, aged): errors = {} u = generateXMLDoc(aged) r = generateXMLDoc(resource) c = None # per ora non usato template.message_structure templateInfo = {} templateInfo['tags'] = template.message_structure #todo il tone e' da aggiungere come parametro alla classe template--> template.tone #templateInfo['tone'] = template.tone templateInfo['tone'] = "Neutral" if type(request.from_date) is not Pendulum: times = convertPendulum(request, template, resource) startime = times[0] endtime = times[1] period = times[2] expirationtime = times[3] else: startime = request.from_date endtime = request.to_date period = pendulum.Period(startime, startime.add(weeks=template.period)) expirationtime = resource.to_date if expirationtime == None: expirationtime = endtime valid_interval = endtime - startime if valid_interval > period: valid_interval = period if template.nmsgmin != template.nmsgmax: nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1) else: nmsg = template.nmsgmax miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)] miniplanID = uuid.uuid4() channels = getChannelsAvailable(template, aged) with open('csv/prova_import_messages.csv') as csvmessages: messages = csv.DictReader(csvmessages) msgs_tosend = getListMessages(messages, nmsg, resource, channels) er = checkForErrors(errors, endtime, expirationtime, startime, miniplan, nmsg, len(msgs_tosend)) errors = er[0] miniplan = er[1] if er[2]: endtime = er[3] else: return errors, miniplan day_of_event = mapDay(resource.on_day) if day_of_event == None: errors['ErrorNoDay'] = 'Error no day specified for periodic messages' miniplan = [] return errors, miniplan # length of the loop depending on the msgs found if len(msgs_tosend) < nmsg: lenloop = len(msgs_tosend) else: lenloop = nmsg c = 0 i = 0 for dt in valid_interval.range("days"): if dt.day_of_week == day_of_event: if c % int(resource.every) == 0: if i > lenloop: break miniplan[i].miniplan_id = miniplanID miniplan[i].date = dt.date() miniplan[i].time_1 = dt.date() miniplan[i].time_2 = dt.subtract(days=1).date() miniplan[i].time = scheduleHour(aged, None) miniplan[i].attached_audio = msgs_tosend[i]['Audio'] miniplan[i].attached_media = msgs_tosend[i]['Media'] miniplan[i].URL = msgs_tosend[i]['URL'] miniplan[i].channel = msgs_tosend[i]['Channel'] #miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'],msgs_tosend[i]['URL']) message_body = msgs_tosend[i]['Text'] m = createMessageJson(message_body, templateInfo) miniplan[i].message_text = composeMessage(u, r, c, m) miniplan[i].intervention_session_id = request.intervention_session_id miniplan[i].pilot_id = request.pilot_id i += 1 c += 1 miniplan = checkMsgsOneDay(miniplan, endtime) return errors, miniplan
def parse_messages(fp): messages = extract_messages_lines(fp) messages = [Message(message) for message in messages] return messages
def scheduleLogarithmic(request, resource, template, aged): ''' Returns the miniplan scheduled with more frequency at the end of the interval It divides the interval for every msg with logaritmic growth:1 1/2 1/3 1/4 Check on period(valid weeks): if request interval is larger that period then user period as interval Last message always sent the day before the event :param request: a request class :param template: a template class :param aged: a user class :return: a miniplan that is a list of messages class with all the fields completed ''' print "Schedule Day" errors = {} if type(request.from_date) is not datetime: times = convertDatetime(request, template, resource) startime = times[0] endtime = times[1] period = times[2] expirationtime = times[3] else: startime = request.from_date endtime = request.to_date period = timedelta(days=template.period * 7) expirationtime = resource.to_date if expirationtime == None: expirationtime = endtime if template.nmsgmin != template.nmsgmax: nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1) else: nmsg = template.nmsgmax miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)] valid_interval = endtime - startime if valid_interval > period: valid_interval = period channels = getChannelsAvailable(template, aged) with open('csv/prova_import_messages.csv') as csvmessages: messages = csv.DictReader(csvmessages) msgs_tosend = getListMessages(messages, nmsg, resource, channels) er = checkForErrors(errors, endtime, expirationtime, startime, miniplan, nmsg, len(msgs_tosend)) errors = er[0] miniplan = er[1] if er[2]: endtime = er[3] else: return errors, miniplan # length of the loop depending on the msgs found if len(msgs_tosend) < nmsg: lenloop = len(msgs_tosend) else: lenloop = nmsg valid_interval = timedelta(seconds=valid_interval.total_seconds()) for i in range(0, lenloop): date = endtime - valid_interval miniplan[i].date = date.date() miniplan[i].time = scheduleHourFromDate(aged, date).time() miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'], msgs_tosend[i]['URL']) miniplan[i].attached_audio = msgs_tosend[i]['Audio'] miniplan[i].attached_media = msgs_tosend[i]['Media'] miniplan[i].URL = msgs_tosend[i]['URL'] miniplan[i].channel = msgs_tosend[i]['Channel'] valid_interval = timedelta(seconds=valid_interval.total_seconds() / (i + 2)) miniplan = checkMsgsOneDay(miniplan, endtime) return errors, miniplan
def scheduleEquallyDividedPeriod(request, resource, template, aged): ''' Returns the miniplan with the temporal interval between the msgs divided equally :param request: a request class :param template: a template class :param aged: a user class :return: a miniplan that is a list of messages class with all the fields completed ''' print "Schedule Day" errors = {} if type(request.from_date) is not datetime: times = convertDatetime(request, template, resource) startime = times[0] endtime = times[1] period = times[2] else: startime = request.from_date endtime = request.to_date period = timedelta(days=template.period * 7) valid_interval = endtime - startime if valid_interval > period: valid_interval = period if template.nmsgmin != template.nmsgmax: nmsg = rnd.randrange(template.nmsgmin, template.nmsgmax + 1) else: nmsg = template.nmsgmax step_send_msg = valid_interval / nmsg # creates miniplan that is a list of messages miniplan = [Message(count, aged.aged_id, intervention_session_id=1) for count in xrange(nmsg)] channels = getChannelsAvailable(template, aged) with open('csv/prova_import_messages.csv') as csvmessages: messages = csv.DictReader(csvmessages) msgs_tosend = getListMessages(messages, nmsg, resource, channels) er = checkForErrors(errors, endtime, None, startime, miniplan, nmsg, len(msgs_tosend)) errors = er[0] miniplan = er[1] if er[2]: endtime = er[3] else: return errors, miniplan # length of the loop depending on the msgs found if len(msgs_tosend) < nmsg: lenloop = len(msgs_tosend) else: lenloop = nmsg # for nmsg fill the miniplan msgs date = startime for i in range(0, lenloop): miniplan[i].date = date.date() miniplan[i].time = scheduleHour(aged, None) miniplan[i].message_text = generate_message_text(aged, msgs_tosend[i]['Text'], msgs_tosend[i]['URL']) miniplan[i].attached_audio = msgs_tosend[i]['Audio'] miniplan[i].attached_media = msgs_tosend[i]['Media'] miniplan[i].URL = msgs_tosend[i]['URL'] miniplan[i].channel = msgs_tosend[i]['Channel'] date += step_send_msg miniplan = checkMsgsOneDay(miniplan, endtime) return errors, miniplan
def read_message(self): if not self.read_boolean(): return None return Message(self.read_enum(LaneType), self.read_enum(SkillType), self.read_byte_array(False))
def test_init_with_empty_body(self): message = Message("[21.10.17, 16:19:29] Christian:") self.assertEqual(message.body, "") self.assertEqual(message.date_time, datetime(2017, 10, 21, 16, 19, 29)) self.assertEqual(message.writer, "Christian")