stapel-slack 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stapel_slack-0.1.0/CONFIG.MD +8 -0
- stapel_slack-0.1.0/LICENSE +21 -0
- stapel_slack-0.1.0/MODULE.md +10 -0
- stapel_slack-0.1.0/PKG-INFO +58 -0
- stapel_slack-0.1.0/README.md +23 -0
- stapel_slack-0.1.0/__init__.py +25 -0
- stapel_slack-0.1.0/apps.py +15 -0
- stapel_slack-0.1.0/conf.py +12 -0
- stapel_slack-0.1.0/conftest.py +58 -0
- stapel_slack-0.1.0/llms.txt +9 -0
- stapel_slack-0.1.0/py.typed +0 -0
- stapel_slack-0.1.0/pyproject.toml +81 -0
- stapel_slack-0.1.0/setup.cfg +4 -0
- stapel_slack-0.1.0/stapel_slack.egg-info/PKG-INFO +58 -0
- stapel_slack-0.1.0/stapel_slack.egg-info/SOURCES.txt +39 -0
- stapel_slack-0.1.0/stapel_slack.egg-info/dependency_links.txt +1 -0
- stapel_slack-0.1.0/stapel_slack.egg-info/requires.txt +10 -0
- stapel_slack-0.1.0/stapel_slack.egg-info/top_level.txt +1 -0
- stapel_slack-0.1.0/stpl_slack_markdown.py +170 -0
- stapel_slack-0.1.0/stpl_slack_provider.py +43 -0
- stapel_slack-0.1.0/stpl_slack_webhook.py +98 -0
- stapel_slack-0.1.0/tests/test_module_names.py +23 -0
- stapel_slack-0.1.0/tests/test_public_api.py +32 -0
- stapel_slack-0.1.0/tests/test_stpl_slack.py +92 -0
- stapel_slack-0.1.0/urls.py +4 -0
- stapel_slack-0.1.0/urls_v1.py +8 -0
- stapel_slack-0.1.0/views.py +24 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stapel contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# MODULE.md — stapel-slack
|
|
2
|
+
|
|
3
|
+
## Provider `slack`
|
|
4
|
+
Fields: `webhook_url` (secret), `channel_label`. A check answers "unknown" (`ok = null`): a webhook cannot be tried without posting.
|
|
5
|
+
|
|
6
|
+
## HTTP
|
|
7
|
+
`POST /slack/api/v1/connections/<id>/test-message` — managers only.
|
|
8
|
+
|
|
9
|
+
## Not here
|
|
10
|
+
Bot tokens, channel lists, threads, GovSlack.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: stapel-slack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Slack for Stapel: incoming-webhook posting from Markdown, connection provider
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/usestapel/stapel-slack
|
|
7
|
+
Project-URL: Repository, https://github.com/usestapel/stapel-slack
|
|
8
|
+
Project-URL: Documentation, https://github.com/usestapel/stapel-slack#readme
|
|
9
|
+
Project-URL: Changelog, https://github.com/usestapel/stapel-slack/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Issues, https://github.com/usestapel/stapel-slack/issues
|
|
11
|
+
Keywords: django,stapel,slack
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: Django
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: stapel-core<1.0,>=0.99.5
|
|
27
|
+
Requires-Dist: stapel-integrations-core<1.0,>=0.1.0
|
|
28
|
+
Requires-Dist: drf-spectacular>=0.27
|
|
29
|
+
Provides-Extra: all
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest; extra == "test"
|
|
32
|
+
Requires-Dist: pytest-django; extra == "test"
|
|
33
|
+
Requires-Dist: pytest-cov; extra == "test"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# stapel-slack
|
|
37
|
+
|
|
38
|
+
Slack for Stapel: post Markdown to a channel through an incoming webhook, with a `slack` connection provider.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install stapel-slack
|
|
44
|
+
```
|
|
45
|
+
Add `stapel_integrations_core` and `stapel_slack` to `INSTALLED_APPS`, mount `path("slack/", include("stapel_slack.urls"))`.
|
|
46
|
+
|
|
47
|
+
## Use
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from stapel_slack import SlackWebhookClient, StapelSlackIntegration
|
|
51
|
+
|
|
52
|
+
slack = StapelSlackIntegration(SlackWebhookClient(webhook_url))
|
|
53
|
+
slack.post("## Decisions\n- ship STPL", title="Weekly sync", link="https://example.com/m/1")
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
See `MODULE.md` for the contract, `CONFIG.MD` for settings, `llms.txt` for agents.
|
|
57
|
+
|
|
58
|
+
MIT licensed.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# stapel-slack
|
|
2
|
+
|
|
3
|
+
Slack for Stapel: post Markdown to a channel through an incoming webhook, with a `slack` connection provider.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install stapel-slack
|
|
9
|
+
```
|
|
10
|
+
Add `stapel_integrations_core` and `stapel_slack` to `INSTALLED_APPS`, mount `path("slack/", include("stapel_slack.urls"))`.
|
|
11
|
+
|
|
12
|
+
## Use
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from stapel_slack import SlackWebhookClient, StapelSlackIntegration
|
|
16
|
+
|
|
17
|
+
slack = StapelSlackIntegration(SlackWebhookClient(webhook_url))
|
|
18
|
+
slack.post("## Decisions\n- ship STPL", title="Weekly sync", link="https://example.com/m/1")
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
See `MODULE.md` for the contract, `CONFIG.MD` for settings, `llms.txt` for agents.
|
|
22
|
+
|
|
23
|
+
MIT licensed.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""stapel-slack — post to Slack from the Stapel framework (lazy exports)."""
|
|
2
|
+
|
|
3
|
+
_LAZY_EXPORTS = {
|
|
4
|
+
"StapelSlackIntegration": ".stpl_slack_webhook",
|
|
5
|
+
"SlackWebhookClient": ".stpl_slack_webhook",
|
|
6
|
+
"SlackWebhookGone": ".stpl_slack_webhook",
|
|
7
|
+
"build_message": ".stpl_slack_markdown",
|
|
8
|
+
"markdown_to_mrkdwn": ".stpl_slack_markdown",
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
__all__ = sorted(_LAZY_EXPORTS)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def __getattr__(name):
|
|
15
|
+
if name in _LAZY_EXPORTS:
|
|
16
|
+
from importlib import import_module
|
|
17
|
+
|
|
18
|
+
value = getattr(import_module(_LAZY_EXPORTS[name], __name__), name)
|
|
19
|
+
globals()[name] = value
|
|
20
|
+
return value
|
|
21
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def __dir__():
|
|
25
|
+
return sorted(set(globals()) | set(__all__))
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from django.apps import AppConfig
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class SlackConfig(AppConfig):
|
|
5
|
+
name = "stapel_slack"
|
|
6
|
+
label = "slack"
|
|
7
|
+
verbose_name = "Slack"
|
|
8
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
9
|
+
|
|
10
|
+
def ready(self):
|
|
11
|
+
from stapel_integrations_core.stpl_integrations_providers import register_provider
|
|
12
|
+
|
|
13
|
+
from .stpl_slack_provider import SlackProvider
|
|
14
|
+
|
|
15
|
+
register_provider(SlackProvider())
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Settings namespace ``STAPEL_SLACK`` (keys are prefixed: see the core)."""
|
|
2
|
+
from stapel_core.conf import AppSettings
|
|
3
|
+
|
|
4
|
+
DEFAULTS = {
|
|
5
|
+
# Our own caps, well under Slack's limits.
|
|
6
|
+
"SLACK_MAX_BLOCKS": 40,
|
|
7
|
+
"SLACK_MAX_CHARS": 12000,
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
slack_settings = AppSettings("STAPEL_SLACK", defaults=DEFAULTS)
|
|
11
|
+
|
|
12
|
+
__all__ = ["DEFAULTS", "slack_settings"]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
def pytest_configure(config):
|
|
2
|
+
from django.conf import settings
|
|
3
|
+
if not settings.configured:
|
|
4
|
+
settings.configure(
|
|
5
|
+
SECRET_KEY="test-secret-key-not-for-production",
|
|
6
|
+
INSTALLED_APPS=[
|
|
7
|
+
"django.contrib.contenttypes",
|
|
8
|
+
"django.contrib.auth",
|
|
9
|
+
"django.contrib.sessions",
|
|
10
|
+
"django.contrib.admin",
|
|
11
|
+
"django.contrib.messages",
|
|
12
|
+
"stapel_core.django.users",
|
|
13
|
+
"rest_framework",
|
|
14
|
+
"stapel_integrations_core",
|
|
15
|
+
"stapel_slack",
|
|
16
|
+
],
|
|
17
|
+
AUTH_USER_MODEL="users.User",
|
|
18
|
+
DATABASES={
|
|
19
|
+
"default": {
|
|
20
|
+
"ENGINE": "django.db.backends.sqlite3",
|
|
21
|
+
"NAME": ":memory:",
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
|
|
25
|
+
USE_TZ=True,
|
|
26
|
+
ROOT_URLCONF="stapel_slack.tests.urls",
|
|
27
|
+
CACHES={
|
|
28
|
+
"default": {
|
|
29
|
+
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
# Synchronous in-process comm with schema validation ON, so the
|
|
33
|
+
# committed contracts in schemas/ are enforced by the tests.
|
|
34
|
+
STAPEL_BUS_BACKEND="stapel_core.bus.backends.memory.MemoryBus",
|
|
35
|
+
STAPEL_COMM={
|
|
36
|
+
"OUTBOX_ENABLED": False,
|
|
37
|
+
"ACTION_TRANSPORT": "inprocess",
|
|
38
|
+
"VALIDATE_SCHEMAS": True,
|
|
39
|
+
},
|
|
40
|
+
MIGRATION_MODULES={
|
|
41
|
+
"users": None,
|
|
42
|
+
"integrations": None, "slack": None,
|
|
43
|
+
},
|
|
44
|
+
)
|
|
45
|
+
import django
|
|
46
|
+
django.setup()
|
|
47
|
+
|
|
48
|
+
from stapel_core.comm.schemas import autoload_schemas
|
|
49
|
+
autoload_schemas()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
import pytest # noqa: E402
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@pytest.fixture
|
|
56
|
+
def api_client():
|
|
57
|
+
from rest_framework.test import APIClient
|
|
58
|
+
return APIClient()
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# stapel-slack
|
|
2
|
+
|
|
3
|
+
> Slack for Stapel: post Markdown to a channel through an incoming webhook, with a `slack` connection provider.
|
|
4
|
+
|
|
5
|
+
## Rules
|
|
6
|
+
- One webhook posts to one channel. Slack returns no message id and has no idempotency key: never retry after `UnknownOutcome`.
|
|
7
|
+
- `SlackWebhookGone`: ask the owner for a new webhook.
|
|
8
|
+
- Mentions and disguised links in the text are neutralised; do not build `mrkdwn` from raw text yourself.
|
|
9
|
+
- Messages over 40 blocks or 12000 characters are cut and say so.
|
|
File without changes
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "stapel-slack"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Slack for Stapel: incoming-webhook posting from Markdown, connection provider"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
keywords = ["django", "stapel", "slack"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 4 - Beta",
|
|
15
|
+
"Framework :: Django",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Programming Language :: Python :: 3.14",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"stapel-core>=0.99.5,<1.0",
|
|
28
|
+
"stapel-integrations-core>=0.1.0,<1.0",
|
|
29
|
+
"drf-spectacular>=0.27",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/usestapel/stapel-slack"
|
|
34
|
+
Repository = "https://github.com/usestapel/stapel-slack"
|
|
35
|
+
Documentation = "https://github.com/usestapel/stapel-slack#readme"
|
|
36
|
+
Changelog = "https://github.com/usestapel/stapel-slack/blob/main/CHANGELOG.md"
|
|
37
|
+
Issues = "https://github.com/usestapel/stapel-slack/issues"
|
|
38
|
+
|
|
39
|
+
[project.optional-dependencies]
|
|
40
|
+
all = []
|
|
41
|
+
# ONE declaration of what the TEST SUITE needs, as opposed to what the package
|
|
42
|
+
# needs. CI installs exactly this (`pip install -e ".[test]"`), so a sibling a
|
|
43
|
+
# test imports and this list does not name is a red release on a clean runner —
|
|
44
|
+
# the class that killed three of them in one night on 2026-08-24. The gate over
|
|
45
|
+
# this list is `stapel-sibling-lint` (SIB001-006), wired into CI below; the
|
|
46
|
+
# skip-vs-fail half of the contract is `tests/siblings.py`.
|
|
47
|
+
test = [
|
|
48
|
+
"pytest",
|
|
49
|
+
"pytest-django",
|
|
50
|
+
"pytest-cov",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
[tool.setuptools]
|
|
54
|
+
package-dir = {"stapel_slack" = "."}
|
|
55
|
+
packages = ["stapel_slack"]
|
|
56
|
+
|
|
57
|
+
[tool.setuptools.package-data]
|
|
58
|
+
# The contract documents ship IN THE WHEEL: that is what makes
|
|
59
|
+
# `stapel-catalog --from-installed` possible, i.e. what turns catalog
|
|
60
|
+
# freshness from somebody's discipline into a property of the lockfile.
|
|
61
|
+
# A module that keeps them repo-only publishes code an agent cannot read.
|
|
62
|
+
stapel_slack = ["py.typed", "llms.txt", "MODULE.md", "docs/capabilities.json", "docs/flows.json", "docs/errors.json", "CONFIG.MD"]
|
|
63
|
+
|
|
64
|
+
[tool.ruff]
|
|
65
|
+
target-version = "py311"
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint]
|
|
68
|
+
# Single source for the git hooks and CI (they pass the same flags on the CLI).
|
|
69
|
+
select = ["E", "F", "W"]
|
|
70
|
+
ignore = ["E501"]
|
|
71
|
+
|
|
72
|
+
[tool.pytest.ini_options]
|
|
73
|
+
django_find_project = false
|
|
74
|
+
addopts = "--tb=short -q --import-mode=importlib"
|
|
75
|
+
|
|
76
|
+
[tool.coverage.run]
|
|
77
|
+
omit = [
|
|
78
|
+
"*/tests/*",
|
|
79
|
+
"*/conftest.py",
|
|
80
|
+
"*/migrations/*",
|
|
81
|
+
]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: stapel-slack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Slack for Stapel: incoming-webhook posting from Markdown, connection provider
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/usestapel/stapel-slack
|
|
7
|
+
Project-URL: Repository, https://github.com/usestapel/stapel-slack
|
|
8
|
+
Project-URL: Documentation, https://github.com/usestapel/stapel-slack#readme
|
|
9
|
+
Project-URL: Changelog, https://github.com/usestapel/stapel-slack/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Issues, https://github.com/usestapel/stapel-slack/issues
|
|
11
|
+
Keywords: django,stapel,slack
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: Django
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: stapel-core<1.0,>=0.99.5
|
|
27
|
+
Requires-Dist: stapel-integrations-core<1.0,>=0.1.0
|
|
28
|
+
Requires-Dist: drf-spectacular>=0.27
|
|
29
|
+
Provides-Extra: all
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest; extra == "test"
|
|
32
|
+
Requires-Dist: pytest-django; extra == "test"
|
|
33
|
+
Requires-Dist: pytest-cov; extra == "test"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# stapel-slack
|
|
37
|
+
|
|
38
|
+
Slack for Stapel: post Markdown to a channel through an incoming webhook, with a `slack` connection provider.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install stapel-slack
|
|
44
|
+
```
|
|
45
|
+
Add `stapel_integrations_core` and `stapel_slack` to `INSTALLED_APPS`, mount `path("slack/", include("stapel_slack.urls"))`.
|
|
46
|
+
|
|
47
|
+
## Use
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from stapel_slack import SlackWebhookClient, StapelSlackIntegration
|
|
51
|
+
|
|
52
|
+
slack = StapelSlackIntegration(SlackWebhookClient(webhook_url))
|
|
53
|
+
slack.post("## Decisions\n- ship STPL", title="Weekly sync", link="https://example.com/m/1")
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
See `MODULE.md` for the contract, `CONFIG.MD` for settings, `llms.txt` for agents.
|
|
57
|
+
|
|
58
|
+
MIT licensed.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
CONFIG.MD
|
|
2
|
+
LICENSE
|
|
3
|
+
MODULE.md
|
|
4
|
+
README.md
|
|
5
|
+
__init__.py
|
|
6
|
+
apps.py
|
|
7
|
+
conf.py
|
|
8
|
+
conftest.py
|
|
9
|
+
llms.txt
|
|
10
|
+
py.typed
|
|
11
|
+
pyproject.toml
|
|
12
|
+
stpl_slack_markdown.py
|
|
13
|
+
stpl_slack_provider.py
|
|
14
|
+
stpl_slack_webhook.py
|
|
15
|
+
urls.py
|
|
16
|
+
urls_v1.py
|
|
17
|
+
views.py
|
|
18
|
+
./CONFIG.MD
|
|
19
|
+
./MODULE.md
|
|
20
|
+
./__init__.py
|
|
21
|
+
./apps.py
|
|
22
|
+
./conf.py
|
|
23
|
+
./conftest.py
|
|
24
|
+
./llms.txt
|
|
25
|
+
./py.typed
|
|
26
|
+
./stpl_slack_markdown.py
|
|
27
|
+
./stpl_slack_provider.py
|
|
28
|
+
./stpl_slack_webhook.py
|
|
29
|
+
./urls.py
|
|
30
|
+
./urls_v1.py
|
|
31
|
+
./views.py
|
|
32
|
+
stapel_slack.egg-info/PKG-INFO
|
|
33
|
+
stapel_slack.egg-info/SOURCES.txt
|
|
34
|
+
stapel_slack.egg-info/dependency_links.txt
|
|
35
|
+
stapel_slack.egg-info/requires.txt
|
|
36
|
+
stapel_slack.egg-info/top_level.txt
|
|
37
|
+
tests/test_module_names.py
|
|
38
|
+
tests/test_public_api.py
|
|
39
|
+
tests/test_stpl_slack.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
stapel_slack
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Markdown to a Slack message (Block Kit with ``mrkdwn`` text).
|
|
2
|
+
|
|
3
|
+
Text from users, transcripts and models is hostile here: ``<!channel>`` pings
|
|
4
|
+
a whole channel and ``<url|label>`` disguises a link. So ``& < >`` are always
|
|
5
|
+
escaped, every text object is ``verbatim`` (nothing is auto-linked or
|
|
6
|
+
mentioned), and previews are off. The only links are Markdown links with a
|
|
7
|
+
web or mail address.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
from stapel_integrations_core import stpl_integrations_markdown as md
|
|
14
|
+
|
|
15
|
+
#: Slack refuses a section above 3000 characters and a header above 150.
|
|
16
|
+
SECTION_MAX = 2900
|
|
17
|
+
HEADER_MAX = 150
|
|
18
|
+
FALLBACK_MAX = 300
|
|
19
|
+
_CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")
|
|
20
|
+
#: A chunk must not end inside an entity or a link.
|
|
21
|
+
_OPEN_TOKEN = re.compile(r"(?:&[a-z]{0,4}|<[^>]*)$")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def escape_mrkdwn(text: str) -> str:
|
|
25
|
+
text = _CONTROL.sub(" ", text)
|
|
26
|
+
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _inline(nodes: list) -> str:
|
|
30
|
+
out: list = []
|
|
31
|
+
index = 0
|
|
32
|
+
while index < len(nodes):
|
|
33
|
+
node = nodes[index]
|
|
34
|
+
if node[0] == "break":
|
|
35
|
+
out.append("\n")
|
|
36
|
+
index += 1
|
|
37
|
+
continue
|
|
38
|
+
_, value, marks = node
|
|
39
|
+
link = next((m[1] for m in marks if isinstance(m, tuple)), None)
|
|
40
|
+
text = escape_mrkdwn(value)
|
|
41
|
+
for mark, wrap in (("code", "`"), ("em", "_"), ("strong", "*"), ("strike", "~")):
|
|
42
|
+
if mark in marks and text.strip():
|
|
43
|
+
text = f"{wrap}{text}{wrap}"
|
|
44
|
+
if link:
|
|
45
|
+
target = escape_mrkdwn(link).replace("|", "%7C")
|
|
46
|
+
text = f"<{target}>" if value == link else f"<{target}|{text.replace('|', '¦')}>"
|
|
47
|
+
out.append(text)
|
|
48
|
+
index += 1
|
|
49
|
+
return "".join(out)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _list(kind: str, items: list, depth: int = 0) -> list:
|
|
53
|
+
lines = []
|
|
54
|
+
for number, (inline, done, children) in enumerate(items, 1):
|
|
55
|
+
bullet = {"ordered": f"{number}.", "task": "☑" if done else "☐"}.get(kind, "•")
|
|
56
|
+
lines.append(" " * depth + f"{bullet} {_inline(inline)}")
|
|
57
|
+
for child in children:
|
|
58
|
+
lines.extend(_list(child[1], child[2], depth + 1))
|
|
59
|
+
return lines
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _plain(nodes: list) -> str:
|
|
63
|
+
return "".join("\n" if n[0] == "break" else n[1] for n in nodes)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _fenced(text: str) -> str:
|
|
67
|
+
return "```\n" + escape_mrkdwn(text).replace("```", "ʼʼʼ") + "\n```"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _block(block: tuple) -> str:
|
|
71
|
+
kind = block[0]
|
|
72
|
+
if kind == "heading":
|
|
73
|
+
return f"*{escape_mrkdwn(_plain(block[2]))}*"
|
|
74
|
+
if kind == "paragraph":
|
|
75
|
+
return _inline(block[1])
|
|
76
|
+
if kind == "list":
|
|
77
|
+
return "\n".join(_list(block[1], block[2]))
|
|
78
|
+
if kind == "code":
|
|
79
|
+
return _fenced(block[2])
|
|
80
|
+
if kind == "quote":
|
|
81
|
+
inner = "\n".join(_block(b) for b in block[1])
|
|
82
|
+
return "\n".join("> " + line for line in inner.split("\n"))
|
|
83
|
+
if kind == "rule":
|
|
84
|
+
return "———"
|
|
85
|
+
_, header, rows = block
|
|
86
|
+
return _fenced("\n".join(" | ".join(_plain(c) for c in row) for row in [header, *rows]))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def markdown_to_mrkdwn(markdown: str) -> str:
|
|
90
|
+
return "\n\n".join(text for text in (_block(b) for b in md.parse(markdown)) if text)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _cut(line: str, size: int) -> tuple:
|
|
94
|
+
head = line[:size]
|
|
95
|
+
space = head.rfind(" ")
|
|
96
|
+
if space > size // 2:
|
|
97
|
+
head = head[:space]
|
|
98
|
+
head = _OPEN_TOKEN.sub("", head) or line[:size]
|
|
99
|
+
return head, line[len(head):].lstrip(" ")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def chunk(text: str, size: int = SECTION_MAX) -> list:
|
|
103
|
+
"""Pieces of at most *size*, split between lines wherever possible."""
|
|
104
|
+
chunks: list = []
|
|
105
|
+
current = ""
|
|
106
|
+
for line in text.split("\n"):
|
|
107
|
+
while len(line) > size:
|
|
108
|
+
if current:
|
|
109
|
+
chunks.append(current)
|
|
110
|
+
current = ""
|
|
111
|
+
head, line = _cut(line, size)
|
|
112
|
+
chunks.append(head)
|
|
113
|
+
candidate = f"{current}\n{line}" if current else line
|
|
114
|
+
if len(candidate) > size:
|
|
115
|
+
chunks.append(current)
|
|
116
|
+
current = line
|
|
117
|
+
else:
|
|
118
|
+
current = candidate
|
|
119
|
+
if current.strip():
|
|
120
|
+
chunks.append(current)
|
|
121
|
+
return [c for c in chunks if c.strip()]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _mrkdwn(text: str) -> dict:
|
|
125
|
+
return {"type": "mrkdwn", "text": text, "verbatim": True}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def build_message(markdown: str, *, title: str = "", link: str = "",
|
|
129
|
+
link_label: str = "Open", max_blocks: int = 40,
|
|
130
|
+
max_chars: int = 12000) -> dict:
|
|
131
|
+
"""The webhook payload. A message over the caps is cut and says so."""
|
|
132
|
+
blocks: list = []
|
|
133
|
+
clean_title = " ".join(_CONTROL.sub(" ", title).split())
|
|
134
|
+
if clean_title:
|
|
135
|
+
# A header is plain text: Slack shows entities literally there.
|
|
136
|
+
shown = clean_title.replace("<", "‹").replace(">", "›")
|
|
137
|
+
if len(shown) > HEADER_MAX:
|
|
138
|
+
shown = shown[: HEADER_MAX - 1] + "…"
|
|
139
|
+
blocks.append({"type": "header", "text": {"type": "plain_text", "text": shown}})
|
|
140
|
+
footer: list = []
|
|
141
|
+
if link and md.safe_href(link):
|
|
142
|
+
target = escape_mrkdwn(link).replace("|", "%7C")
|
|
143
|
+
footer.append(f"<{target}|{escape_mrkdwn(link_label)}>")
|
|
144
|
+
room = max_blocks - len(blocks) - 1
|
|
145
|
+
budget = max_chars
|
|
146
|
+
cut = False
|
|
147
|
+
for piece in chunk(markdown_to_mrkdwn(markdown)):
|
|
148
|
+
if room <= 0 or len(piece) > budget:
|
|
149
|
+
cut = True
|
|
150
|
+
break
|
|
151
|
+
blocks.append({"type": "section", "text": _mrkdwn(piece)})
|
|
152
|
+
room -= 1
|
|
153
|
+
budget -= len(piece)
|
|
154
|
+
if cut:
|
|
155
|
+
footer.insert(0, "_The message was shortened._")
|
|
156
|
+
if footer:
|
|
157
|
+
blocks.append({"type": "context", "elements": [_mrkdwn(" ".join(footer))]})
|
|
158
|
+
if not blocks:
|
|
159
|
+
raise ValueError("an empty message")
|
|
160
|
+
first_line = clean_title or " ".join(markdown.split())
|
|
161
|
+
return {
|
|
162
|
+
# Used by notifications; Slack parses it as mrkdwn.
|
|
163
|
+
"text": escape_mrkdwn(first_line[:FALLBACK_MAX]),
|
|
164
|
+
"blocks": blocks,
|
|
165
|
+
"unfurl_links": False,
|
|
166
|
+
"unfurl_media": False,
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
__all__ = ["build_message", "chunk", "escape_mrkdwn", "markdown_to_mrkdwn"]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""The ``slack`` provider: one connection is one channel."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from stapel_integrations_core.stpl_integrations_net import ConfigError
|
|
5
|
+
from stapel_integrations_core.stpl_integrations_providers import (
|
|
6
|
+
CheckResult,
|
|
7
|
+
Field,
|
|
8
|
+
IntegrationProvider,
|
|
9
|
+
InvalidField,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
from .stpl_slack_webhook import SlackWebhookClient, StapelSlackIntegration, validate_webhook_url
|
|
13
|
+
|
|
14
|
+
SLUG = "slack"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SlackProvider(IntegrationProvider):
|
|
18
|
+
slug = SLUG
|
|
19
|
+
title = "Slack"
|
|
20
|
+
fields = (
|
|
21
|
+
Field("webhook_url", "secret", required=True, label="Incoming webhook URL",
|
|
22
|
+
help="Slack app → Incoming Webhooks. It posts to one channel.", max_length=2048),
|
|
23
|
+
Field("channel_label", label="Channel", help="A note for people; Slack ignores it.",
|
|
24
|
+
max_length=120),
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
def clean(self, config: dict, secrets: dict) -> tuple:
|
|
28
|
+
try:
|
|
29
|
+
url = validate_webhook_url(secrets.get("webhook_url", ""))
|
|
30
|
+
except ConfigError as exc:
|
|
31
|
+
raise InvalidField("webhook_url", exc.detail) from exc
|
|
32
|
+
return config, {**secrets, "webhook_url": url}
|
|
33
|
+
|
|
34
|
+
def build(self, config: dict, secrets: dict) -> StapelSlackIntegration:
|
|
35
|
+
return StapelSlackIntegration(SlackWebhookClient(secrets["webhook_url"]))
|
|
36
|
+
|
|
37
|
+
def check(self, config: dict, secrets: dict) -> CheckResult:
|
|
38
|
+
"""A webhook cannot be tried without posting: see the test message."""
|
|
39
|
+
self.clean(config, secrets)
|
|
40
|
+
return CheckResult(ok=None, errors={})
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
__all__ = ["SLUG", "SlackProvider"]
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""``StapelSlackIntegration`` — post to one channel through an incoming webhook.
|
|
2
|
+
|
|
3
|
+
An incoming webhook is bound to the channel it was created for. Its URL is the
|
|
4
|
+
credential. Slack gives no message id and no idempotency key, so a post whose
|
|
5
|
+
outcome is unknown (:class:`UnknownOutcome`) must not be repeated blindly::
|
|
6
|
+
|
|
7
|
+
slack = StapelSlackIntegration(SlackWebhookClient(webhook_url))
|
|
8
|
+
slack.post("## Decisions\\n- ship STPL", title="Weekly sync")
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from typing import Mapping
|
|
14
|
+
|
|
15
|
+
from stapel_integrations_core.stpl_integrations_net import (
|
|
16
|
+
ApiClient,
|
|
17
|
+
ConfigError,
|
|
18
|
+
IntegrationError,
|
|
19
|
+
RawResponse,
|
|
20
|
+
parse_https_url,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
from .conf import slack_settings
|
|
24
|
+
from .stpl_slack_markdown import build_message
|
|
25
|
+
|
|
26
|
+
WEBHOOK_HOST = "hooks.slack.com"
|
|
27
|
+
_PATH = re.compile(r"^/services/T[A-Z0-9]{2,}/B[A-Z0-9]{2,}/[A-Za-z0-9]{8,}$")
|
|
28
|
+
#: Answers after which this webhook will never work again.
|
|
29
|
+
DEAD_CODES = frozenset({
|
|
30
|
+
"no_service", "no_service_id", "no_active_hooks", "invalid_token", "no_team",
|
|
31
|
+
"team_disabled", "channel_not_found", "channel_is_archived", "action_prohibited",
|
|
32
|
+
"posting_to_general_channel_denied", "user_not_found",
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SlackWebhookGone(ConfigError):
|
|
37
|
+
"""Slack revoked or refuses this webhook: a new one must be created."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def validate_webhook_url(url: str) -> str:
|
|
41
|
+
"""The URL, if it is an incoming-webhook URL. Errors never repeat it."""
|
|
42
|
+
parts = parse_https_url(url, (WEBHOOK_HOST,))
|
|
43
|
+
if parts.path.startswith(("/triggers/", "/workflows/")):
|
|
44
|
+
raise ConfigError("this is a Workflow Builder link; an incoming webhook URL is needed")
|
|
45
|
+
if parts.query or parts.fragment or not _PATH.match(parts.path):
|
|
46
|
+
raise ConfigError("this is not a Slack incoming webhook URL")
|
|
47
|
+
return f"https://{WEBHOOK_HOST}{parts.path}"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class SlackWebhookClient(ApiClient):
|
|
51
|
+
user_agent = "stapel-slack"
|
|
52
|
+
|
|
53
|
+
def __init__(self, webhook_url: str, **kwargs) -> None:
|
|
54
|
+
url = validate_webhook_url(webhook_url)
|
|
55
|
+
self._path = url.removeprefix(f"https://{WEBHOOK_HOST}")
|
|
56
|
+
super().__init__(
|
|
57
|
+
WEBHOOK_HOST,
|
|
58
|
+
secrets=(url, self._path, self._path.rsplit("/", 1)[-1]),
|
|
59
|
+
**kwargs,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def send(self, payload: dict) -> None:
|
|
63
|
+
self.post(self._path, payload)
|
|
64
|
+
|
|
65
|
+
def decode(self, response: RawResponse, read_only: bool):
|
|
66
|
+
return response.body.decode("utf-8", "replace")
|
|
67
|
+
|
|
68
|
+
def build_error(self, status: int, headers: Mapping[str, str], detail: str,
|
|
69
|
+
read_only: bool) -> IntegrationError:
|
|
70
|
+
# Slack answers with a bare code such as ``channel_is_archived``.
|
|
71
|
+
code = detail.strip().lower()
|
|
72
|
+
if status == 410 or code in DEAD_CODES:
|
|
73
|
+
return SlackWebhookGone(code or "gone", status=status)
|
|
74
|
+
return super().build_error(status, headers, detail, read_only)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class StapelSlackIntegration:
|
|
78
|
+
def __init__(self, client: SlackWebhookClient) -> None:
|
|
79
|
+
self.client = client
|
|
80
|
+
|
|
81
|
+
def post(self, markdown: str, *, title: str = "", link: str = "",
|
|
82
|
+
link_label: str = "Open") -> None:
|
|
83
|
+
"""Post one message written in Markdown."""
|
|
84
|
+
self.client.send(build_message(
|
|
85
|
+
markdown, title=title, link=link, link_label=link_label,
|
|
86
|
+
max_blocks=int(slack_settings.SLACK_MAX_BLOCKS),
|
|
87
|
+
max_chars=int(slack_settings.SLACK_MAX_CHARS),
|
|
88
|
+
))
|
|
89
|
+
|
|
90
|
+
def post_payload(self, payload: dict) -> None:
|
|
91
|
+
"""A Block Kit payload you built yourself (escape its text yourself)."""
|
|
92
|
+
self.client.send(payload)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
__all__ = [
|
|
96
|
+
"DEAD_CODES", "SlackWebhookClient", "SlackWebhookGone", "StapelSlackIntegration",
|
|
97
|
+
"WEBHOOK_HOST", "validate_webhook_url",
|
|
98
|
+
]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Our own modules are named ``stpl_<library>_<module>``.
|
|
2
|
+
|
|
3
|
+
The package has a flat layout: with the repository root on ``sys.path`` a
|
|
4
|
+
module called ``markdown`` or ``http`` would shadow the real one. Only the
|
|
5
|
+
names Django and the Stapel tools look for stay bare.
|
|
6
|
+
"""
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
CONVENTIONAL = {
|
|
10
|
+
"__init__", "actions", "admin", "apps", "checks", "conf", "conftest", "dto", "errors",
|
|
11
|
+
"functions", "gdpr", "models", "presenters", "serializers", "services", "urls", "urls_v1",
|
|
12
|
+
"views", "_capabilities", "_codegen", "_codegen_settings", "codegen_urls",
|
|
13
|
+
}
|
|
14
|
+
PREFIX = "stpl_slack_"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_every_other_module_is_prefixed():
|
|
18
|
+
root = Path(__file__).resolve().parent.parent
|
|
19
|
+
bare = sorted(
|
|
20
|
+
p.stem for p in root.glob("*.py")
|
|
21
|
+
if p.stem not in CONVENTIONAL and not p.stem.startswith(PREFIX)
|
|
22
|
+
)
|
|
23
|
+
assert bare == []
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Package-level public API (PEP 562 lazy exports) and import hygiene."""
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import stapel_slack
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TestLazyExports:
|
|
10
|
+
def test_all_names_resolve(self):
|
|
11
|
+
for name in stapel_slack.__all__:
|
|
12
|
+
assert getattr(stapel_slack, name) is not None
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TestImportWithoutDjangoSettings:
|
|
16
|
+
def test_package_import_is_django_free(self):
|
|
17
|
+
"""`import stapel_slack` must not import Django nor require settings."""
|
|
18
|
+
env = {k: v for k, v in os.environ.items() if k != "DJANGO_SETTINGS_MODULE"}
|
|
19
|
+
code = (
|
|
20
|
+
"import sys\n"
|
|
21
|
+
"import stapel_slack\n"
|
|
22
|
+
'polluted = [m for m in sys.modules if m == "django" or m.startswith("django.")]\n'
|
|
23
|
+
'assert not polluted, f"django imported at package import time: {polluted}"\n'
|
|
24
|
+
)
|
|
25
|
+
result = subprocess.run(
|
|
26
|
+
[sys.executable, "-c", code],
|
|
27
|
+
capture_output=True,
|
|
28
|
+
text=True,
|
|
29
|
+
env=env,
|
|
30
|
+
cwd=os.path.dirname(sys.executable),
|
|
31
|
+
)
|
|
32
|
+
assert result.returncode == 0, result.stderr
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from stapel_integrations_core.stpl_integrations_net import (
|
|
6
|
+
ConfigError, RateLimited, RejectedError, TransportFailure, UnknownOutcome,
|
|
7
|
+
)
|
|
8
|
+
from stapel_integrations_core.stpl_integrations_testing import FakeTransport
|
|
9
|
+
from stapel_slack import SlackWebhookClient, SlackWebhookGone, StapelSlackIntegration, build_message, markdown_to_mrkdwn
|
|
10
|
+
|
|
11
|
+
PATH = "/services/T00AA/B00BB/abcdefgh12345678"
|
|
12
|
+
URL = "https://hooks.slack.com" + PATH
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def slack(transport):
|
|
16
|
+
return StapelSlackIntegration(SlackWebhookClient(URL, transport=transport, sleep=lambda _s: None))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def texts(message):
|
|
20
|
+
return [b["text"]["text"] if "text" in b else b["elements"][0]["text"] for b in message["blocks"]]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@pytest.mark.parametrize("hostile", ["<!channel>", "<!here>", "<@U123ABC>", "<https://evil.example|bank>"])
|
|
24
|
+
def test_mentions_and_disguised_links_are_inert(hostile):
|
|
25
|
+
message = build_message(f"note {hostile}", title=hostile)
|
|
26
|
+
body = "".join(texts(message)[1:]) + message["text"]
|
|
27
|
+
tokens = re.findall(r"<([^>]*)>", body)
|
|
28
|
+
# Only a bare web address may be a link: it shows exactly where it goes.
|
|
29
|
+
assert all(t.startswith("https://") and "|" not in t for t in tokens), tokens
|
|
30
|
+
assert "<" not in texts(message)[0]
|
|
31
|
+
assert message["unfurl_links"] is False and message["blocks"][-1]["text"]["verbatim"] is True
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_markdown_formatting_and_safe_links():
|
|
35
|
+
out = markdown_to_mrkdwn("## Plan\n\n**ship** *soon* [doc](https://a.example/x) [bad](javascript:1)\n\n- [x] done")
|
|
36
|
+
assert out.startswith("*Plan*\n\n*ship* _soon_ <https://a.example/x|doc> [bad](javascript:1)")
|
|
37
|
+
assert out.endswith("☑ done")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_long_message_is_cut_within_limits_and_says_so():
|
|
41
|
+
message = build_message("\n\n".join("word " * 700 for _ in range(30)), title="t" * 400)
|
|
42
|
+
sections = [b for b in message["blocks"] if b["type"] == "section"]
|
|
43
|
+
assert len(message["blocks"]) <= 40 and all(len(s["text"]["text"]) <= 2900 for s in sections)
|
|
44
|
+
assert sum(len(s["text"]["text"]) for s in sections) <= 12000
|
|
45
|
+
assert "shortened" in texts(message)[-1] and len(texts(message)[0]) == 150
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_chunks_never_split_an_entity():
|
|
49
|
+
message = build_message("&" * 4000)
|
|
50
|
+
for text in texts(message):
|
|
51
|
+
assert "&" not in text.replace("&", "")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_post_sends_once_to_the_webhook_path():
|
|
55
|
+
transport = FakeTransport()
|
|
56
|
+
transport.on("POST", PATH, "ok")
|
|
57
|
+
slack(transport).post("hello", title="T", link="https://a.example", link_label="Open <it>")
|
|
58
|
+
assert transport.calls[0]["host"] == "hooks.slack.com" and len(transport.calls) == 1
|
|
59
|
+
assert transport.calls[0]["json"]["blocks"][-1]["elements"][0]["text"] == "<https://a.example|Open <it>>"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@pytest.mark.parametrize("answer,kind", [
|
|
63
|
+
((404, "no_service"), SlackWebhookGone), ((410, "channel_is_archived"), SlackWebhookGone),
|
|
64
|
+
((400, "invalid_payload"), RejectedError), ((429, "rate_limited"), RateLimited),
|
|
65
|
+
((500, "oops"), UnknownOutcome), (TransportFailure("x", sent=True), UnknownOutcome),
|
|
66
|
+
])
|
|
67
|
+
def test_answers(answer, kind):
|
|
68
|
+
transport = FakeTransport()
|
|
69
|
+
transport.on("POST", PATH, answer)
|
|
70
|
+
with pytest.raises(kind):
|
|
71
|
+
slack(transport).post("hello")
|
|
72
|
+
assert len(transport.calls) == 1
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_the_secret_url_never_leaks():
|
|
76
|
+
transport = FakeTransport()
|
|
77
|
+
transport.on("POST", PATH, (400, f"bad {URL} abcdefgh12345678"))
|
|
78
|
+
integration = slack(transport)
|
|
79
|
+
with pytest.raises(RejectedError) as caught:
|
|
80
|
+
integration.post("x")
|
|
81
|
+
assert "abcdefgh" not in caught.value.detail + str(caught.value) + repr(integration.client)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@pytest.mark.parametrize("url", [
|
|
85
|
+
"http://hooks.slack.com" + PATH, "https://evil.example" + PATH, URL + "?a=1",
|
|
86
|
+
"https://hooks.slack.com/triggers/T00AA/1/abc", "https://hooks.slack.com/services/x",
|
|
87
|
+
"https://hooks.slack.com.evil.example" + PATH,
|
|
88
|
+
])
|
|
89
|
+
def test_bad_webhook_urls_are_refused_without_echo(url):
|
|
90
|
+
with pytest.raises(ConfigError) as caught:
|
|
91
|
+
SlackWebhookClient(url, transport=FakeTransport())
|
|
92
|
+
assert "abcdefgh" not in str(caught.value)
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""v1 URL set, relative to the ``api/v1/`` mount of ``urls.py``."""
|
|
2
|
+
from django.urls import path
|
|
3
|
+
|
|
4
|
+
from .views import TestMessageView
|
|
5
|
+
|
|
6
|
+
urlpatterns = [
|
|
7
|
+
path("connections/<uuid:connection_id>/test-message", TestMessageView.as_view(), name="slack-test-message"),
|
|
8
|
+
]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""One endpoint: send a test message, the only way to try a webhook."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from drf_spectacular.utils import extend_schema
|
|
5
|
+
from stapel_core.django.api.errors import StapelResponse
|
|
6
|
+
from stapel_integrations_core import services
|
|
7
|
+
from stapel_integrations_core.views import IntegrationAPIView, maps_errors
|
|
8
|
+
|
|
9
|
+
from .stpl_slack_provider import SLUG
|
|
10
|
+
|
|
11
|
+
TEST_MESSAGE = "This is a test message. The Slack connection works."
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@extend_schema(tags=["Slack"])
|
|
15
|
+
class TestMessageView(IntegrationAPIView):
|
|
16
|
+
provider_slug = SLUG
|
|
17
|
+
|
|
18
|
+
@extend_schema(request=None, responses={204: None})
|
|
19
|
+
@maps_errors
|
|
20
|
+
def post(self, request, connection_id): # noqa: R007 — settings CRUD and pickers, no user flow of their own
|
|
21
|
+
# A visible action in somebody's channel: for those who manage it.
|
|
22
|
+
row = services.get_connection(request.user, connection_id, services.MANAGE, provider=SLUG)
|
|
23
|
+
services.open_integration(row).post(TEST_MESSAGE)
|
|
24
|
+
return StapelResponse(status=204)
|