We moved to Slack few months back and the one thing that I love about Slack, is the integration of various apps with it. Most of the integration are out of the box like Google documents, Dropbox, Git and Bitbucket. But we wanted to integrate Drupal with it. Our need was to send a notification message to the #general channel whenever a new Blog post is published.

We start off by adding a Custom Integration from the Slack App Directory.

Salck custom integration

We will be using the Incoming Webhook as we will be sending data from our Drupal site to Slack.

Select the channel where you want to post the message or create a new one. Once the channel is selected it gives you the setup instructions. The most important part is the Webhook URL which we will be used in our Drupal site. You also get a level of customisation about the slack bot like the name and image.

Next we come to our Drupal site. Drupal 8 has a development release for the module which allows integration of Slack. Once the module is installed go to Slack configuration page at “admin/config/services/slack/config”. Here you will enter the Webhook Url as provided by Slack when the integration was added. Additionally you can also change the username and image of the username who will be sending the message to Slack.

Slack configuration


Try sending a test message from the Slack configuration UI and when everything is setup correctly you will receive a message in Slack.

Now, to send a message to Slack when a node is created or update add the following code:
 


/**
 * Send message via slack.
 * @param $node
 * @param $op
 */
function send_message($node, $op) {
 global $base_url;
 $config = \Drupal::config('slack.settings');
 $channel = 'test';
 $url = Url::fromUri($base_url . '/node/' . $node->id());
 $node_title = $node->label();
 $snippet_user_id = $node->get('field_user')->target_id;
 $account = Term::load($snippet_user_id)->getName();
 $username = $config->get('slack_username');
 $link = render(Link::fromTextAndUrl("here", $url)->toRenderable());
 $webhook_url = $config->get('slack_webhook_url');
 
 if ($op == 'insert') {
   $message = 'Snippet `' . $node_title . '`` was added by *' . $account . '*. Click ' . $link . " to view.";
 }
 else {
   $message = 'Snippet `' . $node_title . '`` was updated by *' . $account . '*. Click ' . $link . " to view.";
 }
 // This will send your message to Slack.
 \Drupal::service('slack')
   ->sendMessage($webhook_url, $message, $channel, $username);
}

 

Salck message


Finally we are trying to integrate Disqus comments with Slack so that when there is a new comment we get a notification about it and respond. 

There you go!
 

 

comments powered by Disqus