Building a Drupal module for Slack notifications
Building a Drupal module that integrates with Slack for notifications gives editorial teams a direct path from content changes to the conversations where follow-up happens. Instead of asking an editor to copy a link into a channel, the module can watch selected events, format a useful update, and deliver it through a workspace without tying Drupal to one hosting model.
A dependable implementation needs more than an outgoing webhook. It must decide which events matter, keep access tokens out of exported configuration, move remote calls away from page requests, and show administrators what happened when delivery fails. The following design works with Drupal 10 and 11 and can live inside an existing site or stand alone.
Define notification scope before choosing Slack features
Start with a notification contract: which Drupal events deserve a message, who may receive it, and what action the message should prompt. A newly published article may warrant a notification, while every autosave should remain silent. This prevents the channel from becoming an unread stream of routine changes.
Map content bundles or workflows to Slack channels instead of using a single destination. Configuration can contain a channel map such as article or service_update, with each value holding a Slack channel identifier. Resolve the channel when the event occurs, and fall back to a general operations channel only when the rules explicitly allow it.
Users need a plain-text fallback and a clear link back to Drupal. Include the content title, event type, author, and canonical URL, but omit internal fields that are irrelevant to the audience. This practical approach reflects the emphasis described in Drupalwoo’s project background: implementation choices should solve a visible editorial problem rather than demonstrate technology for its own sake.
Scaffold the module and its configuration
Use a conventional Drupal module named slack_notify, or adapt the same boundaries to an established notification module. Keep Slack-specific code in services and hooks rather than scattering API calls through content types. This separation makes later changes to Slack’s API or message design less disruptive.
A minimal skeleton starts with the usual metadata, configuration, service, and queue files:
# slack_notify.info.yml
name: 'Slack notifications'
type: module
description: 'Sends selected Drupal events to Slack.'
core_version_requirement: ^10 || ^11
config/install/slack_notify.settings.yml
config/schema/slack_notify.schema.yml
slack_notify.module
slack_notify.services.yml
src/Service/NotificationPublisher.php
src/Service/SlackClient.php
src/SlackNotificationWorker.php
The settings configuration stores non-secret routing values such as a channel map and enabled event names. Define a matching schema so configuration validation catches malformed values during import. Keep bot tokens and signing secrets elsewhere; they should never be committed to a repository or placed in a configuration file that is synchronised between environments.
Connect Drupal to the Slack Web API
Create a Slack app for the organisation’s workspace, grant the minimum scopes required, and install it as a bot. chat:write is the central permission for posting messages; add read permissions only if the module must discover channels. Invite the bot to each private destination, because installation does not automatically grant access to every conversation.
Provide the bot token through an environment-specific secret provider. The following client receives an injected endpoint for the chat.postMessage operation, adds the bearer token, sends JSON, and checks both the HTTP response and Slack’s ok field. This last check matters because Slack can return a successful HTTP status while reporting an application error in the response body.
public function postMessage(array $payload): array
{
$response = $this->httpClient->request('POST', $this->postMessageEndpoint, [
'headers' => [
'Authorization' => 'Bearer ' . $this->tokenProvider->get(),
'Content-Type' => 'application/json; charset=utf-8',
],
'body' => json_encode($payload, JSON_THROW_ON_ERROR),
]);
$result = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
if (!$response->isSuccessful() || ($result['ok'] ?? false) !== true) {
throw new SlackRequestException($result['error'] ?? 'Unknown Slack error');
}
return $result;
}
Build the message in a dedicated formatter, not directly in the HTTP client. A Block Kit payload can provide a heading, concise summary, and action link, while the text value remains visible in notifications and assistive contexts. Escape user-controlled strings before adding them to Slack markup so a title cannot mention an unrelated account or channel.
Queue notifications instead of waiting on Slack
A save request should record the event, not wait for a network round trip. In slack_notify.module, call a publisher service from the generic entity insert and update hooks. The publisher checks enabled event names and the configured channel map, then creates an item on a dedicated Drupal queue.
function slack_notify_entity_insert(EntityInterface $entity): void
{
\Drupal::service('slack_notify.publisher')->publish($entity, 'created');
}
function slack_notify_entity_update(EntityInterface $entity): void
{
\Drupal::service('slack_notify.publisher')->publish($entity, 'updated');
}
Declare slack_notifications with hook_queue_info() and tag the worker service for that queue. The worker can deserialize the payload, call SlackClient, and delete the queue item only after a successful response. A failure should be logged with a queue identifier and reason, while the sensitive message body stays out of the log.
Retries need an explicit policy. Use a dedicated retry state or a second scheduled queue, store an attempt count, and add jittered backoff for Slack rate limits. Give each event a stable identifier so a delivery repeated after a timeout is not posted twice. A small key-value expiry list of sent identifiers can provide this protection without adding another database table.
Run Drupal cron regularly so queued messages are sent promptly. On managed Australian hosting, confirm that cron is not disabled by a low traffic threshold, and monitor the queue’s item count separately from web and database health. A healthy site can still have a growing notification queue if the worker is missing, misconfigured, or repeatedly encountering one malformed payload.
Protect credentials, content, and channel governance
Treat the bot token like a password. Store it in a server environment variable or a secrets-backed key provider, rotate it when team membership changes, and give it only the scopes the module uses. Redact the Authorization header from HTTP debug output, and never log the token, full Slack response, or a draft containing unpublished material.
Slack messages can still contain personal information even when the channel is internal. For Australian organisations covered by the Privacy Act 1988, the Australian Privacy Principles may require purpose limitation, security, and careful control of disclosure. Send the minimum necessary fields, use private channels, restrict bot membership, and document retention. Health-service and government sites may also need to satisfy relevant state or territory records rules.
Channel governance belongs in Drupal configuration. A site editor should be able to see where each bundle is delivered, but only an authorised administrator should change channel identifiers. Validate that identifiers match Slack’s expected format, keep a change history, and test a new destination before enabling it. Content-type access must still govern the linked page; Slack’s channel membership is not a substitute for Drupal permissions.
Recommendations for reliable testing and deployment
Test the module at three levels. Unit tests can use a mocked HTTP client to verify the token header, JSON body, and handling of Slack’s ok: false response. Kernel tests can assert that a configured entity event creates a queue item and that an unconfigured bundle creates none. A staging Slack workspace then provides a safe end-to-end check without touching a production channel.
Australian teams often work across Sydney, Melbourne, Brisbane, and regional offices. Many check Slack on a phone during a morning stand-up or while commuting, so keep the first line meaningful on a small screen and put the full detail behind the Drupal link. Format scheduled messages with an explicit time zone, and test daylight-saving changes rather than assuming every server uses Australian Eastern Time.
The commercial market includes small Drupal agencies, sole consultants, and large in-house teams, so the module should remain portable across self-managed and managed Australian hosting. Avoid provider-specific infrastructure and paid Slack features unless they solve a measured requirement. Release configuration examples, version the API integration, and make upgrades reversible; these qualities often matter more to a small agency than a large service layer.
For most teams, the bot-token Web API provides the best balance of control and simplicity. The alternatives suit different delivery and security needs:
| Approach | Control | Operational effort | Suitable use |
|---|---|---|---|
| Incoming webhook | Low; posting only | Very low | Simple alerts from one server |
| Bot token with Web API | High; channels and formatting | Moderate | Multi-site Drupal notifications |
| Events API gateway | High; incoming Slack events | High | Two-way Slack interactions |
| Message options API | Medium; approved messages | Moderate | Central content-distribution controls |
- Require administrators to map each event explicitly to a channel.
- Keep bot tokens outside Drupal configuration exports.
- Send queued requests and apply bounded retry backoff.
- Give notifications a stable identifier to prevent duplicates.
- Test mobile rendering, time zones, and failure responses.
- Record delivery outcomes without logging sensitive content.
- Review channel access and token scopes after team changes.