def test_start(self): # A large set of mocks required to make sure that this test tests start, not # any other function # Does not currently cover exception in the event read loop resource = { 'resource': { 'SlackBotAccessToken': 'token' } } mock_messenger = MagicMock(return_value="dummy messenger") mock_event_handler = Mock() attrs = {'handle.return_value': "dummy return"} mock_event_handler.configure_mock(**attrs) mock_rtm = MagicMock(return_value=mock_event_handler) mock_slack_clients = MagicMock(return_value="dummy clients") slackbot = SlackBot("token", mock_slack_clients) slackbot.clients = Mock(rtm=Mock(rtm_connect=None, rtm_read=None, server=Mock(username=None, login_data={'team':{'name': None}}, domain=None))) slackbot.clients.rtm.rtm_connect = MagicMock(return_value=True) slackbot.clients.rtm.server.username = "******" slackbot.clients.rtm.server.login_data['team']['name'] = "dummy team name" slackbot.clients.rtm.server.domain = "dummy domain" slackbot.clients.rtm.rtm_read = MagicMock(return_value=['event1', 'event2', 'event3']) # Ensure that start completes without error self.assertEqual(slackbot.start(resource, mock_messenger, mock_rtm), None)
def test_start(self): # A large set of mocks required to make sure that this test tests start, not # any other function # Does not currently cover exception in the event read loop resource = {'resource': {'SlackBotAccessToken': 'token'}} mock_messenger = MagicMock(return_value="dummy messenger") mock_event_handler = Mock() attrs = {'handle.return_value': "dummy return"} mock_event_handler.configure_mock(**attrs) mock_rtm = MagicMock(return_value=mock_event_handler) mock_slack_clients = MagicMock(return_value="dummy clients") slackbot = SlackBot("token", mock_slack_clients) slackbot.clients = Mock( rtm=Mock(rtm_connect=None, rtm_read=None, server=Mock(username=None, login_data={'team': { 'name': None }}, domain=None))) slackbot.clients.rtm.rtm_connect = MagicMock(return_value=True) slackbot.clients.rtm.server.username = "******" slackbot.clients.rtm.server.login_data['team'][ 'name'] = "dummy team name" slackbot.clients.rtm.server.domain = "dummy domain" slackbot.clients.rtm.rtm_read = MagicMock( return_value=['event1', 'event2', 'event3']) # Ensure that start completes without error self.assertEqual(slackbot.start(resource, mock_messenger, mock_rtm), None)
def test_stop(self): # Test to ensure that the keep_running variable is properly set to false # When stop is called, and that stop returns without error mock_slack_clients = MagicMock(return_value="dummy clients") slackbot = SlackBot("token", mock_slack_clients) self.assertEqual(slackbot.stop("dummy resource"), None) self.assertEqual(slackbot.keep_running, False)
def main(): log_level = os.getenv("LOG_LEVEL", "INFO") logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=log_level) # Log this at error level even though it's not an error, because we want to be sure the message is seen logging.error("logging level: {}".format(log_level)) slack_token = os.getenv("SLACK_TOKEN", "") logging.info("slack token: {}".format(slack_token)) if slack_token == "": logging.info("SLACK_TOKEN env var not set, expecting token to be provided by Resourcer events") slack_token = None botManager = bot_manager.BotManager(spawn_bot) res = resourcer.Resourcer(botManager) res.start() else: state_updating_q = Queue() flask_thread = FlaskThread(state_updating_q) flask_thread.start() event_processing_q = Queue() intent_runner_pool = WorkerPoolThread(event_processing_q, state_updating_q) intent_runner_pool.start() # only want to run a single instance of the bot in dev mode bot = SlackBot(state_updating_q, event_processing_q, slack_token) bot.start({})
def main(): arguments = ArgumentParser().arguments Utils.make_dir(Config.log_dirpath) logger = Logger(filename=Config.log_filename, is_debug=arguments.debug) logger.info("Start crawling... (migrate={}, debug={})".format( arguments.migrate, arguments.debug)) news_list, df = Crawler(arguments.migrate, logger).execute() if len(news_list) > 0 and not arguments.migrate: slack_bot = SlackBot(Config.channel, Config.debug_channel, Config.slack_api_token) for news in news_list: message = Message.make_message(news) is_success, status = slack_bot.post_message( message, is_debug=arguments.debug) if is_success: logger.info(status) df.to_csv(Config.database_filename, index=False) else: logger.error(status) logger.info("Stop crawling... (migrate={}, debug={})".format( arguments.migrate, arguments.debug))
class Main(): def __init__(self): self.evaluate_images = EvaluateImages() self.slack_bot = SlackBot() def lookup_class(self, classImg): class_name = [] if classImg == 0: class_name = 'cats' elif classImg == 1: class_name = 'flowers' else: class_name = 'a pokemon' return class_name def print_status(self, classImg): print('tweet image') statusStr = 'Check out this image! I think I can see ' + self.lookup_class( classImg) print('status::::', statusStr) def main(self): classImg, img_id = self.evaluate_images.main() if classImg != -1: self.slack_bot.start_bot_and_post_img(self.lookup_class(classImg), img_id) self.print_status(classImg)
def teleop_message(channel: str, user_id: str = None): slack_bot = SlackBot(channel) # Get the onboarding message payload message = slack_bot.get_teleop_payload() # Post the onboarding message in Slack response = slack_web_client.chat_postMessage(**message)
def main(): browser = openbrowser(LOGIN_URL) login(browser) # Generate nanaco object nanaco = generate_nanaco(browser) # 設定額よりも低かった場合送信 if nanaco.money <= MIN_MONEY: slackBot = SlackBot('nanacoBot') slackBot.post_nanaco_status(nanaco)
def handler(event, context): crawler = Crawler() crawler.load_phantom(os.path.join(os.getcwd(), 'bin', 'phantomjs')) logger = logging.getLogger() logger.setLevel(logging.INFO) logger.info("Event: " + str(event)) posts = crawler.crawling() text = "\n".join(map(str, posts)) logger.info("Message: " + text) if posts: bot = SlackBot(slack_token, slack_channel) a = bot.send_message(text) return a
def main(): while True: # create objects cl_filter = CraigslistHousingFilter(CraigslistConfig) slack_bot = SlackBot(SlackConfig) # get matching Craigslist results results = cl_filter.get_matching_results() # post results to Slack for result in results: text = "{0} | {1} | {2} | <{3}>".format(result['where'], result['price'], result['name'], result['url']) slack_bot.post_to_channel(text) # sleep for an hour before repeating time.sleep(AppConfig.SLEEP_INTERVAL)
class MainPi(): def __init__(self): self.evaluate_images = EvaluateImages() self.twitter_keys = TwitterKeys() self.slack_bot = SlackBot() def lookup_class(self, classImg): class_name = [] if classImg == 0: class_name = 'cats' elif classImg == 1: class_name = 'flowers' else: class_name ='a pokemon' return class_name def take_picture(self): cmd = "raspistill -vf -o /home/pi/cloud-pareidolias/01-InputImages/img_20.jpg" subprocess.call(cmd, shell=True) print('take pic') def tweet_image(self, classImg): print('tweet image') twitter = Twython(self.twitter_keys.APP_KEY, self.twitter_keys.APP_SECRET, self.twitter_keys.OAUTH_TOKEN, self.twitter_keys.OAUTH_TOKEN_SECRET) photo = open('/home/pi/cloud-pareidolias/04-Results/final/img_20.jpg', 'rb') response = twitter.upload_media(media=photo) statusStr = 'Check out this image! I think I can see ' + self.lookup_class(classImg) print('status::::', statusStr) twitter.update_status(status=statusStr, media_ids=[response['media_id']]) def print_status(self, classImg): print('tweet image') statusStr = 'Check out this image! I think I can see ' + self.lookup_class(classImg) print('status::::', statusStr) def main(self): self.take_picture() time.sleep(5) classImg, img_id = self.evaluate_images.main() if classImg: self.slack_bot.start_bot_and_post_img(self.lookup_class(classImg), img_id) self.print_status(classImg)
def main(): log_level = os.getenv("LOG_LEVEL", "INFO") logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=log_level) # Log this at error level even though it's not an error, because we want to be sure the message is seen logging.error("logging level: {}".format(log_level)) slack_token = os.getenv("SLACK_TOKEN", "") logging.info("slack token: {}".format(slack_token)) if slack_token == "": logging.info( "SLACK_TOKEN env var not set, expecting token to be provided by Resourcer events" ) slack_token = None botManager = bot_manager.BotManager(spawn_bot) res = resourcer.Resourcer(botManager) res.start() else: # only want to run a single instance of the bot in dev mode bot = SlackBot(slack_token) bot.start({})
def __init__(self): self.interval = 5.0 self.running = False self.configParser = ConfigParser.RawConfigParser() self.configParser.read('config/dob.cfg') self.data_manager = DataManager(configParser=self.configParser) self.drive_watcher = GDriveWatcher(configParser=self.configParser, data_manager=self.data_manager) self.slack_bot = SlackBot(configParser=self.configParser) self.witmanager = WitAIManager(configParser=self.configParser) self.last_drive_scan = None
def run_slack_bot_worker(message): print(message) if message.chat.id in tg_bot.handlers: tg_bot.send_message(message.chat.id, "Already listen. use /unbind") try: slack_token = message.text.split(' ')[1] except IndexError: tg_bot.send_message(message.chat.id, "token is empty") else: slack_bot = SlackBot(token=slack_token, telegram_bot=tg_bot, telegram_chat_id=message.chat.id) _th = Thread(target=slack_bot.listen) tg_bot.handlers[message.chat.id] = _th _th.start() tg_bot.send_message(message.chat.id, "ok. listen your slack ...")
# queue topic options.alerttopic = get_config( 'alerttopic', 'mozdef.*', options.configfile) # how many messages to ask for at once options.prefetch = get_config('prefetch', 50, options.configfile) options.mq_alert_server = get_config('mqalertserver', 'localhost', options.configfile) options.mq_user = get_config('mquser', 'guest', options.configfile) options.mq_password = get_config('mqpassword', 'guest', options.configfile) options.mq_port = get_config('mqport', 5672, options.configfile) # mqack=True sets persistant delivery, False sets transient delivery options.mq_ack = get_config('mqack', True, options.configfile) if __name__ == "__main__": parser = OptionParser() parser.add_option( "-c", dest='configfile', default=sys.argv[0].replace('.py', '.conf'), help="configuration file to use") (options, args) = parser.parse_args() init_config() bot = SlackBot(options.slack_token, options.channels, options.name) monitor_alerts_thread = Thread(target=consume_alerts, args=[bot]) monitor_alerts_thread.daemon = True monitor_alerts_thread.start() bot.run()
from flask import Flask logger = logging.getLogger(__name__) server = Flask(__name__) @server.route ('/toto', methods=['GET']) def local_test(): return Response('it works') if __name__ == "__main__": port= os.getenv("PORT","not found") server.run(host='0.0.0.0',port=8080,debug=True) log_level = os.getenv("LOG_LEVEL", "INFO") logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=log_level) slack_token = os.getenv("SLACK_TOKEN", "") logging.info("token: {}".format(slack_token)) logging.info(port) if slack_token == "": logging.info("SLACK_TOKEN env var not set, expecting token to be provided by Resourcer events") slack_token = None botManager = bot_manager.BotManager(spawn_bot) res = resourcer.Resourcer(botManager) res.start() else: # only want to run a single instance of the bot in dev mode bot = SlackBot(slack_token) bot.start({})
# queue topic options.alerttopic = get_config('alerttopic', 'mozdef.*', options.configfile) # how many messages to ask for at once options.prefetch = get_config('prefetch', 50, options.configfile) options.mq_alert_server = get_config('mqalertserver', 'localhost', options.configfile) options.mq_user = get_config('mquser', 'guest', options.configfile) options.mq_password = get_config('mqpassword', 'guest', options.configfile) options.mq_port = get_config('mqport', 5672, options.configfile) # mqack=True sets persistant delivery, False sets transient delivery options.mq_ack = get_config('mqack', True, options.configfile) if __name__ == "__main__": parser = OptionParser() parser.add_option("-c", dest='configfile', default=sys.argv[0].replace('.py', '.conf'), help="configuration file to use") (options, args) = parser.parse_args() init_config() bot = SlackBot(options.slack_token, options.channels, options.name) monitor_alerts_thread = Thread(target=consume_alerts, args=[bot]) monitor_alerts_thread.daemon = True monitor_alerts_thread.start() bot.run()
def main(): slack_bot = SlackBot() slack_bot.connect()
def __init__(self): self.evaluate_images = EvaluateImages() self.slack_bot = SlackBot()
def test_init(self): mock_slack_clients = MagicMock(return_value="dummy clients") slackbot = SlackBot("token", mock_slack_clients) self.assertEqual(slackbot.clients, "dummy clients")
from slack_bot import SlackBot from slack_bot import spawn_bot logger = logging.getLogger(__name__) if __name__ == "__main__": log_level = os.getenv("LOG_LEVEL", "INFO") logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=log_level) config = yaml.load(file('bot.conf', 'r')) # debug = config["DEBUG"] slack_token = config["SLACK_TOKEN"] logging.info("token: {}".format(slack_token)) if slack_token == "": logging.info( "SLACK_TOKEN env var not set, expecting token to be provided by Resourcer events" ) slack_token = None botManager = bot_manager.BotManager(spawn_bot) res = resourcer.Resourcer(botManager) res.start() else: # only want to run a single instance of the bot in dev mode bot = SlackBot(slack_token) bot.start({})
# how many messages to ask for at once options.prefetch = get_config('prefetch', 50, options.configfile) options.mq_alert_server = get_config('mqalertserver', 'localhost', options.configfile) options.mq_user = get_config('mquser', 'guest', options.configfile) options.mq_password = get_config('mqpassword', 'guest', options.configfile) options.mq_port = get_config('mqport', 5672, options.configfile) # mqack=True sets persistant delivery, False sets transient delivery options.mq_ack = get_config('mqack', True, options.configfile) # wether or not the bot should send a welcome message upon connecting options.notify_welcome = get_config('notify_welcome', True, options.configfile) if __name__ == "__main__": parser = OptionParser() parser.add_option("-c", dest='configfile', default=sys.argv[0].replace('.py', '.conf'), help="configuration file to use") (options, args) = parser.parse_args() init_config() bot = SlackBot(options.slack_token, options.channels, options.name, options.notify_welcome) monitor_alerts_thread = Thread(target=consume_alerts, args=[bot]) monitor_alerts_thread.daemon = True monitor_alerts_thread.start() bot.run()
def __init__(self): self.evaluate_images = EvaluateImages() self.twitter_keys = TwitterKeys() self.slack_bot = SlackBot()
def flip_coin(channel): coin_bot = SlackBot(channel) message = coin_bot.get_message_payload() slack_web_client.chat_postMessage(**message)
from slackclient import SlackClient from slack_bot import SlackBot import os if __name__ == "__main__": SLACK_KEY = os.environ['SLACK_KEY'] RASA_API_URL = 'http://rasa-service:5000/chat' client_obj = SlackClient(SLACK_KEY) bot_id = client_obj.api_call("auth.test")["user_id"] bot = SlackBot(client_obj, bot_id, RASA_API_URL) bot.run()
# Arguments for slack parser.add_argument('--slack_channel', type=str, default='', help='For notifying the status of the recording') parser.add_argument('--slack_notifee', type=str, default='', help='Notifying if something when wrong') args = parser.parse_args() # Init the logger logger = Logger.init_logger(args.out_prefix, args.log_path, logging.DEBUG, LOG_LEVELS[args.log_level], args.saving_period) ffmpeg_logger = Logger.get_adapter(logger, '=== FFMPEG RECODER ===') g_logger = logger # Init the slack if args.slack_channel: slack_token = os.environ.get('SLACK_TOKEN', None) g_slack = SlackBotWrapper(SlackBot(slack_token ,args.slack_channel, args.slack_notifee)) else: g_slack = SlackBotWrapper(None) # Init the recoder and start recording g_recorder = FFmpegRecorder(args.protocol, args.src, args.enable_audio, args.segment_time, args.out_path, args.out_prefix, None, ffmpeg_logger) # Start monitoring thread g_monitor_thread = Thread(target=monitor, args=(args.out_prefix, args.out_path, args.monitor_interval, args.saving_period, args.restart_threshold)) g_monitoring = True g_event.clear() g_monitor_thread.start() # Start recorder
parser.add_argument('--slack_channels', type=str, help='Slack Bot channels for info, alert (seperated by commas)') parser.add_argument('--slack_notifee', type=str, help='ID of person for notification of alerts') parser.add_argument('--log_path', type=str, default='/tmp/slack-autoremoval', help='Location of logs') parser.add_argument('--log_level', type=str, default='error', choices=['critical', 'error', 'warning', 'info', 'debug'], help='Level of console logs') parser.add_argument('--log_saving_period', type=int, default=11, help='Number of days for saving logs') parser_archive = sub_parsers.add_parser('archive') parser_archive.add_argument('--start_date', type=str, help='Starting date of the archive: YYYYMMDD') parser_archive.add_argument('--end_date', type=str, help='Ending date of the archive: YYYYMMDD') parser_archive.set_defaults(func=archive_messages) # Parser the pargument args = parser.parse_args() # Init the logger logger_prefix = args.subparser_name if args.subparser_name else 'main' g_logger = Logger.init_logger(logger_prefix, args.log_path, logging.DEBUG, LOG_LEVELS[args.log_level], args.log_saving_period) # Init the slack bot if args.slack_token: chs = args.slack_channels.split(',') ch_info = chs[0] ch_alert = chs[1] if len(chs) > 1 else None g_slack = SlackBot(args.slack_token, ch_info, args.slack_notifee, channel_alert=ch_alert) # Call the function args.func(args)
class DOBService(object): def __init__(self): self.interval = 5.0 self.running = False self.configParser = ConfigParser.RawConfigParser() self.configParser.read('config/dob.cfg') self.data_manager = DataManager(configParser=self.configParser) self.drive_watcher = GDriveWatcher(configParser=self.configParser, data_manager=self.data_manager) self.slack_bot = SlackBot(configParser=self.configParser) self.witmanager = WitAIManager(configParser=self.configParser) self.last_drive_scan = None def start(self): if self.running: return logging.info('Service starting') self.setup() self.running = True # self.thread = threading.Thread(target=self.run, args=()) # self.thread.daemon = True # self.thread.start() self.run() def setup(self): self.data_manager.connect() self.drive_watcher.connect() self.slack_bot.connect() def run(self): while self.running: now = datetime.datetime.now() # get updated files if self.last_drive_scan is None or ((now - self.last_drive_scan).seconds * 0.0166667) >= 30: self.last_drive_scan = now updated_files = self.drive_watcher.update() self.broadcast_updated_files(updated_files) self.process_slack_messages() time.sleep(self.interval) def process_slack_messages(self): packets = self.slack_bot.update() for packet in packets: event_type = packet['type'] #if event_type == 'hello': #elif event_type == 'message': # self.process_slack_message(packet['message']) #elif event_type == 'user_typing': # #elif event_type == 'team_join': # #elif event_type == 'presence_change': # #else: # if event_type == 'message': self.process_slack_message(packet) def process_slack_message(self, packet): if packet is None or len(packet) == 0: return logging.info('Processing message {}'.format(packet)) if not self.is_valid_slack_message(packet): return user = self.slack_bot.users[packet['user']] channel = self.slack_bot.channels[self.slack_bot.get_channel_key_for_channel_with_id(packet['channel'])] text = packet['text'] if text is None or len(text) == 0: return import re matches = re.findall ('<@[a-zA-z0-9]*>:', text, re.DOTALL) idx = 0 for match in matches: #if ":" in match: if idx == 0: text = text.replace(match, "") else: user_id = match.replace("<", "").replace(">", "").replace("@", "").replace(":", "").strip() user = None if user_id in self.slack_bot.users: user = self.slack_bot.users[user_id] if user is not None: #text = text.replace(match, user['emailAddress']) text = text.replace(match, user['name']) else: text = text.replace(match, "") idx += 1 status, outcomes = self.witmanager.query(text) if outcomes is None or len(outcomes) == 0: return outcome = outcomes[0] # TODO: check that the first always has the highest confience value logging.info('Message has intent {}'.format(outcome.intent)) if outcome.intent == WitAIOutcome.INTENT_RETRIEVE_FILES: self.process_intent_to_retrieve_files(user, channel, outcome) def process_intent_to_retrieve_files(self, user, channel, outcome): min_date = None max_date = None contacts = [] for entity in outcome.entities: if entity.type == WitAIEntity.TYPE_CONTACT: if entity.value is None or len(entity.value) == 0: continue contacts.append(entity.value.lower()) elif entity.type == WitAIEntity.TYPE_DATE: cur_date = entity.value_to_date() if cur_date is not None: if min_date is None and max_date is None: min_date = cur_date max_date = cur_date else: if min_date > cur_date: min_date = cur_date if max_date < cur_date: max_date = cur_date # query db entities = self.data_manager.search_files(contacts=contacts, min_date=min_date, max_date=max_date) if entities is None or len(entities) == 0: msg = "@{} cannot find any files based on your search terms".format(user['name']) self.slack_bot.send_message(msg, channel=channel['id']) else: #msgs = [] msg = "here are some files matching your query:" for entity in entities: if entity.mimeType == GMimeType.Folder: continue #msgs.append("{} ({})".format(entity.title, entity.get_link())) msg += "\n" link = entity.get_link() if link is None or len(link) == 0: msg += "{}".format(entity.title) else: msg += "{} ({})".format(entity.title, entity.get_link()) #for msg in msgs: # self.slack_bot.send_message(msg, channel=channel['id']) self.slack_bot.send_message(msg, channel=channel['id']) def is_valid_slack_message(self, message): if 'channel' not in message: return False if 'text' not in message: return False channel = message['channel'] text = message['text'] mentions = DOBService.extract_entities_from_text(text) return self.slack_bot.me['user_id'] in mentions and channel == self.slack_bot.channels[self.slack_bot.channel]['id'] @staticmethod def extract_entities_from_text(text): import re return re.findall('<@(.*?)>', text, re.DOTALL) def broadcast_updated_files(self, updated_files): print "broadcast_updated_files; updated/added count {}".format(len(updated_files)) for entity in updated_files: msgs = self.construct_slack_message_for_entity(entity) for msg in msgs: self.slack_bot.send_message(msg) def construct_slack_message_for_entities(self, updated_files): now = datetime.datetime.now() updates_dict = {} msgs = [] for entity in updated_files: if (now - entity.modifiedDate).days >= 2: print "ignoring {}".format(entity.title) continue title = entity.title link = entity.get_link() if entity.createdDate == entity.modifiedDate: key = entity.get_owners() else: key = entity.get_modifier() if key not in updates_dict: updates_dict[key] = [] updates_dict[key].append((title, link)) # create messages for key, value in updates_dict.iteritems(): titles = value[0] links = value[1] if len(titles) == 1: msg = "{} updated {} ({})".format(key, titles[0], links[0]) else: msg = "{} has updated " for i in range(len(titles)): if i > 0: msg += ", " msg += titles[i] msg += " ({})".format(links[i]) msgs.append(msg) return msgs def construct_slack_message_for_entity(self, entity): now = datetime.datetime.now() if (now - entity.modifiedDate).days >= 2: print "ignoring {}".format(entity.title) return [] if entity.createdDate == entity.modifiedDate: return ["{} has created a new file {}\n{}".format( entity.get_owners(), entity.title, entity.get_link())] else: return ["{} has modified {}\n{}".format( entity.get_modifier(), entity.title, entity.get_link())] def stop(self): self.running = False