Skip to content

Instantly share code, notes, and snippets.

@tmorioka
Last active January 18, 2018 07:24
Show Gist options
  • Save tmorioka/8d16b17b0bf793f71c12fe3ea3b1bd00 to your computer and use it in GitHub Desktop.
Save tmorioka/8d16b17b0bf793f71c12fe3ea3b1bd00 to your computer and use it in GitHub Desktop.
コマンドが終了したらslackに通知するpythonスクリプト
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from configparser import ConfigParser
import os
import sys
import subprocess
import traceback
import urllib.parse
import urllib.request
""" nsorv = Notify Slack Of Return Value
Requirements:
The configuration file named as `~/.slackrc` should exist.
This configuration file contains the following keys with section `slack`:
- access_token
- channel
"""
argv = sys.argv
if len(argv) <= 1:
print("usage: nsorv cmd")
sys.exit(1)
cmd = argv[1:]
url = "https://slack.com/api/chat.postMessage"
ini = ConfigParser()
ini.read(os.path.join(os.environ["HOME"], ".slackrc"))
access_token = ini["slack"]["access_token"]
channel = ini["slack"]["channel"]
try:
rval = subprocess.call(cmd, shell=False)
message = """the command `{}` finished with exit code {}""".format(
" ".join(cmd), rval)
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"token": access_token,
"text": message,
"channel": channel,
"as_user": False
}
request = urllib.request.Request(url)
request.add_header("Content-Type", "application/x-www-form-urlencoded")
params = urllib.parse.urlencode(data).encode("utf-8")
with urllib.request.urlopen(request, params) as response:
print(response.read().decode("utf-8"))
sys.exit(0)
except Exception:
print(traceback.format_exc())
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment