Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions dapier_cli/cli/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,25 @@ def register(sub):
export.add_argument("--limit", type=int, default=200)
export.add_argument("--cursor", default=None)

post = sub_p.add_parser(
"post",
help="Post a message to a Slack channel or thread (default connection: slack = Au-Tomator bot)",
)
post.add_argument("--channel", required=True,
help="Channel name (e.g. announcements or #announcements) or id (e.g. C01BQC114P2)")
text_group = post.add_mutually_exclusive_group(required=True)
text_group.add_argument("--text-file",
help="Path to UTF-8 text file (or '-' for stdin)")
text_group.add_argument("--text", help="Inline message text")
post.add_argument("--thread-ts", default=None,
help="Thread timestamp to reply in")
post.add_argument("--connection", default="slack",
help="Connection id (default slack = Au-Tomator bot)")
post.add_argument("--no-unfurl", action="store_true",
help="Disable link and media previews")
post.add_argument("--dry-run", action="store_true",
help="Resolve channel and verify bot/channel access without posting")


def run(args, api_url, debug, child=None):
if args.command == "find-user":
Expand Down Expand Up @@ -86,4 +105,17 @@ def run(args, api_url, debug, child=None):
return commands.slack_dm_export(
api_url, args.user, connection_id=args.connection,
limit=args.limit, cursor=args.cursor, debug=debug)
if args.command == "post":
return commands.slack_post(
api_url,
channel=args.channel,
text_file=args.text_file,
text=args.text,
connection_id=args.connection,
thread_ts=args.thread_ts,
unfurl_links=not args.no_unfurl,
unfurl_media=not args.no_unfurl,
dry_run=args.dry_run,
debug=debug,
)
return 2
37 changes: 36 additions & 1 deletion dapier_cli/commands/slack.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
"""Implementation of the `dapier slack` commands."""

import sys
from pathlib import Path
from urllib.parse import urlencode

from .. import api
from .shared import print_json

__all__ = [
"slack_find_user", "slack_open_dm", "slack_history", "slack_dm_export",
"slack_replies", "slack_channels", "slack_search",
"slack_replies", "slack_channels", "slack_search", "slack_post",
]

DEFAULT_CONNECTION_ID = "slack-alexey"
DEFAULT_POST_CONNECTION_ID = "slack"


