/
slack_differ.py
executable file
·70 lines (69 loc) · 2.21 KB
/
slack_differ.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/python
import sh
from os import listdir, mkdir
from os.path import join, realpath, dirname, isdir, isfile
import json
import sys
print "running slack_differ"
dname = dirname(realpath(__file__))
print "dirname : " + dname
script_dir = join(dname,'scripts')
print "script_dir : " + script_dir
if not isdir(script_dir):
print "no script dir found"
scripts = []
else:
scripts = [f for f in listdir(script_dir) if f.endswith(".json")]
for script in scripts:
try:
script_metadata = json.load(open(join(script_dir, script)))
old_file = join(dname, script + ".old")
new_file = join(dname, script + ".new")
new_out = open(new_file,'w')
command = sh.Command(join(script_dir,script_metadata["script"]))
print("running " + join(script_dir,script_metadata["script"]))
command(_out=new_out)
if not isfile(old_file):
sh.cp(new_file,old_file)
diff = sh.diff(old_file,new_file,_ok_code=[0,1])
if len(diff) > 0:
message = str(open(new_file).read())
payload = {
"channel":script_metadata["channel"],
"username":script_metadata["user"],
"text": script_metadata["title"],
"icon_emoji":script_metadata["emoji"],
"attachments" : [
{
"color":"good",
"fields":[
{
"title":"new value",
"value":message,
"short":False
}
]
}
]
}
payload = "payload=" + json.dumps(payload)
sh.mv(new_file,old_file)
sh.curl(["curl", "-X", "POST" ,"--data-urlencode" ,payload,script_metadata["slack_url"]])
except Exception as e:
print "failed on " + script +" :" + str(e)
if len(sys.argv) > 1 and sys.argv[1] == "example":
print("initialising example")
if not isdir(script_dir):
mkdir(script_dir)
script = open(join(script_dir,"example.sh"),'w')
script.write("#!/bin/bash\necho 'hi'")
metafile = open(join(script_dir,"example.json"),'w')
meta = {
"channel":"#example",
"user":"examplebot",
"title":"script title",
"emoji":":metal:",
"slack_url":"https://hook.slack.com/XXX/YYY",
"script":"example.sh"
}
metafile.write(json.dumps(meta))