emberpost 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.
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.3
2
+ Name: emberpost
3
+ Version: 0.1.0
4
+ Summary: Dispatch PagerDuty on-call schedules to Slack.
5
+ Requires-Dist: jsonschema
6
+ Requires-Dist: pagerduty>=6.2.1
7
+ Requires-Dist: pyyaml>=6.0.3
8
+ Requires-Dist: slack-sdk>=3.41.0
9
+ Requires-Python: >=3.14, <3.15
10
+ Description-Content-Type: text/markdown
11
+
12
+ # emberpost
13
+
14
+ <a name="readme-top"></a>
15
+
16
+ <!-- PROJECT SHIELDS -->
17
+ [![pytest][pytest-badge]][pytest-url]
18
+ [![ruff][ruff-badge]][ruff-url]
19
+ [![prek][prek-badge]][prek-url]
20
+
21
+
22
+ <!-- PROJECT LOGO -->
23
+ <br />
24
+ <div align="center">
25
+ <img src="images/logo.png" alt="Logo" width="350" height="325">
26
+ </a>
27
+
28
+ <h3 align="center">README</h3>
29
+
30
+ <p align="center">
31
+ <a href="https://github.com/JSChronicles/emberpost"><strong>Explore the docs &raquo;</strong></a>
32
+ <br />
33
+ <a href="https://github.com/JSChronicles/emberpost/issues/new?labels=Bug%2CNeeds+Triage&projects=&template=bug.yaml&title=%5BBUG%5D+%3Ctitle%3E">Report Bug</a>
34
+ &middot;
35
+ <a href="https://github.com/JSChronicles/emberpost/issues/new?labels=enhancement%2Cfeature+request&projects=&template=feature.yaml&title=%5BFEATURE%5D%3A+">Request Feature</a>
36
+ </p>
37
+ </div>
38
+
39
+ ## Introduction
40
+
41
+ `emberpost` keeps Slack aligned with the current PagerDuty on-call rotation. It reads a YAML schedule definition, resolves the active on-call users from PagerDuty, maps them to Slack users by email, and then updates the configured Slack channel.
42
+
43
+ Use it to post an on-call summary, update a channel topic, or keep a Slack user group in sync with the people currently carrying the pager. Schedule files can be marked as `daily`, `weekly`, or `manual`, which makes the same command safe to run from automation while only processing the rotations due for that run.
44
+
45
+ Start with [examples/01-minimal.yaml](examples/01-minimal.yaml) for the smallest working schedule shape, then add channel topics, user groups, headers, or footers as needed.
46
+
47
+ ## Usage
48
+ 1. When using the uv tool, there are several ways to run and install dependencies. Here are a few examples:
49
+ 1. Manual setup (similar to pip-tools):
50
+ 1. Create a Python virtual environment: uv venv or python -m venv .venv
51
+ 1. Activate the virtual environment: .\.venv\Scripts\activate.ps1
52
+ 1. Install dependencies: uv pip install --requirements pyproject.toml
53
+ 1. uv sync:
54
+ 1. Sync the project's dependencies with the environment: uv sync
55
+ 1. Activate the virtual environment: .venv\Scripts\activate
56
+ 1. uv run:
57
+ 1. Run a command in the project environment.: `uv run example.py <args>`
58
+ 1. uv run emberpost --schedule-file schedules/oncall.yaml --frequency weekly --dry-run
59
+ 1. Note that if you use uv run in a project, i.e. a directory with a pyproject.toml, it will install the current project before running the script.
60
+
61
+
62
+ - The `--frequency` flag is a guardrail for automation. A schedule file marked `weekly` is skipped when the command runs with `--frequency daily`, which lets daily and weekly jobs share the same command shape.
63
+ - Set `slack.set_channel_topic: true` in the schedule file to update the channel topic instead of posting a message:
64
+
65
+ Run a dry run before writing to Slack:
66
+ ```python
67
+ uv run emberpost --schedule-file schedules/oncall.yaml --frequency weekly --dry-run
68
+ ```
69
+
70
+ Run the weekly schedule and update Slack:
71
+ ```python
72
+ uv run emberpost --schedule-file schedules/oncall.yaml --frequency weekly
73
+ ```
74
+
75
+ Process more than one schedule file in a single run:
76
+ ```python
77
+ uv run emberpost --schedule-file schedules/oncall.yaml examples/03-full.yaml --frequency weekly
78
+ ```
79
+
80
+ Run a manual schedule file:
81
+ ```python
82
+ uv run emberpost --schedule-file examples/01-minimal.yaml --frequency manual --dry-run
83
+ ```
84
+
85
+ Run with more logging while troubleshooting:
86
+ ```python
87
+ uv run emberpost --schedule-file schedules/oncall.yaml --frequency weekly --dry-run --log-level DEBUG
88
+ ```
89
+
90
+ Add `slack_group_id` under a schedule group heading to sync that heading's resolved users to a Slack user group:
91
+
92
+ ```yaml
93
+ pagerduty:
94
+ tenant: example.pagerduty.com
95
+ schedule_groups:
96
+ Platform Coverage:
97
+ slack_group_id: S0123456789
98
+ entries:
99
+ - schedule_id: PEXAMPLE1
100
+ label: "Primary Responder"
101
+ - schedule_id: PEXAMPLE2
102
+ label: "Backup Responder"
103
+ ```
104
+
105
+ ## Setting up your Slack Bot
106
+
107
+ ### Bot Information
108
+ This section is just an example manifest, to show what is needed to get the bot working for the posting use.
109
+
110
+ ```yaml
111
+ display_information:
112
+ name: Notification
113
+ description: Notification webhook/app
114
+ background_color: "#2c2d30"
115
+ features:
116
+ bot_user:
117
+ display_name: Notification
118
+ always_online: false
119
+ oauth_config:
120
+ scopes:
121
+ bot:
122
+ - channels:write.topic
123
+ - chat:write
124
+ - chat:write.customize
125
+ - chat:write.public
126
+ - files:read
127
+ - files:write
128
+ - users:read
129
+ - users:read.email
130
+ - groups:write.topic
131
+ - mpim:history
132
+ - im:write.topic
133
+ - mpim:write.topic
134
+ - usergroups:write
135
+ pkce_enabled: false
136
+ settings:
137
+ interactivity:
138
+ is_enabled: true
139
+ request_url: https://example.com/ignore
140
+ org_deploy_enabled: false
141
+ socket_mode_enabled: false
142
+ token_rotation_enabled: false
143
+ is_mcp_enabled: false
144
+ ```
145
+
146
+ ### Create a slack app
147
+
148
+ 1. Set Up Your App
149
+ 1. Go to the [Slack API portal](https://api.slack.com/apps).
150
+ 1. Click [Create New App](https://api.slack.com/apps?new_app=1).
151
+ 1. Choose From scratch and give your app a name and select the workspace where it will be installed.
152
+ 1. Or if you are choosing to copy one of the above templates/manifests then you can choose From a manifest and speed up the process.
153
+ 1. Configure App Features
154
+ 1. Depending on what your app needs to do, you can enable features like:
155
+ 1. Bot Token: For sending messages and interacting with users.
156
+ 1. Event Subscriptions: To listen for events like messages or reactions.
157
+ 1. Set Permissions (Scopes)
158
+ 1. Go to OAuth & Permissions.
159
+ 1. Add the necessary OAuth scopes (e.g., chat:write, commands, users:read).
160
+ 1. These define what your app is allowed to do in the workspace.
161
+ 1. Install the App
162
+ 1. Still in the OAuth & Permissions section, click "Install to Workspace".
163
+ 1. Authorize the app to access your workspace.
164
+ 1. A Slack Admin for your organization will need to review the request
165
+ 1. You’ll receive a Bot User OAuth Token once approved
166
+ 1. save this securely.
167
+
168
+ ### Setup GitHub Repository Slack Notification
169
+ 1. Create a slack app, if you haven't already
170
+ 1. Go to the GitHub repository → Select Settings → select Secrets and variables → Select Actions → Add these three secrets under New repository secret and under Dependabot
171
+ 1. `SLACK_BOT_TOKEN` - This is the authentication token you receive after creating and installing your Slack app. It allows your app to interact with the Slack API and post messages as a bot.
172
+ 1. `SLACK_CHANNEL_ID` - The ID of the primary Slack channel where you want production alerts or notifications to be sent.
173
+ 1. To find a channel ID, right-click on any Slack channel you have access to and select Copy then Copy link. The URL will look something like this: `https://xxxxx.slack.com/archives/Cxxxxx`. The part at the end that starts with a 'C' is the channel ID you’ll need.
174
+ 1. `SLACK_CHANNEL_ID_TEST` - An optional separate channel ID used for testing purposes. It's recommended to use this during development to avoid cluttering your main channel with test messages.
175
+
176
+
177
+
178
+ <!-- MARKDOWN LINKS & IMAGES -->
179
+ [pytest-badge]:https://github.com/JSChronicles/emberpost/actions/workflows/pytest.yaml/badge.svg?branch=main
180
+ [pytest-url]:https://github.com/JSChronicles/emberpost/actions/workflows/pytest.yaml
181
+ [ruff-badge]:https://github.com/JSChronicles/emberpost/actions/workflows/ruff.yaml/badge.svg?branch=main
182
+ [ruff-url]:https://github.com/JSChronicles/emberpost/actions/workflows/ruff.yaml
183
+
184
+ [prek-badge]:https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/j178/prek/master/docs/assets/badge-v0.json
185
+ [prek-url]:https://github.com/j178/prek
@@ -0,0 +1,174 @@
1
+ # emberpost
2
+
3
+ <a name="readme-top"></a>
4
+
5
+ <!-- PROJECT SHIELDS -->
6
+ [![pytest][pytest-badge]][pytest-url]
7
+ [![ruff][ruff-badge]][ruff-url]
8
+ [![prek][prek-badge]][prek-url]
9
+
10
+
11
+ <!-- PROJECT LOGO -->
12
+ <br />
13
+ <div align="center">
14
+ <img src="images/logo.png" alt="Logo" width="350" height="325">
15
+ </a>
16
+
17
+ <h3 align="center">README</h3>
18
+
19
+ <p align="center">
20
+ <a href="https://github.com/JSChronicles/emberpost"><strong>Explore the docs &raquo;</strong></a>
21
+ <br />
22
+ <a href="https://github.com/JSChronicles/emberpost/issues/new?labels=Bug%2CNeeds+Triage&projects=&template=bug.yaml&title=%5BBUG%5D+%3Ctitle%3E">Report Bug</a>
23
+ &middot;
24
+ <a href="https://github.com/JSChronicles/emberpost/issues/new?labels=enhancement%2Cfeature+request&projects=&template=feature.yaml&title=%5BFEATURE%5D%3A+">Request Feature</a>
25
+ </p>
26
+ </div>
27
+
28
+ ## Introduction
29
+
30
+ `emberpost` keeps Slack aligned with the current PagerDuty on-call rotation. It reads a YAML schedule definition, resolves the active on-call users from PagerDuty, maps them to Slack users by email, and then updates the configured Slack channel.
31
+
32
+ Use it to post an on-call summary, update a channel topic, or keep a Slack user group in sync with the people currently carrying the pager. Schedule files can be marked as `daily`, `weekly`, or `manual`, which makes the same command safe to run from automation while only processing the rotations due for that run.
33
+
34
+ Start with [examples/01-minimal.yaml](examples/01-minimal.yaml) for the smallest working schedule shape, then add channel topics, user groups, headers, or footers as needed.
35
+
36
+ ## Usage
37
+ 1. When using the uv tool, there are several ways to run and install dependencies. Here are a few examples:
38
+ 1. Manual setup (similar to pip-tools):
39
+ 1. Create a Python virtual environment: uv venv or python -m venv .venv
40
+ 1. Activate the virtual environment: .\.venv\Scripts\activate.ps1
41
+ 1. Install dependencies: uv pip install --requirements pyproject.toml
42
+ 1. uv sync:
43
+ 1. Sync the project's dependencies with the environment: uv sync
44
+ 1. Activate the virtual environment: .venv\Scripts\activate
45
+ 1. uv run:
46
+ 1. Run a command in the project environment.: `uv run example.py <args>`
47
+ 1. uv run emberpost --schedule-file schedules/oncall.yaml --frequency weekly --dry-run
48
+ 1. Note that if you use uv run in a project, i.e. a directory with a pyproject.toml, it will install the current project before running the script.
49
+
50
+
51
+ - The `--frequency` flag is a guardrail for automation. A schedule file marked `weekly` is skipped when the command runs with `--frequency daily`, which lets daily and weekly jobs share the same command shape.
52
+ - Set `slack.set_channel_topic: true` in the schedule file to update the channel topic instead of posting a message:
53
+
54
+ Run a dry run before writing to Slack:
55
+ ```python
56
+ uv run emberpost --schedule-file schedules/oncall.yaml --frequency weekly --dry-run
57
+ ```
58
+
59
+ Run the weekly schedule and update Slack:
60
+ ```python
61
+ uv run emberpost --schedule-file schedules/oncall.yaml --frequency weekly
62
+ ```
63
+
64
+ Process more than one schedule file in a single run:
65
+ ```python
66
+ uv run emberpost --schedule-file schedules/oncall.yaml examples/03-full.yaml --frequency weekly
67
+ ```
68
+
69
+ Run a manual schedule file:
70
+ ```python
71
+ uv run emberpost --schedule-file examples/01-minimal.yaml --frequency manual --dry-run
72
+ ```
73
+
74
+ Run with more logging while troubleshooting:
75
+ ```python
76
+ uv run emberpost --schedule-file schedules/oncall.yaml --frequency weekly --dry-run --log-level DEBUG
77
+ ```
78
+
79
+ Add `slack_group_id` under a schedule group heading to sync that heading's resolved users to a Slack user group:
80
+
81
+ ```yaml
82
+ pagerduty:
83
+ tenant: example.pagerduty.com
84
+ schedule_groups:
85
+ Platform Coverage:
86
+ slack_group_id: S0123456789
87
+ entries:
88
+ - schedule_id: PEXAMPLE1
89
+ label: "Primary Responder"
90
+ - schedule_id: PEXAMPLE2
91
+ label: "Backup Responder"
92
+ ```
93
+
94
+ ## Setting up your Slack Bot
95
+
96
+ ### Bot Information
97
+ This section is just an example manifest, to show what is needed to get the bot working for the posting use.
98
+
99
+ ```yaml
100
+ display_information:
101
+ name: Notification
102
+ description: Notification webhook/app
103
+ background_color: "#2c2d30"
104
+ features:
105
+ bot_user:
106
+ display_name: Notification
107
+ always_online: false
108
+ oauth_config:
109
+ scopes:
110
+ bot:
111
+ - channels:write.topic
112
+ - chat:write
113
+ - chat:write.customize
114
+ - chat:write.public
115
+ - files:read
116
+ - files:write
117
+ - users:read
118
+ - users:read.email
119
+ - groups:write.topic
120
+ - mpim:history
121
+ - im:write.topic
122
+ - mpim:write.topic
123
+ - usergroups:write
124
+ pkce_enabled: false
125
+ settings:
126
+ interactivity:
127
+ is_enabled: true
128
+ request_url: https://example.com/ignore
129
+ org_deploy_enabled: false
130
+ socket_mode_enabled: false
131
+ token_rotation_enabled: false
132
+ is_mcp_enabled: false
133
+ ```
134
+
135
+ ### Create a slack app
136
+
137
+ 1. Set Up Your App
138
+ 1. Go to the [Slack API portal](https://api.slack.com/apps).
139
+ 1. Click [Create New App](https://api.slack.com/apps?new_app=1).
140
+ 1. Choose From scratch and give your app a name and select the workspace where it will be installed.
141
+ 1. Or if you are choosing to copy one of the above templates/manifests then you can choose From a manifest and speed up the process.
142
+ 1. Configure App Features
143
+ 1. Depending on what your app needs to do, you can enable features like:
144
+ 1. Bot Token: For sending messages and interacting with users.
145
+ 1. Event Subscriptions: To listen for events like messages or reactions.
146
+ 1. Set Permissions (Scopes)
147
+ 1. Go to OAuth & Permissions.
148
+ 1. Add the necessary OAuth scopes (e.g., chat:write, commands, users:read).
149
+ 1. These define what your app is allowed to do in the workspace.
150
+ 1. Install the App
151
+ 1. Still in the OAuth & Permissions section, click "Install to Workspace".
152
+ 1. Authorize the app to access your workspace.
153
+ 1. A Slack Admin for your organization will need to review the request
154
+ 1. You’ll receive a Bot User OAuth Token once approved
155
+ 1. save this securely.
156
+
157
+ ### Setup GitHub Repository Slack Notification
158
+ 1. Create a slack app, if you haven't already
159
+ 1. Go to the GitHub repository → Select Settings → select Secrets and variables → Select Actions → Add these three secrets under New repository secret and under Dependabot
160
+ 1. `SLACK_BOT_TOKEN` - This is the authentication token you receive after creating and installing your Slack app. It allows your app to interact with the Slack API and post messages as a bot.
161
+ 1. `SLACK_CHANNEL_ID` - The ID of the primary Slack channel where you want production alerts or notifications to be sent.
162
+ 1. To find a channel ID, right-click on any Slack channel you have access to and select Copy then Copy link. The URL will look something like this: `https://xxxxx.slack.com/archives/Cxxxxx`. The part at the end that starts with a 'C' is the channel ID you’ll need.
163
+ 1. `SLACK_CHANNEL_ID_TEST` - An optional separate channel ID used for testing purposes. It's recommended to use this during development to avoid cluttering your main channel with test messages.
164
+
165
+
166
+
167
+ <!-- MARKDOWN LINKS & IMAGES -->
168
+ [pytest-badge]:https://github.com/JSChronicles/emberpost/actions/workflows/pytest.yaml/badge.svg?branch=main
169
+ [pytest-url]:https://github.com/JSChronicles/emberpost/actions/workflows/pytest.yaml
170
+ [ruff-badge]:https://github.com/JSChronicles/emberpost/actions/workflows/ruff.yaml/badge.svg?branch=main
171
+ [ruff-url]:https://github.com/JSChronicles/emberpost/actions/workflows/ruff.yaml
172
+
173
+ [prek-badge]:https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/j178/prek/master/docs/assets/badge-v0.json
174
+ [prek-url]:https://github.com/j178/prek
@@ -0,0 +1,92 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.11.7,<0.12"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "emberpost"
7
+ version = "0.1.0"
8
+ description = "Dispatch PagerDuty on-call schedules to Slack."
9
+ readme = "README.md"
10
+ requires-python = ">=3.14,<3.15"
11
+ dependencies = [
12
+ "jsonschema",
13
+ "pagerduty>=6.2.1",
14
+ "pyyaml>=6.0.3",
15
+ "slack-sdk>=3.41.0",
16
+ ]
17
+
18
+ [project.scripts]
19
+ emberpost = "emberpost.post:main"
20
+
21
+ [dependency-groups]
22
+ dev = [
23
+ "pytest-cov==7.1.0",
24
+ "pytest==9.0.3",
25
+ "prek==0.3.8",
26
+ "check-jsonschema",
27
+ "ruff",
28
+ "ty",
29
+ ]
30
+
31
+ [tool.ty.environment]
32
+ python = ".venv"
33
+
34
+ [tool.pytest.ini_options]
35
+ pythonpath = "src"
36
+ addopts = "-s -v --cov=emberpost --cov-report=term-missing --cov-fail-under=50"
37
+ norecursedirs = [".git", "__pycache__", ".venv"]
38
+ testpaths = ["tests"]
39
+
40
+ [tool.coverage.run]
41
+ omit = [
42
+ "tests/*",
43
+ ]
44
+
45
+
46
+ [tool.ruff]
47
+ # https://docs.astral.sh/ruff/settings/
48
+ exclude = [
49
+ ".bzr",
50
+ ".direnv",
51
+ ".eggs",
52
+ ".git",
53
+ ".git-rewrite",
54
+ ".hg",
55
+ ".ipynb_checkpoints",
56
+ ".mypy_cache",
57
+ ".nox",
58
+ ".pants.d",
59
+ ".pyenv",
60
+ ".pytest_cache",
61
+ ".pytype",
62
+ ".ruff_cache",
63
+ ".svn",
64
+ ".tox",
65
+ ".venv",
66
+ ".vscode",
67
+ "__pypackages__",
68
+ "_build",
69
+ "buck-out",
70
+ "build",
71
+ "dist",
72
+ "node_modules",
73
+ "site-packages",
74
+ "venv",
75
+ ]
76
+ line-length = 88
77
+ indent-width = 4
78
+ target-version = "py314"
79
+
80
+ [tool.ruff.lint]
81
+ select = ["N", "E4", "E7", "E9", "F"]
82
+ ignore = []
83
+ task-tags = ["TODO", "FIXME", "HACK"]
84
+ fixable = ["ALL"]
85
+ unfixable = []
86
+ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
87
+
88
+ [tool.ruff.format]
89
+ quote-style = "double"
90
+ indent-style = "space"
91
+ skip-magic-trailing-comma = true
92
+ line-ending = "auto"
@@ -0,0 +1 @@
1
+ """On-call dispatch package."""
@@ -0,0 +1,63 @@
1
+ import os
2
+ import re
3
+ from dataclasses import dataclass
4
+
5
+ import pagerduty
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class PagerDutyOnCall:
10
+ email: str
11
+ name: str
12
+
13
+
14
+ class PagerDutyClient:
15
+ def __init__(self, tenant: str) -> None:
16
+ self.tenant = tenant
17
+ self.client = pagerduty.RestApiV2Client(self._api_key())
18
+
19
+ def get_oncalls(self, schedule_ids: list[str]) -> dict[str, PagerDutyOnCall]:
20
+ if not schedule_ids:
21
+ return {}
22
+
23
+ response = self.client.jget(
24
+ "oncalls", params={"schedule_ids": schedule_ids, "earliest": True}
25
+ )
26
+
27
+ oncalls_by_schedule_id: dict[str, dict] = {}
28
+ user_ids: set[str] = set()
29
+
30
+ for oncall in response.get("oncalls", []):
31
+ schedule_id = oncall["schedule"]["id"]
32
+ if schedule_id in oncalls_by_schedule_id:
33
+ continue
34
+ oncalls_by_schedule_id[schedule_id] = oncall
35
+ user_ids.add(oncall["user"]["id"])
36
+
37
+ missing_schedule_ids = set(schedule_ids) - set(oncalls_by_schedule_id)
38
+ if missing_schedule_ids:
39
+ missing = ", ".join(sorted(missing_schedule_ids))
40
+ raise ValueError(f"No on-call user found for schedule(s): {missing}")
41
+
42
+ users_by_id = {
43
+ user_id: self.client.rget(f"users/{user_id}")
44
+ for user_id in sorted(user_ids)
45
+ }
46
+
47
+ return {
48
+ schedule_id: PagerDutyOnCall(
49
+ email=users_by_id[oncall["user"]["id"]]["email"],
50
+ name=oncall["user"]["summary"],
51
+ )
52
+ for schedule_id, oncall in oncalls_by_schedule_id.items()
53
+ }
54
+
55
+ def _api_key(self) -> str:
56
+ tenant_env_name = re.sub(r"[^A-Z0-9]", "_", self.tenant.upper())
57
+ env_var = f"PAGERDUTY_API_KEY_{tenant_env_name}"
58
+ api_key = os.getenv(env_var)
59
+ if not api_key:
60
+ raise ValueError(
61
+ f"Missing PagerDuty API key for {self.tenant}. Set {env_var}."
62
+ )
63
+ return api_key
@@ -0,0 +1,233 @@
1
+ import argparse
2
+ import logging
3
+ from dataclasses import dataclass
4
+ from datetime import date
5
+ from pathlib import Path
6
+
7
+ from emberpost.pagerduty import PagerDutyClient
8
+ from emberpost.schedule_config import (
9
+ Frequency,
10
+ PagerDutyScheduleEntry,
11
+ PagerDutyScheduleGroup,
12
+ ScheduleConfig,
13
+ load_schedule,
14
+ )
15
+ from emberpost.slack import SlackClient
16
+
17
+ __LOGGER__ = logging.getLogger(__name__)
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class OnCallAssignment:
22
+ group_name: str
23
+ slack_group_id: str | None
24
+ schedule: PagerDutyScheduleEntry
25
+ pagerduty_name: str
26
+ slack_user_id: str | None
27
+
28
+ @property
29
+ def message_line(self) -> str:
30
+ if self.slack_user_id is None:
31
+ raise ValueError("Slack user ID is required to render a Slack mention")
32
+ return f"{self.schedule.label}: <@{self.slack_user_id}>"
33
+
34
+ @property
35
+ def topic_line(self) -> str:
36
+ return f"{self.schedule.label}: {self.pagerduty_name}"
37
+
38
+
39
+ def collect_assignments(
40
+ config: ScheduleConfig,
41
+ pagerduty_client,
42
+ slack_client,
43
+ *,
44
+ resolve_slack_users: bool = True,
45
+ today: date | None = None,
46
+ ) -> list[OnCallAssignment]:
47
+ today = today or date.today()
48
+ assignments: list[OnCallAssignment] = []
49
+ schedule_ids = [
50
+ schedule.schedule_id
51
+ for group in config.pagerduty.schedule_groups.values()
52
+ for schedule in group.entries
53
+ ]
54
+ oncalls_by_schedule_id = pagerduty_client.get_oncalls(schedule_ids)
55
+ slack_ids_by_email: dict[str, str] = {}
56
+
57
+ for group_name, group in config.pagerduty.schedule_groups.items():
58
+ for schedule in entries_for_week(group, today):
59
+ oncall = oncalls_by_schedule_id[schedule.schedule_id]
60
+ email = str(oncall.email)
61
+ assignment_needs_slack_user = (
62
+ resolve_slack_users or group.slack_group_id is not None
63
+ )
64
+ if assignment_needs_slack_user and email not in slack_ids_by_email:
65
+ slack_ids_by_email[email] = slack_client.get_user_id_by_email(
66
+ oncall.email
67
+ )
68
+ assignments.append(
69
+ OnCallAssignment(
70
+ group_name=group_name,
71
+ slack_group_id=group.slack_group_id,
72
+ schedule=schedule,
73
+ pagerduty_name=oncall.name,
74
+ slack_user_id=slack_ids_by_email.get(email),
75
+ )
76
+ )
77
+
78
+ return assignments
79
+
80
+
81
+ def entries_for_week(
82
+ group: PagerDutyScheduleGroup, today: date
83
+ ) -> list[PagerDutyScheduleEntry]:
84
+ if group.swap_on_odd_weeks and today.isocalendar().week % 2 == 1:
85
+ return [group.entries[1], group.entries[0]]
86
+ return group.entries
87
+
88
+
89
+ def render(assignments: list[OnCallAssignment], *, for_topic: bool) -> str:
90
+ lines: list[str] = []
91
+ current_group: str | None = None
92
+
93
+ for assignment in assignments:
94
+ if assignment.group_name != current_group:
95
+ if lines:
96
+ lines.append("")
97
+ lines.append(assignment.group_name)
98
+ current_group = assignment.group_name
99
+
100
+ lines.append(assignment.topic_line if for_topic else assignment.message_line)
101
+
102
+ return "\n".join(lines)
103
+
104
+
105
+ def slack_user_group_updates(
106
+ assignments: list[OnCallAssignment],
107
+ ) -> dict[str, list[str]]:
108
+ updates: dict[str, list[str]] = {}
109
+ for assignment in assignments:
110
+ if assignment.slack_group_id is None:
111
+ continue
112
+ if assignment.slack_user_id is None:
113
+ raise ValueError("Slack user ID is required to update a Slack user group")
114
+ user_ids = updates.setdefault(assignment.slack_group_id, [])
115
+ if assignment.slack_user_id not in user_ids:
116
+ user_ids.append(assignment.slack_user_id)
117
+ return updates
118
+
119
+
120
+ def dispatch(config: ScheduleConfig, frequency: Frequency, *, dry_run: bool) -> None:
121
+ if config.suspended:
122
+ __LOGGER__.info(f"{config.id} is suspended; skipping")
123
+ return
124
+
125
+ if config.schedule != frequency:
126
+ __LOGGER__.info(
127
+ f"{config.id} is scheduled for {config.schedule}; skipping {frequency}"
128
+ )
129
+ return
130
+
131
+ pagerduty_client = PagerDutyClient(config.pagerduty.tenant)
132
+ slack_client = SlackClient(config.slack.slack_space, config.slack.slack_channel_id)
133
+ resolve_slack_users = not config.slack.set_channel_topic
134
+ assignments = collect_assignments(
135
+ config, pagerduty_client, slack_client, resolve_slack_users=resolve_slack_users
136
+ )
137
+ rendered = render(assignments, for_topic=config.slack.set_channel_topic)
138
+
139
+ if config.message_header:
140
+ rendered = f"{config.message_header}\n{rendered}"
141
+ if config.message_footer:
142
+ rendered = f"{rendered}\n{config.message_footer}"
143
+
144
+ if dry_run:
145
+ target = (
146
+ "channel topic" if config.slack.set_channel_topic else "channel message"
147
+ )
148
+ print(
149
+ f"(dry-run) Would update Slack {target} for {config.slack.slack_channel_id}:"
150
+ )
151
+ print(rendered)
152
+ for slack_group_id, user_ids in slack_user_group_updates(assignments).items():
153
+ print(
154
+ f"(dry-run) Would update Slack user group "
155
+ f"{slack_group_id}: {','.join(user_ids)}"
156
+ )
157
+ return
158
+
159
+ if config.slack.set_channel_topic:
160
+ slack_client.update_channel_topic(rendered)
161
+ else:
162
+ slack_client.post_message(rendered)
163
+
164
+ for slack_group_id, user_ids in slack_user_group_updates(assignments).items():
165
+ slack_client.update_user_group(slack_group_id, user_ids)
166
+
167
+
168
+ def dispatch_schedule_files(
169
+ schedule_files: list[Path], frequency: Frequency, *, dry_run: bool
170
+ ) -> None:
171
+ failed = False
172
+
173
+ for schedule_file in schedule_files:
174
+ __LOGGER__.info(f"Processing {schedule_file}")
175
+ try:
176
+ config = load_schedule(schedule_file)
177
+ dispatch(config, frequency, dry_run=dry_run)
178
+ except Exception:
179
+ __LOGGER__.exception(f"Error processing {schedule_file}")
180
+ failed = True
181
+
182
+ if failed:
183
+ raise RuntimeError("One or more schedule files failed to process")
184
+
185
+
186
+ def parse_args() -> argparse.Namespace:
187
+ parser = argparse.ArgumentParser(
188
+ description="Dispatch PagerDuty on-call schedules to Slack."
189
+ )
190
+ parser.add_argument(
191
+ "--schedule-file",
192
+ nargs="+",
193
+ type=Path,
194
+ required=True,
195
+ help="One or more schedule YAML files to process.",
196
+ )
197
+ parser.add_argument(
198
+ "--frequency",
199
+ choices=list(Frequency),
200
+ required=True,
201
+ help="Only process schedules matching this frequency.",
202
+ )
203
+ parser.add_argument(
204
+ "--dry-run",
205
+ action="store_true",
206
+ help="Resolve on-call users and print intended Slack changes without writing to Slack.",
207
+ )
208
+ parser.add_argument(
209
+ "--log-level",
210
+ default="INFO",
211
+ choices=["DEBUG", "INFO", "WARNING", "ERROR"],
212
+ help="Logging level.",
213
+ )
214
+ return parser.parse_args()
215
+
216
+
217
+ def main() -> None:
218
+ args = parse_args()
219
+ logging.basicConfig(
220
+ level=getattr(logging, args.log_level),
221
+ format=("%(levelname)-8s [%(filename)s:%(funcName)s:%(lineno)d] %(message)s"),
222
+ )
223
+ if args.log_level != "DEBUG":
224
+ # Suppress HTTP request logs from the PagerDuty client at INFO.
225
+ logging.getLogger("httpx").setLevel(logging.WARNING)
226
+
227
+ dispatch_schedule_files(
228
+ args.schedule_file, Frequency(args.frequency), dry_run=args.dry_run
229
+ )
230
+
231
+
232
+ if __name__ == "__main__":
233
+ main()
@@ -0,0 +1,110 @@
1
+ import json
2
+ from dataclasses import dataclass
3
+ from enum import StrEnum
4
+ from pathlib import Path
5
+
6
+ import jsonschema
7
+ import yaml
8
+
9
+
10
+ SCHEMA_PATH = Path(__file__).resolve().parents[2] / "schemas" / "schedule.schema.json"
11
+
12
+
13
+ class Frequency(StrEnum):
14
+ daily = "daily"
15
+ weekly = "weekly"
16
+ manual = "manual"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class PagerDutyScheduleEntry:
21
+ schedule_id: str
22
+ label: str
23
+
24
+ @classmethod
25
+ def from_dict(cls, config: dict) -> "PagerDutyScheduleEntry":
26
+ return cls(schedule_id=config["schedule_id"], label=config["label"])
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class PagerDutyScheduleGroup:
31
+ entries: list[PagerDutyScheduleEntry]
32
+ slack_group_id: str | None = None
33
+ swap_on_odd_weeks: bool = False
34
+
35
+ @classmethod
36
+ def from_dict(cls, config: dict) -> "PagerDutyScheduleGroup":
37
+ return cls(
38
+ entries=[
39
+ PagerDutyScheduleEntry.from_dict(entry) for entry in config["entries"]
40
+ ],
41
+ slack_group_id=config.get("slack_group_id"),
42
+ swap_on_odd_weeks=config.get("swap_on_odd_weeks", False),
43
+ )
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class PagerDutyConfig:
48
+ tenant: str
49
+ schedule_groups: dict[str, PagerDutyScheduleGroup]
50
+
51
+ @classmethod
52
+ def from_dict(cls, config: dict) -> "PagerDutyConfig":
53
+ return cls(
54
+ tenant=config["tenant"],
55
+ schedule_groups={
56
+ group_name: PagerDutyScheduleGroup.from_dict(group)
57
+ for group_name, group in config["schedule_groups"].items()
58
+ },
59
+ )
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class SlackConfig:
64
+ slack_space: str
65
+ slack_channel_id: str
66
+ set_channel_topic: bool = False
67
+
68
+ @classmethod
69
+ def from_dict(cls, config: dict) -> "SlackConfig":
70
+ return cls(
71
+ slack_space=config["slack_space"],
72
+ slack_channel_id=config["slack_channel_id"],
73
+ set_channel_topic=config.get("set_channel_topic", False),
74
+ )
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class ScheduleConfig:
79
+ id: str
80
+ schedule: Frequency
81
+ pagerduty: PagerDutyConfig
82
+ slack: SlackConfig
83
+ suspended: bool = False
84
+ message_header: str | None = None
85
+ message_footer: str | None = None
86
+
87
+ @classmethod
88
+ def from_dict(cls, config: dict) -> "ScheduleConfig":
89
+ return cls(
90
+ id=config["id"],
91
+ schedule=Frequency(config["schedule"]),
92
+ suspended=config.get("suspended", False),
93
+ pagerduty=PagerDutyConfig.from_dict(config["pagerduty"]),
94
+ slack=SlackConfig.from_dict(config["slack"]),
95
+ message_header=config.get("message_header"),
96
+ message_footer=config.get("message_footer"),
97
+ )
98
+
99
+
100
+ def load_schedule(path: Path) -> ScheduleConfig:
101
+ with path.open(encoding="utf-8") as schedule_file:
102
+ raw_config = yaml.safe_load(schedule_file)
103
+
104
+ validate_schedule_schema(raw_config)
105
+ return ScheduleConfig.from_dict(raw_config)
106
+
107
+
108
+ def validate_schedule_schema(config: object) -> None:
109
+ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
110
+ jsonschema.validate(config, schema)
@@ -0,0 +1,36 @@
1
+ import os
2
+ import re
3
+
4
+ from slack_sdk import WebClient
5
+
6
+
7
+ class SlackClient:
8
+ def __init__(self, slack_space: str, channel_id: str) -> None:
9
+ self.slack_space = slack_space
10
+ self.channel_id = channel_id
11
+ self.client = WebClient(token=self._api_key())
12
+
13
+ def get_user_id_by_email(self, email: str) -> str:
14
+ response = self.client.users_lookupByEmail(email=str(email))
15
+ return response["user"]["id"]
16
+
17
+ def post_message(self, message: str) -> None:
18
+ self.client.chat_postMessage(channel=self.channel_id, text=message)
19
+
20
+ def update_channel_topic(self, topic: str) -> None:
21
+ self.client.conversations_setTopic(channel=self.channel_id, topic=topic)
22
+
23
+ def update_user_group(self, user_group_id: str, user_ids: list[str]) -> None:
24
+ self.client.usergroups_users_update(
25
+ usergroup=user_group_id, users=",".join(user_ids)
26
+ )
27
+
28
+ def _api_key(self) -> str:
29
+ slack_space_env_name = re.sub(r"[^A-Z0-9]", "_", self.slack_space.upper())
30
+ env_var = f"SLACK_API_KEY_{slack_space_env_name}"
31
+ api_key = os.getenv(env_var)
32
+ if not api_key:
33
+ raise ValueError(
34
+ f"Missing Slack API key for {self.slack_space}. Set {env_var}."
35
+ )
36
+ return api_key