def _handle_slackout(bot, event, command): """forward messages to slack over webhook""" slack_sink = bot.get_config_option('slack') if isinstance(slack_sink, list): for sinkConfig in slack_sink: try: slackkey = sinkConfig["key"] channel = sinkConfig["channel"] convlist = sinkConfig["synced_conversations"] if event.conv_id in convlist: fullname = event.user.full_name response = yield from bot._client.getentitybyid( [event.user_id.chat_id]) try: photo_url = "http:" + response['entity'][0][ 'properties']['photo_url'] except Exception as e: print("Slack: Could not pull avatar for {}".format( fullname)) client = SlackClient(slackkey) client.chat_post_message(channel, event.text, username=fullname, icon_url=photo_url) except Exception as e: print( "Could not handle slackout, is config.json properly configured?" )
def postOnSlack(channel, botName, message, access_token, log_type): slackMessage = "" channel = "#%s"%channel if (time.time() - exeptionHandlingModule.EHM_SLACK_POST_TIME) > 1: if log_type == exeptionHandlingModule.EHM_LOG: slackMessage = slackMessage + "[ %s - Log ] :information_source: \n"%exeptionHandlingModule.EHM_APP_NAME slackMessage = slackMessage + "```Message: %s \nEHM Code: %s ```"%(message, exeptionHandlingModule.EHM_LOG) elif log_type == exeptionHandlingModule.EHM_EXCEPTION_CRITICAL: slackMessage = slackMessage + "[ %s - CRITICAL ERROR ] :no_entry: \n"%exeptionHandlingModule.EHM_APP_NAME slackMessage = slackMessage + "```Message: %s \nEHM Code: %s ```"%(message, exeptionHandlingModule.EHM_LOG) elif log_type == exeptionHandlingModule.EHM_EXCEPTION_WARNING: slackMessage = slackMessage + "[ %s - WARNING ] :warning: \n"%exeptionHandlingModule.EHM_APP_NAME slackMessage = slackMessage + "```Message: %s \nEHM Code: %s ```"%(message, exeptionHandlingModule.EHM_LOG) elif log_type == exeptionHandlingModule.EHM_EXCEPTION_IGNORABLE: slackMessage = slackMessage + "[ %s - IGNORABLE ERROR ] :heavy_exclamation_mark: \n"%exeptionHandlingModule.EHM_APP_NAME slackMessage = slackMessage + "```Message: %s \nEHM Code: %s ```"%(message, exeptionHandlingModule.EHM_LOG) try: token = access_token client = SlackClient(token) client.chat_post_message(channel, slackMessage, username=botName) exeptionHandlingModule.EHM_SLACK_POST_TIME = time.time() except Exception, e: print "[ EHM ERROR ] while posting message to slack: %s"%e ehmlog("[ EHM ERROR ] while posting message to slack: %s"%e)
class SlackNotifier(Notifier): def __init__(self, token, channel): self.slack = SlackClient(token) self.channel = channel def post_message(self, bot_name='SoftLayer Nofitier', as_user=True, **kwargs): type = kwargs.get('type') account = kwargs.get('account') update = kwargs.get('update') update_date = kwargs.get('update_date') href = kwargs.get('href') id = kwargs.get('id') color = kwargs.get('color') attachments = dict() attachments['thumb_url'] = 'https://pbs.twimg.com/profile_images/969317315/CLEAN_sl-logo_400x400.jpg' attachments['color'] = kwargs.get('color') attachments['title'] = 'Notification of UPDATE: %s %s under %s' % ( type, id, account) attachments['title_link'] = href attachments['text'] = 'Update Date: %s\nUpdate Content:%s' % ( update_date, update) logging.debug('Slack message: %s' % str(attachments)) self.slack.chat_post_message(self.channel, '', username=bot_name, as_user=as_user, attachments=json.JSONEncoder().encode([attachments]))
def _handle_slackout(bot, event, command): """forward messages to slack over webhook""" slack_sink = bot.get_config_option('slack') if isinstance(slack_sink, list): for sinkConfig in slack_sink: try: slackkey = sinkConfig["key"] channel = sinkConfig["channel"] convlist = sinkConfig["synced_conversations"] if event.conv_id in convlist: fullname = event.user.full_name response = yield from bot._client.getentitybyid([event.user_id.chat_id]) try: photo_url = "http:" + response.entities[0].properties.photo_url except Exception as e: print("Slack: Could not pull avatar for {}".format(fullname)) client = SlackClient(slackkey) client.chat_post_message(channel, event.text, username=fullname, icon_url=photo_url) except Exception as e: print("Could not handle slackout with key {} between {} and {}. is config.json properly configured?".format(slackkey,channel,convlist))
class SlackSender(Module): def configure(self): self.client = SlackClient('YOUR_SLACK_API_TOKEN_HERE') self.current_run = None def process(self, blob): data = blob['CHData'] data_io = StringIO(data) preamble = DAQPreamble(file_obj=data_io) print(ctime()) print(preamble) event = DAQEvent(file_obj=data_io) print("Run: {0}".format(event.header.run)) print("Time Slice: {0}".format(event.header.time_slice)) if not self.current_run == event.header.run: self.current_run = event.header.run self.client.chat_post_message( "#du2-live", "Run #{0} has started!".format(event.header.run), username="******" ) return blob
def notify_results(results, credentials): try: if 'slack' in credentials and 'SLACK_TOKEN' in credentials['slack']: SLACK_TOKEN = credentials['slack']['SLACK_TOKEN'] SLACK_CHANNEL = credentials['slack']['SLACK_CHANNEL'] SLACK_USERNAME = credentials['slack']['SLACK_USERNAME'] client = SlackClient(SLACK_TOKEN) message_output = "Score %s for Test of \"%s\"\n\n"%(results['set'].get_score(), results['site'].title) message_output += "Full Report: %s\n\n"%(results['report_url']) # for message in results['messages']['success']: # message_output += (message+'\n\n') # for message in results['messages']['error']: # message_output += (message+'\n\n') # for message in results['messages']['warning']: # message_output += (message+'\n\n') # for message in results['messages']['info']: # message_output += (message+'\n\n') stripped = stripHtmlTags(message_output) client.chat_post_message(SLACK_CHANNEL, stripped, username=SLACK_USERNAME) else: logger.warn("Warning: Slack API credentials not supplied.") except Exception: logger.error("Error sending notification to Slack: %s"%(traceback.format_exc()))
def _handle_slackout(bot, event, command): if "_slack_no_repeat" in dir(event) and event._slack_no_repeat: return """forward messages to slack over webhook""" slack_sink = bot.get_config_option('slack') if isinstance(slack_sink, list): for sinkConfig in slack_sink: try: slackkey = sinkConfig["key"] channel = sinkConfig["channel"] convlist = sinkConfig["synced_conversations"] if event.conv_id in convlist: fullname = event.user.full_name response = yield from bot._client.getentitybyid( [event.user_id.chat_id]) try: photo_url = "http:" + response.entities[ 0].properties.photo_url except Exception as e: print("Slack: Could not pull avatar for {}".format( fullname)) client = SlackClient(slackkey) client.chat_post_message(channel, event.text, username=fullname, icon_url=photo_url) except Exception as e: print( "Could not handle slackout with key {} between {} and {}. is config.json properly configured?" .format(slackkey, channel, convlist))
class Slackchat: def __init__(self): settings = sublime.load_settings("SubSlack.sublime-settings") token = settings.get('token') self.bot = settings.get('bot_name') self.room = '#%s' % settings.get('default_chat') self.client = SlackClient(token) def post(self, text): self.client.chat_post_message(self.room, text, username=self.bot)
class Slackchat: def __init__(self): settings = sublime.load_settings("SubSlack.sublime-settings") token = settings.get("token") self.bot = settings.get("bot_name") self.room = "#%s" % settings.get("default_chat") self.client = SlackClient(token) def post(self, text): self.client.chat_post_message(self.room, text, username=self.bot)
def send_general(text): if settings.SLACK_ENABLED: connection = SlackClient(settings.SLACK_TOKEN) try: connection.chat_post_message( settings.SLACK_TEST_CHANNEL if settings.SLACK_TEST else settings.SLACK_GENERAL_CHANNEL, text, username=settings.SLACK_BOT, parse='full', unfurl_links='true') return True except: pass return False
def talk_to_slack(): # this function sends the same output of the files to slack get_last_data() token_dir = os.path.expanduser("~/.packages/conf/conf.txt") client = None if os.path.exists(token_dir): with open(token_dir, "r") as fp: client = SlackClient(fp.readlines()[0].strip()) with open(LOG_FILE_DIR, "a+") as fp: fp.write(last_data + "\n") if client is not None: client.chat_post_message("#mail-tracker-notif", last_data, username="******") sys.exit(0)
def _handle_slackout(bot, event, command): if "_slack_no_repeat" in dir(event) and event._slack_no_repeat: return """forward messages to slack over webhook""" slack_sink = bot.get_config_option('slack') if isinstance(slack_sink, list): for sinkConfig in slack_sink: try: slackkey = sinkConfig["key"] channel = sinkConfig["channel"] convlist = sinkConfig["synced_conversations"] if event.conv_id in convlist: fullname = event.user.full_name response = yield from bot._client.getentitybyid( [event.user_id.chat_id]) try: photo_url = "http:" + response.entities[ 0].properties.photo_url except Exception as e: logger.exception( "FAILED to acquire photo_url for {}".format( fullname)) photo_url = None try: client = SlackClient(slackkey, verify=True) except TypeError: client = SlackClient(slackkey) slack_api_params = { 'username': fullname, 'icon_url': photo_url } if "link_names" not in sinkConfig or sinkConfig[ "link_names"]: logger.debug("slack api link_names is active") slack_api_params["link_names"] = 1 client.chat_post_message(channel, event.text, **slack_api_params) except Exception as e: logger.exception( "Could not handle slackout with key {} between {} and {}." " Is config.json properly configured?".format( slackkey, channel, convlist))
def send_kill(kill_id): if settings.SLACK_ENABLED: connection = SlackClient(settings.SLACK_TOKEN) try: connection.chat_post_message( settings.SLACK_TEST_CHANNEL if settings.SLACK_TEST else settings.SLACK_KILL_CHANNEL, "https://zkillboard.com/kill/" + str(kill_id) + "/", username=settings.SLACK_BOT, parse='full', unfurl_links='true') return True except: pass return False
def talk_to_slack(): # this function sends the same output of the files to slack get_last_data() token_dir = os.path.expanduser('~/.packages/conf/conf.txt') client = None if os.path.exists(token_dir): with open(token_dir, 'r') as fp: client = SlackClient(fp.readlines()[0].strip()) with open(LOG_FILE_DIR, 'a+') as fp: fp.write(last_data + '\n') if client is not None: client.chat_post_message('#mail-tracker-notif', last_data, username='******') sys.exit(0)
def _handle_slackout(bot, event, command): if "_slack_no_repeat" in dir(event) and event._slack_no_repeat: return """forward messages to slack over webhook""" slack_sink = bot.get_config_option('slack') if isinstance(slack_sink, list): for sinkConfig in slack_sink: try: slackkey = sinkConfig["key"] channel = sinkConfig["channel"] convlist = sinkConfig["synced_conversations"] if event.conv_id in convlist: fullname = event.user.full_name response = yield from bot._client.getentitybyid([event.user_id.chat_id]) try: photo_url = "http:" + \ response.entities[0].properties.photo_url except Exception as e: logger.exception( "FAILED to acquire photo_url for {}".format(fullname)) photo_url = None try: client = SlackClient(slackkey, verify=True) except TypeError: client = SlackClient(slackkey) slack_api_params = {'username': fullname, 'icon_url': photo_url} if "link_names" not in sinkConfig or sinkConfig["link_names"]: logger.debug("slack api link_names is active") slack_api_params["link_names"] = 1 if bot.conversations.catalog[event.conv_id]["history"] or "otr_privacy" not in sinkConfig or not sinkConfig["otr_privacy"]: client.chat_post_message( channel, event.text, **slack_api_params) except Exception as e: logger.exception("Could not handle slackout with key {} between {} and {}." " Is config.json properly configured?".format(slackkey, channel, convlist))
def _slack_send(bot, sinkConfig, message, chat_id, passthru): _response = yield from bot._client.get_entity_by_id( hangups.hangouts_pb2.GetEntityByIdRequest( request_header = bot._client.get_request_header(), batch_lookup_spec = [ hangups.hangouts_pb2.EntityLookupSpec( gaia_id = chat_id )])) try: photo_url = "http:" + _response.entity[0].properties.photo_url except Exception as e: logger.exception("FAILED to acquire photo_url for {}".format(fullname)) photo_url = None if "original_request" in passthru: message = passthru["original_request"]["message"] if isinstance(passthru["original_request"]["user"], str): fullname = passthru["original_request"]["user"] else: fullname = _response.entity[0].properties.display_name; try: try: client = SlackClient(sinkConfig["key"], verify=True) except TypeError: client = SlackClient(sinkConfig["key"]) slack_api_params = { 'username': fullname, 'icon_url': photo_url } if "link_names" not in sinkConfig or sinkConfig["link_names"]: logger.debug("slack api link_names is active") slack_api_params["link_names"] = 1 client.chat_post_message(sinkConfig["channel"], message, **slack_api_params) except Exception as e: logger.exception( "Could not handle slackout with key {} between {} and {}. " "Is config.json properly configured?".format( slackkey, channel ))
def process_flow(self, data, jenkins_master): build_status = data.get('build').get('status') if build_status != 'FAILURE': self.log.debug('This flow will not be processed') return build_number = data.get('build').get('number') build = self.jenkins_master[data.get('name')].get_build(int(build_number)) build_name = build.name console = build.get_console() lines = console.split('\n') line_number = len(lines) index = 0 failed_jobs = {} while index < line_number: if lines[index].startswith('[Result] FAILURE'): job_name = lines[index - 1].lstrip('[Job Name]').lstrip().rstrip('\n') url = lines[index + 1].lstrip('[URL]').lstrip().rstrip('\n') failed_jobs[job_name] = url index = index + 1 full_url = data.get('build').get('full_url') if len(failed_jobs) == 0: msg = '<%s|%s> failed' % (full_url, build_name) else: failed_jobs_msg = '' for name in failed_jobs: failed_jobs_msg = ' '.join([failed_jobs_msg, '<%s|%s>' % (failed_jobs[name], name)]) msg = '<%s|%s> failed at %s' % (full_url, build_name, failed_jobs_msg) self.log.debug('Slack message: %s' % msg) slack_token = self.config['slack']['token'] slack_botname = self.config['slack']['name'] slack_channel = self.config['slack']['channel'] slack = SlackClient(slack_token) slack.chat_post_message(slack_channel, msg, username=slack_botname, mrkdwn=True)
def _slack_send(bot, sinkConfig, message, chat_id, passthru): _response = yield from bot._client.get_entity_by_id( hangups.hangouts_pb2.GetEntityByIdRequest( request_header=bot._client.get_request_header(), batch_lookup_spec=[ hangups.hangouts_pb2.EntityLookupSpec(gaia_id=chat_id) ])) try: photo_url = "http:" + _response.entity[0].properties.photo_url except Exception as e: logger.exception("FAILED to acquire photo_url for {}".format(fullname)) photo_url = None if "original_request" in passthru: message = passthru["original_request"]["message"] if isinstance(passthru["original_request"]["user"], str): fullname = passthru["original_request"]["user"] else: fullname = _response.entity[0].properties.display_name try: try: client = SlackClient(sinkConfig["key"], verify=True) except TypeError: client = SlackClient(sinkConfig["key"]) slack_api_params = {'username': fullname, 'icon_url': photo_url} if "link_names" not in sinkConfig or sinkConfig["link_names"]: logger.debug("slack api link_names is active") slack_api_params["link_names"] = 1 client.chat_post_message(sinkConfig["channel"], message, **slack_api_params) except Exception as e: logger.exception( "Could not handle slackout with key {} between {} and {}. " "Is config.json properly configured?".format(slackkey, channel))
class ChatClient(): def __init__(self, token, user, send_to): self.client = SlackClient(token) self.user = user self.send_to = send_to def _send_msg(self, msg): self.client.chat_post_message(self.send_to, msg, username=self.user) def allow_airline(self, airline, iata): self._send_msg("Airline '%s (%s)' allowed in search" % (airline, iata)) def disable_airline(self, airline, iata, reason): self._send_msg("Airline '%s (%s)' disabled in search because: %s" % (airline, iata, reason)) def start_scraping(self, airline, iata): self._send_msg("Scraping of airline '%s (%s)' started" % (airline, iata)) def stop_scraping(self, airline, iata, reason): self._send_msg("Scraping of airline '%s (%s)' stopped because: %s" % (airline, iata, reason)) def start_automat(self, airline, iata): self._send_msg("Automat for airline '%s (%s)' started" % (airline, iata)) def stop_automat(self, airline, iata, reason): self._send_msg("Automat for airline '%s (%s)' stopped because: %s" % (airline, iata, reason)) def saving_deactivated(self, iata): self._send_msg("Saving results to DB deactivated for airline '%s' " % (iata)) def saving_activated(self, iata): self._send_msg("Saving results to DB activated for airline '%s' " % (iata))
def post(self, request): serializer = SlackChatSerializer(data=request.data) client = SlackClient( 'xoxp-4254176702-8269771440-11734785028-c59bdd6fab') if serializer.is_valid(): try: message_construct = serializer.data['message_construct'] chat_message = client.chat_post_message('#help', message_construct, username='******') content = {'data': chat_message} return Response(content) except ObjectDoesNotExist: raise Http404
def notify(message): api = SlackClient(config.SLACK_API_KEY) channel = config.SLACK_CHANNEL username = config.SLACK_USERNAME api.chat_post_message(channel, message, username=username, as_user=False)
#!/usr/bin/env python from pyslack import SlackClient import requests from BeautifulSoup import BeautifulSoup slack_token = 'get-ur-own' client = SlackClient(slack_token) url = 'https://www.gfoodtrucks.com/kiosklanding/all' r = requests.get(url) soup = BeautifulSoup(r.content) today = soup.find('div', {'id': 'tab_0'}) message = '' for box in today.findAll('div', {'class': 'ordering_box'}): truck_name = box.find('strong').string truck_type = box.find('span').string message = message + truck_name.strip() + " : " + truck_type.strip() + '\n' client.chat_post_message('#sfo', message, username='******')
def _send_to_external_chat(self, config, event): conv_id = config["trigger"] relay_channels = config["config.json"][self.configkey] user = event.passthru["original_request"]["user"] message = event.passthru["original_request"]["message"] if not message: message = "" # XXX: rudimentary conversion of html to markdown message = re.sub(r"</?b>", "*", message) message = re.sub(r"</?i>", "_", message) message = re.sub(r"</?pre>", "`", message) bridge_user = self._get_user_details(user, { "event": event }) try: client = SlackClient(config["config.json"]["key"], verify=True) except TypeError: client = SlackClient(config["config.json"]["key"]) slack_api_params = { 'username': bridge_user["preferred_name"], 'icon_url': bridge_user["photo_url"] } if "link_names" not in config["config.json"] or config["config.json"]["link_names"]: slack_api_params["link_names"] = 1 """XXX: deferred image sending this plugin leverages existing storage in hangouts - since there isn't a direct means to acquire the public url of a hangups-upload file we need to wait for other handlers to post the image in hangouts, which generates the public url, which we will send in a deferred post. handlers.image_uri_from() is packaged as a task to wait for an image link to be associated with an image id that this handler sees """ if( "image_id" in event.passthru["original_request"] and event.passthru["original_request"]["image_id"] ): if( "conv_event" in event and "attachments" in event.conv_event and len(event.conv_event.attachments) == 1 ): message = "shared an image: {}".format(event.conv_event.attachments[0]) else: # without attachments, create a deferred post until the public image url becomes available image_id = event.passthru["original_request"]["image_id"] loop = asyncio.get_event_loop() task = loop.create_task( self.bot._handlers.image_uri_from( image_id, self._send_deferred_photo, relay_channels, client, slack_api_params )) """standard message relay""" for relay_channel in relay_channels: client.chat_post_message(relay_channel, message, **slack_api_params)
return sub_expire # Main salt_root = "/salt/" pillar_filelist = [] for root, dirs, files in os.walk(salt_root): for f in files: if "/pillar/" in root: pillar_filelist.append(os.path.join(root, f)) report_data = extract_certs(pillar_filelist) for entry in report_data: slack_client = SlackClient(slack_api_key) slack_message = "" subject = report_data[entry][0] expire_after = report_data[entry][1] if (expire_after - timedelta(days=30)) < datetime.now(): slack_message = "*ACTION REQUIRED:* A certificate found in `{}`, with a subject of `{}`, is expired/will expire on *{}*.".format( entry, subject, expire_after) elif (expire_after - timedelta(days=60)) < datetime.now(): slack_message = "*Warning:* A certificate found in `{}`, with a subject of `{}`, will expire on *{}*.".format( entry, subject, expire_after) if slack_message: slack_client.chat_post_message(slack_channel, slack_message, username=slack_username)
async def _send_to_external_chat(self, config, event): conv_id = config["trigger"] relay_channels = config["config.json"][self.configkey] user = event.passthru["original_request"]["user"] message = event.passthru["original_request"]["message"] if not message: message = "" # XXX: rudimentary conversion of html to markdown message = re.sub(r"</?b>", "*", message) message = re.sub(r"</?i>", "_", message) message = re.sub(r"</?pre>", "`", message) bridge_user = self._get_user_details(user, { "event": event }) try: client = SlackClient(config["config.json"]["key"], verify=True) except TypeError: client = SlackClient(config["config.json"]["key"]) slack_api_params = { 'username': bridge_user["preferred_name"], 'icon_url': bridge_user["photo_url"] } if "link_names" not in config["config.json"] or config["config.json"]["link_names"]: slack_api_params["link_names"] = 1 """XXX: deferred image sending this plugin leverages existing storage in hangouts - since there isn't a direct means to acquire the public url of a hangups-upload file we need to wait for other handlers to post the image in hangouts, which generates the public url, which we will send in a deferred post. handlers.image_uri_from() is packaged as a task to wait for an image link to be associated with an image id that this handler sees """ if( "image_id" in event.passthru["original_request"] and event.passthru["original_request"]["image_id"] ): if( "conv_event" in event and "attachments" in event.conv_event and len(event.conv_event.attachments) == 1 ): message = "shared an image: {}".format(event.conv_event.attachments[0]) else: # without attachments, create a deferred post until the public image url becomes available image_id = event.passthru["original_request"]["image_id"] loop = asyncio.get_event_loop() task = loop.create_task( self.bot._handlers.image_uri_from( image_id, self._send_deferred_photo, relay_channels, client, slack_api_params )) """standard message relay""" for relay_channel in relay_channels: client.chat_post_message(relay_channel, message, **slack_api_params)
#keywords to search, need to pull these from the yaml too. tier1 = ['Looking to join', 'group of friends', 'new person'] tier2 = ['joining',"settlement","large city","small city","large town","small town","start"] #don't change below plz while True: print 'Checking for more newfriends...' subreddit = r.get_subreddit('civcraft') for submission in subreddit.get_new(limit=10): op_text = submission.selftext.lower() has_newfriend = False if any(string in op_text for string in tier1): has_newfriend = True for x in range(len(tier2)): if tier2[x] in op_text or submission.title: if any(string in op_text for string in tier2) and not tier2[x]: has_newfriend = True flair = submission.author_flair_text if submission.id not in already_done and has_newfriend and not flair: output = open("output.txt","a") msg = '[NEWFRIEND?] ' + submission.title + submission.short_link client.chat_post_message(channel, msg, username='******') already_done.append(submission.id) output.write(submission.id+"\n") print 'Sending to Slack!' time.sleep(120) else: print '\033[1m' + submission.title + '\033[0m' + ' does not meet criteria, moving on' time.sleep(10)
from pyslack import SlackClient client = SlackClient('') client.chat_post_message('#group3', "testing, testing...", username='******')
import ConfigParser import time # Get config information from ../Authentication/Slack.cfg config = ConfigParser.RawConfigParser() config.read("../Authentication/Slack.cfg") __token__ = config.get("LogPoster", "token") # User token from config file to generate client = SlackClient(__token__) __channel__ = "#logging-scripts" __username__ = "Script Logger" client.chat_post_message(__channel__, "Update-ComputerStatistics; Start time: 2:03", username=__username__) time.sleep(2.5) client.chat_post_message(__channel__, "Update-ComputerStatistics; End time: 2:05", username=__username__) __username__ = "SQL Job Logger" time.sleep(2.5) client.chat_post_message(__channel__, "Repopulate CMDB Table; Start time: 2:05", username=__username__) time.sleep(2.5) client.chat_post_message(__channel__, "Repopulate CMDB Table; End time: 2:05", username=__username__) raw_input() __channel__ = "#logging-serverstats" __username__ = "Statistics Logger" client.chat_post_message(__channel__, "APPSERVER01: [CPU]:20% - [RAM]:64% - [Tasks Running]:2", username=__username__) time.sleep(1) client.chat_post_message( __channel__, "SQLSERVER01: [CPU]:4% - [RAM]:15% - [Open Connections]:12", username=__username__
from pyslack import SlackClient import os token = os.environ['SLACK_TOKEN'] if token == '': print('Could not get SLACK_TOKEN') exit(1) client = SlackClient(token) client.chat_post_message('#log', "Posted from post.py: hello!", username='******')
class newsReporterBase: def __init__(self): self.blacklist = ['http://Amazon.co.jp/', 'http://Amazon.co.jp'] self.slack_client = SlackClient(self.slack_token) def run(self): try: rows = self._summarise_rows() self._report_to_slack(rows, self.channel) except Exception as e: message = 'ニュースの更新に失敗しました: ' + str(e) self.slack_client.chat_post_message( self.channel, message, username=self.slackname ) def _summarise_rows(self): target_time = self._calc_target_time() rows = self._request_urls(200, target_time) return self._select_keys(rows) def _calc_target_time(self): target_time = datetime.now() + timedelta(hours=-self.waybackhours) return int(target_time.strftime('%s')) def _request_urls(self, count, target_time): reporter = tl.urlReporter(**self.twitter_conf) rows = reporter.request_urls( count=count, target_time=target_time, **self.twlist_conf ) return rows def _select_keys(self, rows): formed_row = (self._form_row(r) for r in rows if r['url'] not in self.blacklist) return sorted(formed_row, key=lambda x: x['value'], reverse=True) def _form_row(self, row): favorite = max(row['favorite_counts']) retweet = max(row['retweet_counts']) return { 'url': row['url'], 'title': self._check_title(row['title']), 'value': favorite + retweet } def _check_title(self, title): if title is None: return '[タイトルが取得できませんでした]' else: return title.strip() def _report_to_slack(self, rows, channel, threshold=0): filtered_rows = [r for r in rows if r['value'] >= threshold] message = self._form_message(filtered_rows) if len(message) <= 1800: self.slack_client.chat_post_message( channel, message, username=self.slackname ) else: self._report_to_slack(filtered_rows, channel, threshold+1) def _form_message(self, rows): template = '>>>{body}' body = self._form_body(rows) message = template.format(body=body, domain=self.domain) return message def _form_body(self, rows): if len(rows) >= 1: return '\n\n'.join(self._form_each_row(**r) for r in rows) else: return '最新のツイートはありません'.format(self.domain) def _form_each_row(self, url, title, value): elems = self._pick_elems(url, title, value) return '\n'.join(elems) def _pick_elems(self, url, title, value): if value >= 1: return [self._make_stars(value), title, url] else: return [title, url] def _make_stars(self, value): if value >= 10: return ':star:×' + str(value) else: return ':star:' * value
Y.append(1 - noseHeight(x,y,z)/noseHeight(comX,comY,comZ)) #鼻の横幅 Y.append(diff(x,y,z,comX,comY,comZ,31,35)) #口横幅 Y.append(diff(x,y,z,comX,comY,comZ,48,54)) #パーツ間距離 Y.append(diff(x,y,z,comX,comY,comZ,39,42)) Y.append(diff(x,y,z,comX,comY,comZ,21,22)) Y.append(diff(x,y,z,comX,comY,comZ,33,51)) Y.append(diff(x,y,z,comX,comY,comZ,57,8)) num = 0 for j in range(0,len(Y)): num+=fabs(Y[j]) print name[i] print num if (num/len(Y))<error: error = (num/len(Y)) authedName = name[i] authedName += ' has come' client.chat_post_message('#bot_dev',authedName,username='******') #for i in range(0,12): # X.append(i) #print X,Y #plt.bar(X,Y) #plt.show() except: pass cv2.destroyAllWindows()
# https://api.slack.com/community # https://api.slack.com/community#python # v1 avec ce client : # https://github.com/loisaidasam/pyslack from pyslack import SlackClient # https://api.slack.com/apps botUserOAuthAccessToken = input("Bot User OAuth Access Token ? ") print("Bot User OAuth Access Token : ", botUserOAuthAccessToken) client = SlackClient(botUserOAuthAccessToken) client.chat_post_message('#dev', "Hello ", username='******')
def main(): opts = parse_args() cfg = yaml.load(open(opts.config)) # match Yaml options to commandline options try: if cfg['mail']['frommail'] != "": opts.frommail = cfg['mail']['frommail'] except: pass try: if cfg['mail']['tomail'] != "": opts.tomail = cfg['mail']['tomail'] except: pass try: if cfg['mail']['smtphost'] != "": opts.smtphost = cfg['mail']['smtphost'] except: pass try: if cfg['mail']['smtpport'] != "": opts.smtpport = int(cfg['mail']['smtpport']) except: pass try: if cfg['mail']['usessl'] != "": opts.usessl = bool(cfg['mail']['usessl']) except: pass try: if cfg['mail']['username'] != "": opts.username = cfg['mail']['username'] except: pass try: if cfg['mail']['password'] != "": opts.password = cfg['mail']['password'] except: pass try: if cfg['interval'] != "": opts.interval = int(cfg['interval']) except: pass try: if cfg['update'] != "": opts.update = bool(cfg['update']) except: pass try: if cfg['queries'] != "": opts.queries = cfg['queries'] except: pass try: if cfg['slackroom'] != "": opts.slackroom = cfg['slackroom'] except: pass try: if cfg['slacktoken'] != "": opts.slacktoken = cfg['slacktoken'] except: pass try: if cfg['slackuser'] != "": opts.slackuser = cfg['slackuser'] except: pass try: if cfg['verbose'] != "": opts.verbose = bool(cfg['verbose']) except: pass # print debug info if opts.verbose: print("from mail: " + opts.frommail) print("to mail: " + str(opts.tomail)) print("smtp host: " + opts.smtphost) print("smtp port: " + str(opts.smtpport)) print("use ssl: " + str(opts.usessl)) print("username: "******"interval: " + str(opts.interval)) print("update: " + str(opts.update)) print("queries: " + str(opts.queries)) print("slack room: " + str(opts.slackroom)) print("slack user: "******"Adding document: " + md['title'] + " (" + file['id'] + ")") docs[file['id']] = None # Check that we are not getting too many documents if counter > 999: print("WARNING: Query returns too many documents, not tracking all docs: " + query) # Track if there where changes foundChanges = False # A mail message to send via mail mailMessageBody = "" # A message to be sent via slack slackMessageBody = "" # Iterate over the documents we monitor for doc,modifiedDate in docs.items(): # Get information about the specified file. This will throw # an exception if the file does not exist. md = gd.get_file_metadata(doc) if md['mimeType'] == 'application/vnd.google-apps.document': # Get some metadata for the file we track if modifiedDate is None: modifiedDate=md['modifiedDate'] title = md['title'] try: md['embedLink'] except KeyError: editLink = "" else: editLink = md['embedLink'].replace('preview', 'edit') # Iterate over the revisions (from oldest to newest). lastRevModifiedDate=None for rev in gd.revisions(doc): lastRevModifiedDate = rev['modifiedDate'] if modifiedDate != lastRevModifiedDate: foundChanges = True if lastRevModifiedDate is None: print("Need Edit access to: " + title + " (" + editLink + ")") mailMessageBody += '<li><a href="' + editLink + '">' + title + ' (need edit access)</a></li>' + os.linesep slackMessageBody += '<' + editLink + '|*' + title + ' (need edit access)*>' + os.linesep else: print("Document Change: " + title + " (" + editLink + ")") mailMessageBody += '<li><a href="' + editLink + '">' + title + '</a></li>' + os.linesep slackMessageBody += '<' + editLink + '|*' + title + '*>' + os.linesep if lastRevModifiedDate is None: docs[md['id']] = modifiedDate else: docs[md['id']] = lastRevModifiedDate # Write out the new files list and dates if opts.update and foundChanges: print("Updating file list") # write new file list f = open('myfilelist.py.new', 'w') f.write("docs={}\n") # Iterate over the documents we monitor for doc,modifiedDate in docs.items(): if modifiedDate is not None: f.write('docs["' + doc + '"] = "' + modifiedDate + '"\n') f.close() # put new file in place os.rename('myfilelist.py.new', 'myfilelist.py') if opts.slackuser != "" and opts.slackroom != "" and opts.slacktoken != "" and slackMessageBody != "": print("Sending slack with changes") client = SlackClient(opts.slacktoken) client.chat_post_message("#" + opts.slackroom, ">>> The following documents have been changed since the last scan" + os.linesep + slackMessageBody, username=opts.slackuser) # Send a mail with the changes # # If you get: smtplib.SMTPAuthenticationError: (534... when using gmail # you need to enable less secure access at https://www.google.com/settings/u/1/security/lesssecureapps # if opts.frommail != "" and mailMessageBody != "": print("Sending email with changes") finalMessageBody = "<html><head></head><body><ul>" + mailMessageBody + "</ul></body>" msg = MIMEText(finalMessageBody, 'html') msg['Subject'] = "The following documents have been changed since the last scan" msg['From'] = opts.frommail msg['To'] = ', '.join(opts.tomail) # Send the message via our own SMTP server, but don't include the # envelope header. if opts.usessl: s = smtplib.SMTP_SSL(opts.smtphost, opts.smtpport) else: s = smtplib.SMTP(opts.smtphost, opts.smtpport) s.ehlo() s.starttls() if opts.username != "": s.login(opts.username, opts.password) s.sendmail(opts.frommail, opts.tomail, msg.as_string()) s.quit() # Bail out if we don't want to loop if opts.interval == 0: break else: time.sleep(opts.interval * 60)