class TestLocationMovement(unittest.TestCase): def setUp(self): ms = Mock() self.entityManager = Mock() self.mp = MessageProcessor(self.entityManager, ms) def test_go_somewhere_changes_user_status_to_going(self): user = User(123) user.set_name('TestUser') user.status = UserStatus.READY self.entityManager.getEntityByField = MagicMock(return_value=user) self.mp.message(123, 'Go somewhere') self.assertEqual(user.status, UserStatus.GOING) def test_changes_user_location(self): user = User(123) user.set_name('TestUser') user.status = UserStatus.GOING self.entityManager.getEntityByField = MagicMock(return_value=user) self.mp.message(123, 'Forest') self.assertEqual(user.status, UserStatus.READY) self.assertEqual(user.location, Location.FOREST)
def setUp(self): ms = Mock() self.entityManager = Mock() self.mp = MessageProcessor(self.entityManager, ms) user1 = User(123) user1.set_name('TestUser1') user1.location = Location.ARENA user1.status = UserStatus.READY user2 = User(321) user2.set_name('TestUser2') user2.location = Location.ARENA user2.status = UserStatus.READY self.users = {123: user1, 321: user2} def user_return (c, field, chat_id): if int(chat_id) in self.users: return self.users[int(chat_id)] else: return None self.user_return = user_return def getAllByField(c, field, value): return [self.users[user] for user in self.users if self.users[user].location == value] self.getAllByField = getAllByField self.entityManager.getEntityByField = MagicMock(side_effect=self.user_return) self.entityManager.getAllByField = MagicMock(side_effect=self.getAllByField)
def __init__(self): print "loading credentials" try: print "Starting arena now, press ^C to stop the arena" self.gametick = 2 self.controller = Controller( '/Users/philhouse/Library/Application Support/Dolphin/Pipes/player1' ) self._message_queue = Queue() self._controller_queue = Queue() self.message_processor = MessageProcessor(self._controller_queue, self._message_queue) self.chat_stream = TwitchStream(self._message_queue) # initialize contributions dictionary and last updates array self.contributions = {} self.latest_inputs = [] self.message_processor.start() self.chat_stream.start() # initialize requests call to update web and begin processing controls self.scoreboard_update = self.update_web() self.run() except KeyboardInterrupt: print "Stopped" self.message_processor.join() self.chat_stream.join() self.scoreboard_update.join()
def __init__(self): print "loading credentials" try: print "Starting arena now, press ^C to stop the arena" self.gametick = 2 self.controller = Controller('/Users/philhouse/Library/Application Support/Dolphin/Pipes/player1') self._message_queue = Queue() self._controller_queue = Queue() self.message_processor = MessageProcessor( self._controller_queue, self._message_queue ) self.chat_stream = TwitchStream( self._message_queue ) # initialize contributions dictionary and last updates array self.contributions = {} self.latest_inputs = [] self.message_processor.start() self.chat_stream.start() # initialize requests call to update web and begin processing controls self.scoreboard_update = self.update_web() self.run() except KeyboardInterrupt: print "Stopped" self.message_processor.join() self.chat_stream.join() self.scoreboard_update.join()
def main(): """Do Stuff Here""" # Make a conversational Bot! tco = ThreadCommonObject() friend = Persona("Sam") key_listener = KeyListener(tco=tco) message_processor = MessageProcessor(tco=tco, persona=friend) key_listener.start() message_processor.start() while True: # listen and respond try: if not tco.shutdown: time.sleep(0.5) else: if key_listener.is_alive(): key_listener.join(5.0) print("cp joined") if key_listener.is_alive() == False else print("cp has timed out") if message_processor.is_alive(): message_processor.join(5.0) print("kl joined") if message_processor.is_alive() == False else print("kl has timed out") break except KeyboardInterrupt: tco.shutdown = True
def process_sales_messages(self): """ Process messages, record sales and log. """ try: input_file = open(self.sales_multi_input_path, 'r') message_processor = MessageProcessor(self.sales_list) for message in input_file: message_processor.process_message(message) if (self.number_messages % self.BASIC_REPORT_ITER == 0) and (self.number_messages > 0): self.sales_list = message_processor.sales_list self._prepare_report() if (self.number_messages % self.MAX_REPORT_ITER == 0): break self.number_messages += 1 except Exception as e: logging.warning("Input Error: %s", e) finally: input_file.close()
import time # Packages from slackclient import SlackClient from spacy import load as spacy_load from pyowm import OWM # Local from exceptions import MessageProcessingException from slack_helper import parse_bot_commands from message_processor import MessageProcessor from weather_formatter import WeatherFormatter # instantiate Slack client slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN')) message_processor = MessageProcessor(spacy_load('en_core_web_lg')) owm = OWM(os.environ.get('OWM_API_KEY')) # constants RTM_READ_DELAY = 1 # 1 second delay between reading from RTM """ Executes bot command if the command is known """ def handle_command(command, channel): slack_client.api_call("chat.postMessage", channel=channel, text="Let me check that for you...") try:
def setUp(self): self.processor = MessageProcessor()
class Arena: def __init__(self): print "loading credentials" try: print "Starting arena now, press ^C to stop the arena" self.gametick = 2 self.controller = Controller( '/Users/philhouse/Library/Application Support/Dolphin/Pipes/player1' ) self._message_queue = Queue() self._controller_queue = Queue() self.message_processor = MessageProcessor(self._controller_queue, self._message_queue) self.chat_stream = TwitchStream(self._message_queue) # initialize contributions dictionary and last updates array self.contributions = {} self.latest_inputs = [] self.message_processor.start() self.chat_stream.start() # initialize requests call to update web and begin processing controls self.scoreboard_update = self.update_web() self.run() except KeyboardInterrupt: print "Stopped" self.message_processor.join() self.chat_stream.join() self.scoreboard_update.join() def run(self): print "now running" while True: time.sleep(.01) # self.controller.hit_button(Button.A) try: control = self._controller_queue.get(block=False) input = '' if 'direction' in control: self.controller.tilt_control(control['control'], control['direction']) input = str(control['control']) + ' ' + str( control['direction']) elif 'control' in control: self.controller.hit_button(control['control']) input = str(control['control']) print "receiving control: %s" % str(control) self.contributions[control['user']] = self.contributions.get( control['user'], 0) + 1 self.latest_inputs.append({ 'user': control['user'], 'input': input }) except Empty: pass def update_web(self): """ a method used for updating the web scoreboard with the current contributions :return: reference to timer object """ headers = {'Content-Type': 'application/json'} print "inside update web" data_blob = { 'top_contributors': self.contributions, 'latest_inputs': self.latest_inputs } resp = requests.post('http://localhost:3000/update_contributors', data=json.dumps(data_blob), timeout=1, headers=headers) print resp self.latest_inputs = [] self.scoreboard_update = threading.Timer(2, self.update_web) self.scoreboard_update.start() return self.scoreboard_update
def setUp(self): ms = Mock() self.entityManager = Mock() self.mp = MessageProcessor(self.entityManager, ms)
class TestMessageProcessor(unittest.TestCase): def setUp(self): self.processor = MessageProcessor() @mock.patch("message_queue.queue_manager.QueueManager.add") def test_incoming_message_added_to_processing(self, queue_add_mock): self.processor.process_incoming_event(data.thread_hi_message_json) queue_add_mock.assert_called_once_with(mock.ANY, mock.ANY) def test_second_hi_doesnt_void_old_one(self): # add one real message then mock the receiver self.processor.process_incoming_event(data.thread_hi_message_json) self.processor._queue_manager.add = MagicMock() self.processor._queue_manager.void = MagicMock() # add the same self.processor.process_incoming_event(data.thread_hi_message_json) # and see what happens self.processor._queue_manager.add.assert_called_once_with( mock.ANY, mock.ANY) self.processor._queue_manager.void.assert_not_called() def test_standard_answer_to_hi_voids_it(self): # add one real message then mock the receiver self.processor.process_incoming_event(data.thread_hi_message_json) self.processor._queue_manager.add = MagicMock() self.processor._queue_manager.void = MagicMock() # add answer to it self.processor.process_incoming_event(data.thread_answer_message_json) # check self.processor._queue_manager.add.assert_not_called() self.processor._queue_manager.void.assert_called_once_with(mock.ANY) def test_new_message_from_same_user_voids_old_one(self): # add one real message then mock the receiver self.processor.process_incoming_event(data.thread_hi_message_json) self.processor._queue_manager.add = MagicMock() self.processor._queue_manager.void = MagicMock() # add answer to it self.processor.process_incoming_event( data.thread_following_message_json) # check self.processor._queue_manager.add.assert_not_called() self.processor._queue_manager.void.assert_called_once_with(mock.ANY) def test_hi_answer_to_hi_voids_it(self): # add one real message then mock the receiver self.processor.process_incoming_event(data.thread_hi_message_json) self.processor._queue_manager.add = MagicMock() self.processor._queue_manager.void = MagicMock() # add answer to it self.processor.process_incoming_event( data.thread_answer_hi_message_json) # check self.processor._queue_manager.add.assert_not_called() self.processor._queue_manager.void.assert_called_once_with(mock.ANY) def test_hi_edited_to_another_hi_doesnt_void_it(self): # add one real message then mock the receiver self.processor.process_incoming_event(data.thread_hi_message_json) self.processor._queue_manager.add = MagicMock() self.processor._queue_manager.void = MagicMock() # add answer to it self.processor.process_incoming_event( data.message_changed_hi_to_hi_event_json) # check self.processor._queue_manager.add.assert_not_called() self.processor._queue_manager.void.assert_not_called() def test_hi_edited_to_standard_text_voids_hi(self): # add one real message then mock the receiver self.processor.process_incoming_event(data.thread_hi_message_json) self.processor._queue_manager.add = MagicMock() self.processor._queue_manager.void = MagicMock() # add answer to it self.processor.process_incoming_event( data.message_changed_hi_to_std_event_json) # check self.processor._queue_manager.add.assert_not_called() self.processor._queue_manager.void.assert_called_once_with(mock.ANY) def test_hi_deleted_voids_hi(self): # add one real message then mock the receiver self.processor.process_incoming_event(data.thread_hi_message_json) self.processor._queue_manager.add = MagicMock() self.processor._queue_manager.void = MagicMock() # add answer to it self.processor.process_incoming_event( data.message_deleted_hi_event_json) # check self.processor._queue_manager.add.assert_not_called() self.processor._queue_manager.void.assert_called_once_with(mock.ANY) def test_following_messages_in_another_channel_doesnt_void_old_one(self): # add one real message then mock the receiver self.processor.process_incoming_event(data.thread_hi_message_json) self.processor._queue_manager.add = MagicMock() self.processor._queue_manager.void = MagicMock() # add answer to it self.processor.process_incoming_event( data.standard_message_in_another_channel_event_json) # check self.processor._queue_manager.add.assert_not_called() self.processor._queue_manager.void.assert_not_called()
import utils from contextlib import contextmanager from banner import Banner EVENT_API_FIELD_TYPE = "type" EVENT_API_FIELD_CHALLENGE = "challenge" EVENT_API_REQ_TYPE_URL_VERIFICATION = "url_verification" EVENT_API_REQ_TYPE_EVENT = "event_callback" SLACK_APP_API_KEY = "xoxb-241837748225-MZ9SgESli64vpVtUbbkWTMJR" message_processor = MessageProcessor() app = Flask(__name__) banner = Banner() class UnsupportedRequestException(BaseException): pass def handle_errors(func): """Decorator for functions that take single request argument and return dict response.""" def error_handling_wrapper(req): try: response = func(req) print("Responding:", response) except UnsupportedRequestException: print("UnsupportedRequestException:", req)
from message_processor import MessageProcessor SAYNOHI_HOMEPAGE = "https://distillery-tech.slack.com/apps/A69BQ5S2Z-say-no-hi" EVENT_API_FIELD_TYPE = "type" EVENT_API_FIELD_TOKEN = "token" EVENT_API_FIELD_CHALLENGE = "challenge" EVENT_API_REQ_TYPE_URL_VERIFICATION = "url_verification" EVENT_API_REQ_TYPE_EVENT = "event_callback" AUTH_API_ARG_CODE = "code" AUTH_API_ARG_STATE = "state" http_client = httplib2.Http(".cache") message_processor = MessageProcessor() app = Flask(__name__) # Flask app should start in global layout class UnsupportedRequestException(BaseException): pass @app.route('/webhook', methods=['POST', 'GET']) def webhook(): """Endpoint for event callbacks from slack""" req = request.get_json(silent=True, force=True) print("Got WebHook Request:", json.dumps(req, indent=4)) return process_event_api_request(req)
class TestMessageProcessor(TestCase): def setUp(self): self.message_processor = MessageProcessor(create_test_input_list()) def test_process_message(self): message = create_test_input_list()[0] self.message_processor._parse_message_two = mock.MagicMock() self.message_processor._apply_adjustments = mock.MagicMock() self.message_processor._parse_message_one = mock.MagicMock() self.message_processor.process_message(message) self.message_processor._parse_message_two.assert_called_with( message.lower().split()) message = create_test_input_list()[3] self.message_processor.process_message(message) self.message_processor._apply_adjustments.assert_called_with( message.lower().split()) message = create_test_input_list()[1] self.message_processor.process_message(message) self.message_processor._parse_message_one.assert_called_with( message.lower().split()) @mock.patch('message_processor.logging') def test_invalid_message_process_type_one(self, mock_logging): with self.assertRaises(Exception) as context: message = "Metroid Prime 4 at eightQuid" self.message_processor.process_message(message) expected_error = "Float required for product value: {}".format( message) self.assertTrue(mock_logging.warning.called) self.assertTrue(expected_error in context.exception) @mock.patch('message_processor.logging') def test_invalid_message_process(self, mock_logging): with self.assertRaises(Exception) as context: message = None self.message_processor.process_message(message) expected_error = "AttributeError: 'NoneType' object has no attribute 'lower'" self.assertTrue(expected_error in context.exception) self.assertTrue(mock_logging.warning.called) mock_logging.assert_called_with( "Could not parse message Some invalid input. \n {}".format( expected_error)) def test__apply_adjustments(self): adjustment_message = "Add 2 Animal Crossing".split( ) # use this for other test "Add 2 Giraffes on Unicycles" mock_sale = mock.MagicMock() mock_sale.product = "Animal Crossing" self.message_processor.sales_list = [mock_sale] self.message_processor._apply_adjustments(adjustment_message) self.assertTrue( self.message_processor.sales_list[0].add_adjustment.called) @mock.patch('message_processor.logging') def test__apply_adjustments_exceptions(self, mock_logging): with self.assertRaises(Exception) as context: adjustment_message = None self.message_processor._apply_adjustments(adjustment_message) expected_exception_err = "'NoneType' object is not subscriptable" expected_error = "Cannot parse adjustment message: {}".format( expected_exception_err) self.assertTrue(mock_logging.warning.called) mock_logging.assert_called_with(expected_error) @mock.patch('message_processor.Sale') def test__parse_message_one(self, mock_sale): message = "Animal Crossing at 34.98".split() self.message_processor._parse_message_one(message) mock_sale.assert_called_with("Animal Crossing", value=34.98) @mock.patch('message_processor.logging') def test__parse_message_one_exceptions(self, mock_logging): with self.assertRaises(Exception) as context: expected_error = "Cannot parse message type one: {}. Expected format <product> at <value>".format( " 'NoneType' object is not iterable") message = None self.message_processor._parse_message_one(message) mock_logging.assert_called_with(expected_error) self.assertTrue(mock_logging.warning.called) @mock.patch('message_processor.Sale') def test__parse_message_two(self, mock_sale): message = "5 of Animal Crossing at 34.98 each".split() self.message_processor._parse_message_two(message) mock_sale.assert_called_with("Animal Crossing", amount=5, value=34.98) @mock.patch('message_processor.logging') def test__parse_message_two_exceptions(self, mock_logging): with self.assertRaises(Exception) as context: expected_error = "Cannot parse message type one: {}. Expected format <product> at <value>".format( " 'NoneType' object is not iterable") message = None self.message_processor._parse_message_two(message) mock_logging.assert_called_with(expected_error) self.assertTrue(mock_logging.warning.called)
def setUp(self): self.message_processor = MessageProcessor(create_test_input_list())
class TestDuelling(unittest.TestCase): def setUp(self): ms = Mock() self.entityManager = Mock() self.mp = MessageProcessor(self.entityManager, ms) user1 = User(123) user1.set_name('TestUser1') user1.location = Location.ARENA user1.status = UserStatus.READY user2 = User(321) user2.set_name('TestUser2') user2.location = Location.ARENA user2.status = UserStatus.READY self.users = {123: user1, 321: user2} def user_return (c, field, chat_id): if int(chat_id) in self.users: return self.users[int(chat_id)] else: return None self.user_return = user_return def getAllByField(c, field, value): return [self.users[user] for user in self.users if self.users[user].location == value] self.getAllByField = getAllByField self.entityManager.getEntityByField = MagicMock(side_effect=self.user_return) self.entityManager.getAllByField = MagicMock(side_effect=self.getAllByField) def test_starting_duel_with_someone(self): self.mp.message(123, 'Duel') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) def test_starting_duel_with_no_one(self): self.users[321].location = Location.VILLAGE self.mp.message(123, 'Duel') self.assertEqual(self.users[123].status, UserStatus.READY) def test_send_invite_to_user(self): self.mp.message(123, 'Duel') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.mp.message(123, '321') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) def test_send_invite_to_user_busy(self): self.mp.message(123, 'Duel') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.users[321].status = UserStatus.GOING self.mp.message(123, '321') self.assertEqual(self.users[123].status, UserStatus.READY) def test_send_invite_to_user_other_location(self): self.mp.message(123, 'Duel') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.users[321].location = Location.VILLAGE self.mp.message(123, '321') self.assertEqual(self.users[123].status, UserStatus.READY) def test_send_invite_to_incorrect_user(self): self.mp.message(123, 'Duel') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.mp.message(123, '321632') self.assertEqual(self.users[123].status, UserStatus.READY) def test_send_invite_to_user_and_start_duel(self): self.mp.message(123, 'Duel') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.mp.message(123, '321') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.mp.message(321, 'Duel 123') self.assertEqual(self.users[123].status, UserStatus.DUELLING) self.assertEqual(self.users[321].status, UserStatus.DUELLING) def test_attack(self): self.mp.message(123, 'Duel') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.mp.message(123, '321') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.mp.message(321, 'Duel 123') self.assertEqual(self.users[123].status, UserStatus.DUELLING) self.assertEqual(self.users[321].status, UserStatus.DUELLING) self.mp.message(123, 'Attack') self.assertEqual(self.users[123].status, UserStatus.DUELLING_ATTACKED) self.assertEqual(self.users[321].status, UserStatus.DUELLING) self.mp.message(321, 'Attack') self.assertEqual(self.users[123].status, UserStatus.DUELLING) self.assertEqual(self.users[321].status, UserStatus.DUELLING) def test_duel_end(self): self.mp.message(123, 'Duel') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.mp.message(123, '321') self.assertEqual(self.users[123].status, UserStatus.STARTING_DUEL) self.mp.message(321, 'Duel 123') self.assertEqual(self.users[123].status, UserStatus.DUELLING) self.assertEqual(self.users[321].status, UserStatus.DUELLING) self.users[123].health = 1 self.mp.message(123, 'Attack') self.assertEqual(self.users[123].status, UserStatus.DUELLING_ATTACKED) self.assertEqual(self.users[321].status, UserStatus.DUELLING) self.mp.message(321, 'Attack') self.assertEqual(self.users[123].status, UserStatus.READY) self.assertEqual(self.users[321].status, UserStatus.READY)
import settings import key_helper public_key = key_helper.get_public_key_str() print("Loading blockchain") serialized_block_chain = file_helper.load_blockchain() block_chain = BlockChain.deserialize(serialized_block_chain) message_queue = Queue() transaction_queue = Queue() network = Network(public_key, message_queue) print("Starting miner") miner = Miner(network, public_key, transaction_queue) miner.start(block_chain, settings.DIFFICULTY) print("Starting network listener") message_processor = MessageProcessor(message_queue, network, block_chain, miner, public_key, settings.DIFFICULTY, transaction_queue) message_processor.start() network.publish('chain_request', block_chain.tail.height) def main(): print("Running") try: while True: time.sleep(1) except KeyboardInterrupt: print("Exiting gracefully") miner.stop() message_processor.stop()
class Arena: def __init__(self): print "loading credentials" try: print "Starting arena now, press ^C to stop the arena" self.gametick = 2 self.controller = Controller('/Users/philhouse/Library/Application Support/Dolphin/Pipes/player1') self._message_queue = Queue() self._controller_queue = Queue() self.message_processor = MessageProcessor( self._controller_queue, self._message_queue ) self.chat_stream = TwitchStream( self._message_queue ) # initialize contributions dictionary and last updates array self.contributions = {} self.latest_inputs = [] self.message_processor.start() self.chat_stream.start() # initialize requests call to update web and begin processing controls self.scoreboard_update = self.update_web() self.run() except KeyboardInterrupt: print "Stopped" self.message_processor.join() self.chat_stream.join() self.scoreboard_update.join() def run(self): print "now running" while True: time.sleep(.01) # self.controller.hit_button(Button.A) try: control = self._controller_queue.get(block=False) input = '' if 'direction' in control: self.controller.tilt_control( control['control'], control['direction'] ) input = str(control['control']) + ' ' + str(control['direction']) elif 'control' in control: self.controller.hit_button(control['control']) input = str(control['control']) print "receiving control: %s" % str(control) self.contributions[control['user']] = self.contributions.get(control['user'], 0) + 1 self.latest_inputs.append({'user': control['user'], 'input': input}) except Empty: pass def update_web(self): """ a method used for updating the web scoreboard with the current contributions :return: reference to timer object """ headers = {'Content-Type': 'application/json'} print "inside update web" data_blob = { 'top_contributors': self.contributions, 'latest_inputs': self.latest_inputs } resp = requests.post('http://localhost:3000/update_contributors', data=json.dumps(data_blob), timeout=1, headers=headers) print resp self.latest_inputs = [] self.scoreboard_update = threading.Timer(2, self.update_web) self.scoreboard_update.start() return self.scoreboard_update
engine.connect() Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() entity_manager = EntityManager(session) # Setting up bot polling updater = Updater(token=TOKEN) dispatcher = updater.dispatcher logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) ms = BotMessageSender(updater.bot) mp = MessageProcessor(entity_manager, ms) def start(bot, update): mp.start(update.message.chat_id, update.message.text) def message(bot, update): mp.message(update.message.chat_id, update.message.text) def broadcast(bot, update): mp.broadcast(update.message.chat_id, update.message.text) def go(bot, update):
if __name__ == '__main__': # intialize everything client = discord.Client() config = get_config() setup_logging(config) logger = logging.getLogger() db = database.ServerDatabase(config["dbuser"], config["dbname"], config["dbhost"], logger, config["dbpass"]) bot = Hasami(client, logger, config, db) message_processor = MessageProcessor(client, bot, config["prefix"], logger, db) # client events @client.event async def on_ready(): logger.info("logged in as {0}".format(client.user.name)) await bot.start() @client.event async def on_message(message): await message_processor.process_message(message) @client.event async def on_server_join(server): self._logger.info("Joined {0}".format(server.name)) db.add_server(server.id, server.name, config["prefix"])