Send Slack Notifications from a Web Interface


1Introduction

This mini tutorial explains how to create a simple web interface that sends notifications to a Slack channel.

You’ll need to create a Slack application. Once the application is created, you can generate a webhook URL and select the channel to associate with it.
This process is described in detail in the Slack documentation.


2Project Setup

If you already have an existing Temma project, you can skip this step.

If your Temma project won’t be used to serve a website (and you won’t use Smarty templates), install the minimal version with:

$ composer create-project digicreon/temma-project-api mon_api

If you want to create a full-featured Temma project, including web rendering, install it like this:

$ composer create-project digicreon/temma-project-web mon_site

3Configuration

We’ll keep the configuration minimal, with only what’s strictly necessary.

Edit the file etc/temma.php :

<?php

return [
    'application' => [
        'dataSources' => [
            // definition of the Slack data source
            'slack' => 'slack://WEBHOOK'
        ],
    ],
];

Replace WEBHOOK with the webhook token provided by Slack, without the https:// prefix.
Example : hooks.slack.com/services/TXXXXXXXX/BYYYYYYYY/ZZZZZZZZZZZZZZZZZZZZZZZZ


4Controller

We’ll create a Message controller with three actions, corresponding to the three routes:

  • /message/form: Displays the message input form
  • /message/notify: Processes the submitted form and sends the message to Slack
  • /message/sent: Displays a confirmation message

Create the file controller/Message.php:

<?php

/** Message controller. */
class Message extends \Temma\Web\Controller {
    /** Displays the form. */
    public function form() {
    }
    /** Sends the Slack notification. */
    public function notify() {
        // retrieve the message
        $message = $_POST['message'] ?? null;
        // if message is empty, redirect to form
        if (!$message)
            return $this->_redirect('/message/form');
        // send message to Slack
        $this->slack[''] = $message;
        // redirect to confirmation
        $this->_redirect('/message/sent');
    }
    /** Displays the confirmation message. */
    public function sent() {
    }
}

The form and sent actions do nothing but render a page.

The notify action sends the Slack notification (only if the message is not empty), then redirects accordingly: if empty, back to the form; if valid, to the confirmation page.


5Smarty Templates

Edit the file templates/message/form.tpl :

<html>
<body>
    <form method="post" action="/message/notify">
        Your message:
        <input type="text" name="message">
        <input type="submit" value="Envoyer">
    </form>
</body>
</html>

Edit the file templates/message/sent.tpl :

<html>
<body>
    Your message has been sent to Slack.
</body>
</html>