def slack_find_user(api_url, query, connection_id=DEFAULT_CONNECTION_ID, limit=50, debug=False):
Expand Down Expand Up @@ -99,3 +102,35 @@ def slack_search(api_url, query, connection_id=DEFAULT_CONNECTION_ID, count=20,
return _get(api_url, "/api/agent/slack/search", {
"q": query, "connection_id": connection_id, "count": int(count),
"page": int(page)}, debug)


def slack_post(api_url, channel, text_file=None, text=None,
connection_id=DEFAULT_POST_CONNECTION_ID, thread_ts=None,
unfurl_links=True, unfurl_media=True, dry_run=False, debug=False):
if text_file is not None:
if text_file == "-":
body_text = sys.stdin.read()
else:
try:
body_text = Path(text_file).read_text(encoding="utf-8")
except OSError as exc:
print(f"Error: cannot read text file {text_file!r}: {exc}", file=sys.stderr)
return 1
else:
body_text = str(text or "")
if not body_text.strip():
print("Error: message text is empty", file=sys.stderr)
return 1
payload = {
"channel": channel,
"text": body_text,
"connection_id": connection_id,
"unfurl_links": bool(unfurl_links),
"unfurl_media": bool(unfurl_media),
"dry_run": bool(dry_run),
}
if thread_ts:
payload["thread_ts"] = thread_ts
data = api.call(api_url, "POST", "/api/agent/slack/post", body=payload, debug=debug)
print_json(data)
return 0
31 changes: 31 additions & 0 deletions src/dapier/api/agent/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,35 @@ def _simple(event, action, fn, build):
return _json_response(200, payload)


def post_api(event):
subject, error = require_operator(event, "slack.post")
if error:
return error
try:
body = json.loads(event.get("body") or "{}")
except (ValueError, TypeError):
return _json_response(400, {"error": "Invalid JSON body"})
if not isinstance(body, dict):
return _json_response(400, {"error": "Invalid JSON body"})
connection_id = str(
body.get("connection_id") or slack_ops.DEFAULT_POST_CONNECTION_ID
).strip().lower() or slack_ops.DEFAULT_POST_CONNECTION_ID
try:
payload = slack_ops.post_message(
body.get("channel") or "",
body.get("text") or "",
connection_id=connection_id,
thread_ts=body.get("thread_ts"),
unfurl_links=body.get("unfurl_links", True),
unfurl_media=body.get("unfurl_media", True),
dry_run=bool(body.get("dry_run", False)),
)
except (slack_ops.SlackOpsError, ValueError) as exc:
return _error(exc)
audit.emit(payload["connection"], "slack.post", subject, outcome="ok")
return _json_response(200, payload)


def route_slack(event, method, path):
"""Return a response for Slack agent routes, or None if unmatched."""
if path == "/api/agent/slack/users" and method == "GET":
Expand All @@ -129,6 +158,8 @@ def route_slack(event, method, path):
return history_api(event)
if path == "/api/agent/slack/dm-export" and method == "GET":
return dm_export_api(event)
if path == "/api/agent/slack/post" and method == "POST":
return post_api(event)
if path == "/api/agent/slack/replies" and method == "GET":
return _simple(event, "slack.replies", slack_ops.replies, lambda q, c: {
"channel": q.get("channel") or "", "thread_ts": q.get("thread_ts") or "",
Expand Down
78 changes: 77 additions & 1 deletion src/dapier/api/agent/slack_ops.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
"""Slack DM/export helpers for the agent API (connection token stays server-side)."""
"""Slack DM/export/post helpers for the agent API (connection token stays server-side)."""

import re

from ...connections import discovery as slack_discovery
from ...connections import tokens
from ...connections.providers import oauth_providers
from .. import discovery as discovery_api

DEFAULT_CONNECTION_ID = "slack-alexey"
DEFAULT_POST_CONNECTION_ID = "slack"
_CHANNEL_ID_RE = re.compile(r"^[CGD][A-Z0-9]+$")


class SlackOpsError(Exception):
Expand Down Expand Up @@ -243,3 +247,75 @@ def dm_export(user, *, connection_id=DEFAULT_CONNECTION_ID, limit=200, cursor=No
hist = history(
opened["channel"], connection_id=connection_id, limit=limit, cursor=cursor)
return {**opened, **hist, "user_id": opened["user_id"]}


def _resolve_channel_id(token, channel):
"""Return a Slack channel ID, resolving #name via conversations.list when needed."""
raw = str(channel or "").strip()
if not raw:
raise SlackOpsError("channel is required")
if _CHANNEL_ID_RE.fullmatch(raw):
return raw
target = raw.lstrip("#").strip().lower()
if not target:
raise SlackOpsError("channel is required")
cursor = None
for _ in range(5):
payload = {"limit": 200, "exclude_archived": True, "types": "public_channel,private_channel"}
if cursor:
payload["cursor"] = cursor
data = _call(token, "conversations.list", payload)
for item in data.get("channels") or []:
if isinstance(item, dict) and str(item.get("name") or "").lower() == target:
cid = item.get("id")
if cid:
return cid
cursor = (data.get("response_metadata") or {}).get("next_cursor") or None
if not cursor:
break
raise SlackOpsError(f"Slack channel {channel!r} not found", status=404)


def post_message(channel, text, *, connection_id=DEFAULT_POST_CONNECTION_ID, thread_ts=None,
unfurl_links=True, unfurl_media=True, dry_run=False):
"""Post a message (or dry-run check) to a Slack channel/thread via chat.postMessage."""
connection_id, _connection, token = _connection_and_token(connection_id)
text = str(text or "")
if not text.strip():
raise SlackOpsError("text is required")
channel_id = _resolve_channel_id(token, channel)
thread_ts = str(thread_ts).strip() if thread_ts else None
if dry_run:
info = _call(token, "conversations.info", {"channel": channel_id})
ch = info.get("channel") or {}
auth = _call(token, "auth.test", {})
return {
"ok": True,
"dry_run": True,
"connection": connection_id,
"channel": channel_id,
"channel_name": ch.get("name"),
"is_member": ch.get("is_member"),
"bot_id": auth.get("bot_id"),
"user_id": auth.get("user_id"),
"thread_ts": thread_ts,
"unfurl_links": bool(unfurl_links),
"unfurl_media": bool(unfurl_media),
"text_length": len(text),
}
payload = {
"channel": channel_id,
"text": text,
"unfurl_links": bool(unfurl_links),
"unfurl_media": bool(unfurl_media),
}
if thread_ts:
payload["thread_ts"] = thread_ts
data = _call(token, "chat.postMessage", payload)
return {
"ok": True,
"connection": connection_id,
"channel": data.get("channel") or channel_id,
"ts": data.get("ts"),
"thread_ts": thread_ts,
}
139 changes: 139 additions & 0 deletions tests/test_slack_ops_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,145 @@ def test_cli_help_registers():
assert args.command == "find-user"


def test_post_message_resolves_channel_name_and_posts(monkeypatch):
monkeypatch.setattr(slack_ops.discovery_api, "_load",
lambda cid, table: (_connection(cid), None))
monkeypatch.setattr(slack_ops.tokens, "get_access_token",
FakeTokens("xoxb-" + "b" * 40).get_access_token)
calls = []

def fake_call(method, token, payload, transport=None):
calls.append((method, payload))
if method == "conversations.list":
return {
"ok": True,
"channels": [{"id": "C01BQC114P2", "name": "announcements"}],
"response_metadata": {},
}
if method == "chat.postMessage":
return {"ok": True, "channel": "C01BQC114P2", "ts": "1700000000.000100"}
raise AssertionError(method)

monkeypatch.setattr(slack_ops.slack_discovery, "_slack_call", fake_call)
res = slack_ops.post_message(
"#announcements", "Hello world", thread_ts="1699999999.000100",
unfurl_links=False, unfurl_media=False,
)
assert res["ok"] is True
assert res["channel"] == "C01BQC114P2"
assert res["ts"] == "1700000000.000100"
assert calls[1][0] == "chat.postMessage"
assert calls[1][1]["thread_ts"] == "1699999999.000100"
assert calls[1][1]["unfurl_links"] is False


def test_post_message_dry_run(monkeypatch):
monkeypatch.setattr(slack_ops.discovery_api, "_load",
lambda cid, table: (_connection(cid), None))
monkeypatch.setattr(slack_ops.tokens, "get_access_token",
FakeTokens("xoxb-" + "b" * 40).get_access_token)

def fake_call(method, token, payload, transport=None):
if method == "conversations.info":
return {"ok": True, "channel": {"id": "C01BQC114P2", "name": "announcements", "is_member": True}}
if method == "auth.test":
return {"ok": True, "bot_id": "B123", "user_id": "U123"}
raise AssertionError(method)

monkeypatch.setattr(slack_ops.slack_discovery, "_slack_call", fake_call)
res = slack_ops.post_message("C01BQC114P2", "Hello", dry_run=True)
assert res["dry_run"] is True
assert res["is_member"] is True
assert res["bot_id"] == "B123"


def test_post_message_loud_errors(monkeypatch):
monkeypatch.setattr(slack_ops.discovery_api, "_load",
lambda cid, table: (_connection(cid), None))
monkeypatch.setattr(slack_ops.tokens, "get_access_token",
FakeTokens("xoxb-" + "b" * 40).get_access_token)

def fake_not_in_channel(method, token, payload, transport=None):
raise slack_ops.slack_discovery.DiscoveryError(
"Slack rejected chat.postMessage: not_in_channel", status=502)

monkeypatch.setattr(slack_ops.slack_discovery, "_slack_call", fake_not_in_channel)
with pytest.raises(slack_ops.SlackOpsError, match="not_in_channel"):
slack_ops.post_message("C01BQC114P2", "Hello")


def test_route_slack_post(monkeypatch):
calls = {}

def require_operator(event, action):
calls["action"] = action
return "subject-1", None

monkeypatch.setattr(slack_api, "require_operator", require_operator)
monkeypatch.setattr(slack_api, "audit", type("A", (), {
"emit": staticmethod(lambda *a, **k: None)
})())
monkeypatch.setattr(
slack_api.slack_ops, "post_message",
lambda channel, text, **kw: {
"ok": True, "connection": kw["connection_id"],
"channel": channel, "ts": "1.2", "thread_ts": kw.get("thread_ts"),
},
)
resp = slack_api.route_slack(
{"body": json.dumps({"channel": "C01BQC114P2", "text": "Hi"})},
"POST", "/api/agent/slack/post",
)
assert resp["statusCode"] == 200
body = json.loads(resp["body"])
assert body["connection"] == "slack"
assert calls["action"] == "slack.post"


def test_cli_post_parses_and_reads_file(tmp_path, monkeypatch):
from dapier_cli.cli import build_parser
from dapier_cli import commands

msg_file = tmp_path / "msg.txt"
msg_file.write_text("Line 1\nLine 2\n", encoding="utf-8")

parser = build_parser()
args = parser.parse_args([
"slack", "post", "--channel", "announcements",
"--text-file", str(msg_file), "--no-unfurl", "--dry-run",
])
assert args.group == "slack"
assert args.command == "post"
assert args.connection == "slack"

captured = {}

def fake_api_call(api_url, method, path, body=None, debug=False):
captured["method"] = method
captured["path"] = path
captured["body"] = body
return {"ok": True, "dry_run": True, "channel": "C01BQC114P2"}

monkeypatch.setattr(commands.slack.api, "call", fake_api_call)
rc = commands.slack_post(
"https://example.com", args.channel, text_file=args.text_file,
connection_id=args.connection, unfurl_links=not args.no_unfurl,
unfurl_media=not args.no_unfurl, dry_run=args.dry_run,
)
assert rc == 0
assert captured["path"] == "/api/agent/slack/post"
assert captured["body"]["text"] == "Line 1\nLine 2\n"
assert captured["body"]["unfurl_links"] is False
assert captured["body"]["dry_run"] is True

# Missing file returns non-zero loudly
rc_missing = commands.slack_post(
"https://example.com", "announcements",
text_file=str(tmp_path / "missing.txt"),
)
assert rc_missing != 0


def _fake_slack(monkeypatch, handler):
monkeypatch.setattr(slack_ops.discovery_api, "_load",
lambda cid, table: (_connection(cid), None))
Expand Down
Loading