def test_get_random_message(self): source = 'testing_message_generator' msg_gen = MessageGenerator(source=source) msg = msg_gen.get_random_message() # Ensures that the message is of type dict (hence can be converted to json) assert isinstance(msg, dict) # Ensure that all required context attributes CloudEvent are set for key in [ 'specversion', 'type', 'source', 'id', 'time', 'contenttype', 'data' ]: assert key in msg.keys() # Ensure that the source was set appropriately assert msg['source'] == source # Ensures that the timestamp is UTC msg_date = dateutil.parser.parse(msg['time']) assert msg_date.tzname() == 'UTC' # Ensure that the timestamp is up to date (not older than 10 seconds) delta = (datetime.now(timezone.utc) - msg_date) assert delta.total_seconds() < 10 # Ensure that the data field contains the right value types for k in ['timestamp', 'rand_int', 'text']: assert k in msg['data'].keys()
def test_mez_returns_background_task(self): line = "a mob has been mesmerized" unit = MessageGenerator('/path/to/eq', IRRELEVANT_CHARACTER, ACTIONS_MAP) task = unit.action_for(line) self.assertEqual(19, task.timeout) self.assertEqual('Mesmerize Warning', task.message) self.assertEqual('Mez', task.title) expected_command = 'urxvt -iconic -geometry 15x1 -bg red -fg white -title Mez -e python stop_watch.py 19 "Mesmerize Warning" 1' self.assertEqual(expected_command, task.command)
class Bot: def __init__(self): self.token = config_provider.token self.generator = MessageGenerator() HelloActor.start() InfoActor.start() BuildListActor.start() ServiceStatusActor.start() RockPaperActor.start() BuildActor.start() def run(self): self.generator.run()
def _controller_factory(): return MessagingController( generator=MessageGenerator('test_source'), producer=KafkaProducer(bootstrap_servers=broker), target_topic=topic, send_interval=1, replication_factor=1, num_partitions=1)
def __init__(self, token: str, messageGenerator: MessageGenerator, imageGenerator: ImageGenerator) -> None: logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO, ) self.logger = logging.getLogger("LOG") self.logger.info("Starting BOT.") self.updater = Updater(token) self.dispatcher = self.updater.dispatcher self.messageGenerator = messageGenerator self.imageGenerator = imageGenerator messageGenerator.generate() self.message = self.messageGenerator.get_message() self.job = self.updater.job_queue self.job_daily = self.job.run_daily(callback=self.send_daily_message, time=DAILY_TIME, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None) start_handler = CommandHandler("start", self.send_start) self.dispatcher.add_handler(start_handler) help_handler = CommandHandler("help", self.send_help) self.dispatcher.add_handler(help_handler) enable_handler = CommandHandler("enable", self.send_enable) self.dispatcher.add_handler(enable_handler) disable_handler = CommandHandler("disable", self.send_disable) self.dispatcher.add_handler(disable_handler) chart_handler = CommandHandler("grafico", self.send_chart) self.dispatcher.add_handler(chart_handler) message_handler = CommandHandler("news", self.send_message) self.dispatcher.add_handler(message_handler)
def test_tell_that_we_ignore(self): unit = MessageGenerator('/path/to/eq', 'tabashir', ACTIONS_MAP) line = "a vendor tells you, That'll be 10 plat" self.assertIsNone(unit.action_for(line))
def test_basic_tell(self): unit = MessageGenerator('/path/to/eq', IRRELEVANT_CHARACTER, ACTIONS_MAP) line = "anothertoon tells you, 'hello there'" expected_message = 'Incoming Tell' self.assertEqual(expected_message, unit.action_for(line).message)
def test_line_depending_on_character_name_when_character_not_matched(self): unit = MessageGenerator('/path/to/eq', 'tabashir', ACTIONS_MAP) line = "shadows will consume you, anothertoon" self.assertIsNone(unit.action_for(line))
def test_line_depending_on_character_name_when_character_matches(self): unit = MessageGenerator('/path/to/eq', 'tabashir', ACTIONS_MAP) line = "shadows will consume you, tabashir" expected_message = 'Run away from the raid' self.assertEqual(expected_message, unit.action_for(line).message)
def test_basic_full_line_match_returns_message(self): unit = MessageGenerator('/path/to/eq', IRRELEVANT_CHARACTER, ACTIONS_MAP) line = "Marnek enters the realm of the dead" expected_message = "Marnek is in skeleton form, shrouded players DPS now" self.assertEqual(expected_message, unit.action_for(line).message)
def test_unrecognised_line_should_return_nothing(self): unit = MessageGenerator('/path/to/eq', IRRELEVANT_CHARACTER, ACTIONS_MAP) line = 'this will not be parsed' action = unit.action_for(line) self.assertIsNone(action)
def update_service_call(): """ Diese Methode ruft in regelmäßigen Abständen (5min) """ try: update_service.update(updater) except Exception as e: logging.warning("error in update_Service_call: {}".format(str(e))) threading.Timer(conf["update-service-frequency"] * 60, update_service_call).start() data_handler = DataHandler() # ruft de Daten ab und berechnet Werte harry_plotter = Plotter(data_handler) # der Auserwählte. Nur er kann plotten mail_man = MessageGenerator( data_handler) # der mail_man generiert die Textnachrichten update_service = UpdateService(data_handler, mail_man) # service für die täglichen Updates callback_service = CallbackService(mail_man, harry_plotter, update_service) updater = Updater(util.get_apikey()) data_handler.new_data_callback = replot_all replot_all() dropdown_commands = [] # kommandos binden for key in commands.keys(): command = commands[key] callback = callback_service.get_callback(command["type"], command["resp-id"])
# update the image TODO could have been done better self.update_image() def update_image(self) -> None: self.imageGenerator.generate() # update the message to send daily def update_message(self) -> None: self.messageGenerator.update() self.message = messageGenerator.get_message() # start the bot def run(self) -> int: self.logger.info("Polling BOT.") self.updater.start_polling() # Run the BOT until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the BOT gracefully. self.updater.idle() return 0 if __name__ == "__main__": TOKEN = get_token() messageGenerator = MessageGenerator() imageGenerator = ImageGenerator() BOT = Bot(TOKEN, messageGenerator, imageGenerator) BOT.run()
from commons import * from message_generator import MessageGenerator from messaging_controller import MessagingController from kafka import KafkaProducer from logging import info from config import * if __name__ == '__main__': # Read in the environment variables prepare_logging(LOG_FILE_PATH, LOG_FORMAT, LOG_LEVEL) info('Start logging with the following setting: \n ' + get_env_variable_str(locals())) # prepare the message generator and controller generator = MessageGenerator(MESSAGE_SOURCE) producer = KafkaProducer( bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS.split(',')) controller = MessagingController(generator, producer, KAFKA_TOPIC_OUTPUT, MESSAGE_SEND_INTERVAL, KAFKA_TOPIC_OUTPUT_NUM_PARTITIONS, KAFKA_TOPIC_OUTPUT_REPLICATION_FACTOR) # start execution controller.start_producing()
character = CHARLIST.getName(CHARNUM) server = CHARLIST.getServer(CHARNUM) # generate logfile path log_path = "eqlog_%s_%s.txt" % (character, server) log_file = DepCheck.getLogFile(eq_home, character, log_path) actions_map = ActionsMapper('actions.yml').actions try: # open log file with open(log_file, 'r+') as f: # move to the end of the file f.seek(0, 2) generator = MessageGenerator(eq_home, character, actions_map) # loop over each new line of the file # act on keywords from chat messages parsed from logfile # if no new line, wait for short while before re-checking # NOTE: this is to prevent excessive CPU when there are no # incoming lines, it should not delay between pending lines while True: line = f.readline() if not line: time.sleep(0.1) continue # print("DEBUG: "+ line) action = generator.action_for(line) if action: print("ACTION: %s" % (action.message))
#!/usr/bin/python # tratar comentarios na primeira linha da .MMSG file com a palavra chave extends. # gerar MSG file sem comentarios e sem espaco entre as linhas # comentar contribuicao da heranca # fatorar codigo em funcoes import sys from message_generator import MessageGenerator if __name__ == "__main__": app = MessageGenerator() if len(sys.argv) == 2: app.generate_for_package(sys.argv[1]) elif len(sys.argv) >= 3: for i in range(2, len(sys.argv)): app.generate_for_metamessage(sys.argv[1], sys.argv[i])