elleryq
8/8/2018 - 3:04 AM

可以送訊息,也可以送指定指令的執行結果給 slack 的小工具。

可以送訊息,也可以送指定指令的執行結果給 slack 的小工具。

#!/usr/bin/python3
# Tested in Ubuntu 14.04
# Requirement packages:
# - sudo apt install python3-requests
import sys
import argparse
import json
import requests
import subprocess


def main():
    parser = argparse.ArgumentParser(description='slack-run')
    parser.add_argument(
        "--url",
        required=True,
        help="specify slack incoming webhook url")
    parser.add_argument(
        "--username",
        help="username, default is {}".format(sys.argv[0]),
        dest='username')
    parser.add_argument(
        "--msg",
        help="message, default is 'foo'",
        dest='msg',
        default='foo')
    parser.add_argument(
        "--cmd",
        help="The command you want to run.",
        dest='cmd')
    args = parser.parse_args()

    if args.cmd:
      cmd = args.cmd
      cmd_output = subprocess.check_output(
        cmd,
        stderr=subprocess.STDOUT,
        shell=True
      )
      cmd_output = cmd_output.decode('utf-8')
    elif args.msg:
      cmd_output = args.msg

    payload = {
        # "channel": "#backup-status",
        "username": args.username,
        "text": cmd_output
    }

    r = requests.post(
        args.url,
        data=json.dumps(payload))
    print(r.text)


if __name__ == "__main__":
    main()