def alert_battery_level(slack_config, alert_level): slack_messenger = SlackMessenger(slack_config["alert_slack_token"], slack_config["alert_channel"], slack_config["alert_slackbot_name"]) slack_messenger.notify( slack_config["alert_list"], "Laptop battery is below " + str(alert_level) + "%.")
def alert_error(slack_config): slack_messenger = SlackMessenger(slack_config["alert_slack_token"], slack_config["alert_channel"], slack_config["alert_slackbot_name"]) slack_messenger.notify( slack_config["alert_list"], "Internal error for Battery Notifier, please check the logs.")
def report_battery_level(slack_config, battery_level): if slack_config.getboolean("reporting") is True: slack_messenger = SlackMessenger(slack_config["report_slack_token"], slack_config["report_channel"], slack_config["report_slackbot_name"]) slack_messenger.message("Current laptop battery level: " + str(battery_level) + "%.")
def process_exception(ex): if settings.SEND_EX_TO_SLACK: slack_msg = SlackMessenger(settings.USE_THIS_SLACK_CONFIG) slack_msg.handle_send_slack_internal_ex(ex) lg("Sent Slack Message", 0) else: lg("Hit Exception(" + str(ex) + ")", 0) return None
def process_exception(ex): if settings.SEND_EX_TO_SLACK: slack_msg = SlackMessenger(settings.USE_THIS_SLACK_CONFIG) slack_msg.handle_send_slack_internal_ex(ex) lg("Sent Slack Message", 0) else: lg("Hit Exception(" + str(ex) + ")", 0) return None
def main(): if len(sys.argv) < 2: print("Error: One argument (the message to send) must be provided.") sys.exit(1) s = SlackMessenger(slack_token, channel, slackbot_name) result = s.message(sys.argv[1]) log_result(result) if report: report_result(result)
def main(): config = Config("config/local-config.json").get_config() gr = GithubRetriever(config["participants"], config) sm = SlackMessenger(config) scores = get_leader_board(gr) sorted_scores = sorted([(p, scores[p]) for p in scores], key=lambda x: -x[1]) leaderboard_message = "Leetcode solution count leaderboard: \n" for s in sorted_scores: leaderboard_message = leaderboard_message + "{}: {} \n".format( s[0], s[1]) sm.send_message(leaderboard_message)
def handle_ajax_post(request): status = "Display Error" err_msg = "Failed to Process Post" record = { "StatusDiv" : "", "ResultDiv" : "" } try: posted_hash = simplejson.loads(request.body) if "Action" not in posted_hash: status = "Display Error" err_msg = "Missing 'Action' Key in POST" else: action = str(posted_hash["Action"]) lg("POST - Processing(" + str(action) + ")", 6) if action == "AjaxDemo": proc_rs = handle_post_ajax_demo(posted_hash) status = str(proc_rs["Status"]) err_msg = str(proc_rs["Error"]) record = proc_rs["Record"] # end of AjaxDemo else: status = "Display Error" err_msg = "Unsupported Ajax Action(" + str(action) + ")" lg("ERROR: Failed POST" + str(err_msg), 0) # If Slack is enabled, send the unsupported error: if settings.SEND_EX_TO_SLACK: slack_msg = SlackMessenger(settings.USE_THIS_SLACK_CONFIG) slack_msg.handle_send_slack_internal_ex(err_msg) # end of if send to slack # end of if a supported server-side action # end of handling all Posts # Assign final results: results = build_def_result(status, err_msg, record) except Exception,e: results = build_def_result("Display Error", "Failed to decode Post-ed JSON with Ex(" + str(e) + ")", record) lg("ERROR: " + str(e), 0) process_exception(e)
def handle_ajax_post(request): status = "Display Error" err_msg = "Failed to Process Post" record = {"StatusDiv": "", "ResultDiv": ""} try: posted_hash = simplejson.loads(request.body) if "Action" not in posted_hash: status = "Display Error" err_msg = "Missing 'Action' Key in POST" else: action = str(posted_hash["Action"]) lg("POST - Processing(" + str(action) + ")", 6) if action == "AjaxDemo": proc_rs = handle_post_ajax_demo(posted_hash) status = str(proc_rs["Status"]) err_msg = str(proc_rs["Error"]) record = proc_rs["Record"] # end of AjaxDemo else: status = "Display Error" err_msg = "Unsupported Ajax Action(" + str(action) + ")" lg("ERROR: Failed POST" + str(err_msg), 0) # If Slack is enabled, send the unsupported error: if settings.SEND_EX_TO_SLACK: slack_msg = SlackMessenger(settings.USE_THIS_SLACK_CONFIG) slack_msg.handle_send_slack_internal_ex(err_msg) # end of if send to slack # end of if a supported server-side action # end of handling all Posts # Assign final results: results = build_def_result(status, err_msg, record) except Exception, e: results = build_def_result( "Display Error", "Failed to decode Post-ed JSON with Ex(" + str(e) + ")", record) lg("ERROR: " + str(e), 0) process_exception(e)
def report_result(result): s = SlackMessenger(report_slack_token, report_channel, report_slackbot_name) result_body = "Response body:\n```\n" + \ json.dumps(result, indent=4, sort_keys=True) + "\n```" if result.get("ok"): s.operation_report("*SUCCESS*", "Sent message to channel. " + \ result_body) else: s.operation_report("*ERROR*", "Failed to send message to " +\ "Slack channel." + result_body) s.notify(report_alert_list, "Internal error, please check the logs.")
from slack_messenger import SlackMessenger if __name__ == '__main__': slack_messenger = SlackMessenger() # print(slack_messenger.test_post_on_hg_slack("testing...")) print(slack_messenger.upload_file_to_hg_fantasy_football_channel("reports/Things-Won't-Change(363515)/Things-Won't-Change(363515)_week-1_report.pdf"))
def slack_notify_users(alert_users, message_text): if report: s = SlackMessenger(report_slack_token, report_channel, report_slackbot_name) s.notify(alert_users, message_text) Logger.debug("Slack alert sent.")
#!/usr/bin/python from slack_messenger import SlackMessenger slack_config = { "BotName": "bugbot", "ChannelName": "debugging", "NotifyUser": "******", "Token": "xoxb-51351043345-oHKTiT5sXqIAlxwYzQspae54", "EnvName": "LocalDev" } slack_msg = SlackMessenger(slack_config) try: print "Testing an Exception that shows up in Slack" testing_how_this_looks_from_slack except Exception, k: print "Sending an error message to Slack for the expected Exception(" + str( k) + ")" slack_msg.handle_send_slack_internal_ex(k) # end of try/ex print "Done"
def event_handler(): # If a GET request is made, return 404. if request.method == 'GET': return make_response("These are not the slackbots you're looking for.", 404) # Parse the request payload into JSON event_data = json.loads(request.data.decode('utf-8')) # Verify the request token request_token = event_data.get("token") if SLACK_VERIFICATION_TOKEN != request_token: return make_response( "Request contains invalid Slack verification token", 403) # Echo the URL verification challenge code if "challenge" in event_data: return make_response(event_data["challenge"], 200, {"content_type": "application/json"}) if event_data["event"]["type"] == "message" or event_data["event"][ "type"] == "message.im": message_text = event_data["event"]["text"] message_channel = event_data["event"]["channel"] mentioned_user = 0 user_id, message_body = parse_direct_mention(message_text) direct_processed = False if user_id is not None: mentioned_user = user_id message_text = message_body if (message_channel.startswith("D") or mentioned_user == starterbot_id ) and event_data["event"]["user"] in globals()["bot_admin_users"]: messenger = SlackMessenger(slack_client) messenger.set_channel(message_channel) if message_text.startswith("!listProcesses"): if len(subprocesses) == 0: messenger.set_text( "There are no processes running on ABB right now.") messenger.send_message() else: reddit_process = {} slack_process = {} for process_name, process_info in subprocesses.items(): if process_info["type"] == "reddit": reddit_process[process_name] = process_info elif process_info["type"] == "slack": slack_process[process_name] = process_info header_attachment = Attachment("", "") reddit_attachment = Attachment("", "") slack_attachment = Attachment("", "") header_attachment.set_content( pretext= "These are the currently running processes on ABB", text= "The processes have been broken into two groups: those that monitor reddit and those that monitor slack" ) reddit_attachment.set_content( text="These processes run loops which monitor *reddit*" ) slack_attachment.set_content( text="These processes run loops which monitor *slack*") for reddit_name, reddit_info in reddit_process.items(): if reddit_info["process"].poll() is not None: reddit_attachment.add_field(title=reddit_name, value="Stopped", short=False) else: reddit_attachment.add_field( title=reddit_name, value="Running Since: " + reddit_info["start_dt"].strftime( "%b %d, %I:%M %p %Z"), short=False) for slack_name, slack_info in slack_process.items(): if slack_info["process"].poll() is not None: slack_attachment.add_field(title=slack_name, value="Stopped", short=False) else: slack_attachment.add_field( title=slack_name, value="Running Since: " + slack_info["start_dt"].strftime( "%b %d, %I:%M %p %Z"), short=False) messenger.add_attachment(header_attachment) messenger.add_attachment(reddit_attachment) messenger.add_attachment(slack_attachment) messenger.send_message() direct_processed = True elif message_text.startswith("!startProcess"): command = message_text.replace("!startProcess", "") command_args = command.split('|') process_args = {} for arg in command_args: arg_parts = arg.split(':') if len(arg_parts) == 2: arg_name = arg_parts[0].strip().lower() arg_val = arg_parts[1].strip() process_args[arg_name] = arg_val if "name" not in process_args: messenger.set_text( "A name is required to start a new process") messenger.send_message() messenger.set_channel(message_channel) if "script" not in process_args: messenger.set_text( "A script is required to start a new process") messenger.send_message() messenger.set_channel(message_channel) popen_script = shlex.split(process_args["script"]) if popen_script[0] != "python3" or popen_script[1].startswith( "../") or popen_script[1].startswith( "/") or popen_script[1].startswith("~"): globals()["bot_admin_users"] = [] panic_attachment = Attachment("", "") panic_attachment.set_content( pretext= "@channel An attempt to inject code into ActualBernieBot was detected from a slack user. Process management is locked until the bot is restarted.", text= "The information on the injection attempt is listed below." ) panic_attachment.add_field( title="From Slack User", value=list(slack_users.keys())[list( slack_users.values()).index( event_data["event"]["user"])], short=False) panic_attachment.add_field(title="Attempted Command", value=process_args["script"], short=False) panic_attachment.set_color(color="danger") messenger.set_channel(slack_channels["bot-notifications"]) messenger.add_attachment(panic_attachment) messenger.send_message() else: started = start_process(process_args["name"], process_args["type"], popen_script) if not started: messenger.set_text( "A process with that name is already running. Try !listProcesses to see which are on." ) messenger.send_message() else: messenger.set_text( "Your requested process has been started.") messenger.send_message() direct_processed = True elif message_text.startswith("!killProcess"): name = message_text.replace("!killProcess", "").strip() killed = kill_process(name) if not killed: messenger.set_text( "That process isn't currently running, so I can't kill it. Try !listProcesses to see which are on." ) messenger.send_message() else: messenger.set_text("The process *" + name + "* has been killed.") messenger.send_message() direct_processed = True elif message_text.startswith("!pauseProcess"): name = message_text.replace("!pauseProcess", "").strip() stopped = stop_process(name) if not stopped: messenger.set_text("That process doesn't exist.") messenger.send_message() else: messenger.set_text("The process *" + name + "* has been paused.") messenger.send_message() direct_processed = True elif message_text.startswith("!unpauseProcess"): name = message_text.replace("!unpauseProcess", "").strip() stopped = refresh_process(name) if not stopped: messenger.set_text("That process doesn't exist.") messenger.send_message() else: messenger.set_text("The process *" + name + "* has been unpaused.") messenger.send_message() direct_processed = True elif message_text.startswith("!restartProcess"): name = message_text.replace("!restartProcess", "").strip() restarted = restart_process(name) if not restarted: messenger.set_text( "Failed to restart process *" + name + "*. If it is in the process list, try stopping the process and starting it again." ) messenger.send_message() else: messenger.set_text("Process *" + name + "* has been restarted.") messenger.send_message() direct_processed = True elif message_channel.startswith( "D") or mentioned_user == starterbot_id: messenger = SlackMessenger() messenger.set_channel(message_channel) if message_text.startswith("!queueSize"): item_count = 0 for item in subreddit.mod.modqueue(limit=None): item_count += 1 messenger.set_text("The modqueue currently has *" + str(item_count) + "* items in it.") messenger.send_message() direct_processed = True elif message_text.startswith("!top"): top_post = subreddit.top(time_filter='day', limit=1) reddit_link = Attachment("", "") for post in top_post: reddit_link.set_content( text="This is the current post at the top of the sub") reddit_link.set_author( author_name=post.author.name, author_link="https://www.reddit.com/user/" + post.author.name) reddit_link.set_link(title=post.title, url=post.permalink) messenger.add_attachment(reddit_link) messenger.send_message() direct_processed = True elif message_text.startswith("!controversial"): contro_post = subreddit.controversial(time_filter='day', limit=1) reddit_link = Attachment("", "") for post in contro_post: reddit_link.set_content( text="This is today's most controversial post") reddit_link.set_author( author_name=post.author.name, author_link="https://www.reddit.com/user/" + post.author.name) reddit_link.set_link(title=post.title, url=post.permalink) messenger.add_attachment(reddit_link) messenger.send_message() direct_processed = True if direct_processed is False: sqs.send_message( QueueUrl= "https://sqs.us-east-1.amazonaws.com/068534578493/slackbotevent.fifo", MessageBody=json.dumps(event_data), MessageGroupId="slack-event", MessageDeduplicationId=event_data['event_id']) else: sqs.send_message( QueueUrl= "https://sqs.us-east-1.amazonaws.com/068534578493/slackbotevent.fifo", MessageBody=json.dumps(event_data), MessageGroupId="slack-event", MessageDeduplicationId=event_data['event_id']) return make_response("", 200)
def handle_command(command, channel): """ Executes bot command if the command is known """ # Default response is help text for the user default_response = "Not sure what you mean. Try *{}*.".format('help') # Finds and executes the given command, filling in response response = None response_sent = False # This is where you start to implement more commands! if command.startswith('!help'): response = "These are the commands available right now: !help, !time, !queueSize, !testComplex" elif command.startswith('!time'): response = datetime.now().timetz().isoformat() elif command.startswith('!queueSize'): print('Calculating Queue Size') item_count = 0 for item in subreddit.mod.modqueue(limit=None): item_count += 1 messenger = SlackMessenger() response = "The modqueue currently has *"+str(item_count)+"* items in it." result = messenger.set_text(response).set_channel(channel).send_message() if result: print('Queue Size Sent') else: print('Problem Sending Queue Size') response_sent = True elif command.startswith('!testComplex'): print('Building Complex') messenger = SlackMessenger(slack_client) attachment = Attachment("This should test a more complex message", "This should test a more complex message") attachment.set_author( author_name="JordanLeDoux", author_link="https://www.reddit.com/user/JordanLeDoux" ) attachment.set_content( text="This should test a more complex message", pretext="A test message now" ) attachment.set_color( color="good" ) attachment.set_footer( footer="Provided By ActualBernieBot" ) result = messenger.post_attachment(attachment, channel) if result: print('Complex Sent') else: print('Problem Sending Complex') response_sent = True elif command.startswith('!postQuote'): if "random" not in joined_channels: slack_client.api_call( "channels.join", channel=channel_list["random"] ) response = "I was told to post a quote here, but I'm not an intelligent bot yet..." channel = channel_list["random"] elif command.startswith('!banVote'): command = command.replace('!banVote', '') command_args = command.split('|') ban_args = {} for arg in command_args: arg_parts = arg.split(':') arg_name = arg_parts[0].strip().lower() arg_val = arg_parts[1].strip().lower() ban_args[arg_name] = arg_val if "user" not in ban_args: response = "The !banVote command requires a user parameter in this format: !banVote User: username | ..." if "type" not in ban_args: response = "The !banVote command requires a type parameter in this format: !banvote Type: temp | ..." elif ban_args["type"] == "temp": ban_args["type_readable"] = "Temporary" elif ban_args["type"] == "perm": ban_args["type_readable"] = "Permanent" if response is None: username = ban_args['user'] pretext = "A vote to ban has been called" text = "Please vote" actions = [ { 'name': 'ban', 'text': 'Permaban (Requested)', 'type': 'button', 'value': 'permaban', 'style': 'danger', 'confirm': { "title": "Are you sure?", "text": "This will permanently ban this user if the vote passes.", "ok_text": "Yes", "dismiss_text": "No" } }, { 'name': 'ban', 'text': 'Tempban (Default: 2 Days)', 'type': 'button', 'value': 'tempban' }, { 'name': 'ban', 'text': 'Warn Via PM (Using Cited Rules)', 'type': 'button', 'value': 'warn' }, { 'name': 'ban', 'text': 'No Action', 'type': 'button', 'value': 'none' } ] fields = [ { 'title': 'Duration', 'value': ban_args["type_readable"], 'short': True } ] color = "danger" slack_client.api_call( "chat.postMessage", channel=channel, callback_id="vote_button", attachments=[ { "author_name": username, "author_link": "https://www.reddit.com/user/" + username, "pretext": pretext, "text": text, "actions": actions, "fields": fields, "color": color, "mrkdwn_in": ["pretext", "text", "fields"], "footer": "Provided By ActualBernieBot" } ] ) #response = "I will call a vote to ban *"+ban_args["user"]+"* with a *"+ban_args["type_readable"]+"* ban" # Sends the response back to the channel if not response_sent: slack_client.api_call( "chat.postMessage", channel=channel, text=response or default_response )
def slack_report_message(operation_status, message_text): if report: s = SlackMessenger(report_slack_token, report_channel, report_slackbot_name) s.operation_report(operation_status, message_text) Logger.debug("Slack report sent.")
#!/usr/bin/python from slack_messenger import SlackMessenger slack_config = { "BotName" : "bugbot", "ChannelName" : "debugging", "NotifyUser" : "jay", "Token" : "xoxb-51351043345-oHKTiT5sXqIAlxwYzQspae54", "EnvName" : "LocalDev" } slack_msg = SlackMessenger(slack_config) try: print "Testing an Exception that shows up in Slack" testing_how_this_looks_from_slack except Exception,k: print "Sending an error message to Slack for the expected Exception(" + str(k) + ")" slack_msg.handle_send_slack_internal_ex(k) # end of try/ex print "Done"
use_chosen_week_function() report_info = use_default_league_function() fantasy_football_report = report_info[0] selected_league_id = report_info[1] generated_report = fantasy_football_report.create_pdf_report() upload_file_to_google_drive_bool = bool(distutils.strtobool(config.get("Google_Drive_Settings", "google_drive_upload"))) upload_message = "" if upload_file_to_google_drive_bool: # upload pdf to google drive google_drive_uploader = GoogleDriveUploader(generated_report) upload_message = google_drive_uploader.upload_file() print(upload_message) post_to_slack_bool = bool(distutils.strtobool(config.get("Slack_Settings", "post_to_slack"))) if post_to_slack_bool: if selected_league_id == config.get("Fantasy_Football_Report_Settings", "humangeo_id"): slack_messenger = SlackMessenger() # post shareable link to uploaded google drive pdf on slack # print(slack_messenger.post_to_hg_fantasy_football_channel(upload_message)) # upload pdf report directly to slack print(slack_messenger.upload_file_to_hg_fantasy_football_channel(generated_report)) print("DONE!") else: print("{}\n".format(upload_message)) print("DONE!")