feat(slack): new Slack notification/ChatOps integration
Slack Web API, 8 commands: send message (text/Block Kit), list/create channel, invite to channel, set topic, get user, add reaction. Bot-token auth, stdlib-only. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
import json, os, sys, urllib.parse, urllib.request, urllib.error
|
||||
|
||||
BASE = "https://slack.com/api"
|
||||
|
||||
|
||||
def _cfg():
|
||||
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
|
||||
|
||||
def _inputs():
|
||||
return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
|
||||
|
||||
|
||||
def call(method_name, cfg, body=None, params=None, http="POST"):
|
||||
url = BASE + "/" + method_name
|
||||
if params:
|
||||
url += "?" + urllib.parse.urlencode({k: v for k, v in params.items() if v not in (None, "")})
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
headers = {"Authorization": "Bearer " + str(cfg.get("bot_token", "")), "Accept": "application/json"}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json; charset=utf-8"
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=http)
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
resp = json.loads(r.read() or "{}")
|
||||
if not resp.get("ok"):
|
||||
raise Exception("Slack error: " + str(resp.get("error") or resp))
|
||||
return resp
|
||||
|
||||
|
||||
def _run(fn):
|
||||
try:
|
||||
print(json.dumps(fn(_cfg(), _inputs())))
|
||||
except urllib.error.HTTPError as e:
|
||||
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def main(cfg, inputs):
|
||||
channel = str(inputs.get("channel") or "").strip()
|
||||
if not channel:
|
||||
raise Exception("channel is required")
|
||||
|
||||
text = str(inputs.get("text") or "").strip()
|
||||
blocks_raw = str(inputs.get("blocks") or "").strip()
|
||||
thread_ts = str(inputs.get("thread_ts") or "").strip()
|
||||
|
||||
if not text and not blocks_raw:
|
||||
raise Exception("text or blocks is required")
|
||||
|
||||
body = {"channel": channel}
|
||||
if text:
|
||||
body["text"] = text
|
||||
if blocks_raw:
|
||||
try:
|
||||
body["blocks"] = json.loads(blocks_raw)
|
||||
except Exception:
|
||||
raise Exception("blocks must be a valid JSON array")
|
||||
if thread_ts:
|
||||
body["thread_ts"] = thread_ts
|
||||
|
||||
return call("chat.postMessage", cfg, body=body)
|
||||
|
||||
|
||||
_run(main)
|
||||
Reference in New Issue
Block a user