Created
August 10, 2020 11:03
-
-
Save csghone/56a654a90aa23dd0d2e8bc370650f25b to your computer and use it in GitHub Desktop.
Send messages/files to Slack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
eg: | |
./send_to_slack.py -u csghone '#testingbots' -m hello -e heavy_check_mark | |
./send_to_slack.py -u csghone '#testingbots' -a send_file -f /path/to/myfile -e heavy_check_mark -m hello | |
""" | |
from __future__ import print_function | |
import os | |
import sys | |
import json | |
import argparse | |
import traceback | |
import logging | |
import logging.handlers | |
try: | |
from slack import WebClient | |
except: | |
print("Upgrade slackclient", file=sys.stderr) | |
logger = logging.getLogger() | |
LOG_FORMATTER = logging.Formatter( | |
"%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - " + | |
"%(lineno)s - %(funcName)s - " + | |
"%(message)s", | |
"%Y%m%d %H:%M:%S") | |
def setup_logging(level=logging.INFO, enable_console=True): | |
console_log_handler = logging.StreamHandler() | |
if enable_console: | |
logger.addHandler(console_log_handler) | |
logger.setLevel(level) | |
for handler in logging.root.handlers: | |
handler.setFormatter(fmt=LOG_FORMATTER) | |
def process(**kwargs): | |
users = kwargs["users"] | |
action = kwargs["action"] | |
message = kwargs["message"] | |
title = kwargs["title"] | |
file_to_send = kwargs.get("file_to_send") | |
emoji_name = kwargs.get("emoji_name") | |
for index, item in enumerate(users): | |
if item[0] not in ["U", "C", "@", "#"]: | |
users[index] = "@" + item | |
token = "PUT YOUR TOKEN HERE" | |
assert token != "PUT YOUR TOKEN HERE", print("Update your token", file=sys.stderr) | |
slack_client = WebClient(token=token) | |
slack_args = {} | |
if emoji_name is not None: | |
message = ":{}: ".format(emoji_name) + message | |
slack_args["text"] = message | |
slack_args["title"] = title | |
if action == "send_message": | |
api_to_use = "chat.postMessage" | |
elif action == "send_file": | |
api_to_use = "files.upload" | |
slack_args["channels"] = ",".join(users) | |
slack_args["initial_comment"] = message | |
if title == "": | |
slack_args["title"] = os.path.basename(file_to_send) | |
slack_args["filename"] = os.path.basename(file_to_send) | |
slack_args["file"] = open(file_to_send, mode="rb") | |
else: | |
assert False | |
if action == "send_message": | |
for user in users: | |
status = slack_client.chat_postMessage( | |
channel=user, **slack_args) | |
elif action == "send_file": | |
status = slack_client.files_upload(**slack_args) | |
return 0 | |
def main(): | |
parser = argparse.ArgumentParser(description="Send to Slack") | |
parser.add_argument( | |
"-a", | |
"--action", | |
dest="action", | |
choices=["send_message", "send_file"], | |
type=str, | |
help="Action", | |
default="send_message" | |
) | |
parser.add_argument( | |
"-u", | |
"--users", | |
dest="users", | |
nargs="+", | |
help="Recpients separated by space. eg: -u @csghone csghone U3ZTSC4LA #testingbots C9N67D9G8", | |
type=str, | |
required=True | |
) | |
parser.add_argument( | |
"-t", | |
"--title", | |
dest="title", | |
help="Message title to use", | |
type=str, | |
default="" | |
) | |
parser.add_argument( | |
"-m", | |
"--message", | |
dest="message", | |
help="Message to send", | |
type=str, | |
default="" | |
) | |
parser.add_argument( | |
"-f", | |
"--file_to_send", | |
dest="file_to_send", | |
help="File to send", | |
type=str, | |
default=None | |
) | |
parser.add_argument( | |
"-e", | |
"--emoji_name", | |
dest="emoji_name", | |
help="Emoji to attach to message/file", | |
type=str, | |
default=None | |
) | |
myargs = parser.parse_args() | |
if myargs.action == "send_message" and myargs.message == "": | |
logger.error("-m not specified") | |
return -1 | |
if myargs.action == "send_file" and myargs.file_to_send == None: | |
logger.error("-f not specified") | |
return -1 | |
if myargs.action == "send_file" and not os.path.exists(myargs.file_to_send): | |
logger.error("Cannot find: %s", myargs.file_to_send) | |
return -1 | |
return process(**vars(myargs)) | |
if __name__ == '__main__': | |
setup_logging(level=logging.INFO) | |
try: | |
sys.exit(main()) # Ensure return value is passed to shell | |
except Exception as error: # pylint: disable=W0702, W0703 | |
exc_mesg = traceback.format_exc() | |
logger.error("\n%s", exc_mesg) | |
logger.error("Error: %s", error) | |
sys.exit(-1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment