Declaration of VAR

and some other stuff

Telegram notifications for Drupal

2016-08-18 12:12:08 +0200

2016-08-18 12:12:08 +0200 | Comments

In previous posts I described how to send notifications from WordpPress and MediaWiki via Telegram bot (it is all in Russian, but you can just Google Translate it - should be fine).

Now I want to tell you, how to send notifications about new posts (and/or comments) from Drupal.

Everything was tested with Drupal version 8.1.8.

I was surprised, when discovered, that there is no hooks/API for “publish” event in Drupal out-of-the-box, like how it’s done in MediaWiki and WordPress. Perhaps, I didn’t look for it hard enough, but the fact that I failed to find it quickly is enough :)

So, first you need to install a new module, which provides such hooks - Hook Post Action (don’t forget to activate it). That will create the following folder: \modules\hook_post_action\. Go inside and make a copy of the folder with example (hook_post_action_example) and rename it to hook_post_action_telegram (or any other name) and rename both files inside it as well. After all this you should have the following structure:

\modules\hook_post_action\
|__ hook_post_action_telegram\
    |__ hook_post_action_telegram.module
    |__ hook_post_action_telegram.info.yml

Once again, you need to activate in from admin-page of your Drupal.

You can put some info to the *.yml file, but it doesn’t matter. The interesting stuff is happening inside the *.module. Delete everything except the very first function hook_post_action_example_entity_postsave (or any other, if you understand the difference). Rename it to hook_post_action_telegram_entity_postsave (or any other name) and that’s where you implement the notification. I simply copied it from my WordPress plugin, as it’s all the same, and adjusted it to Drupal’s specifics:

<?php

/**
 * @file
 * Telegram notifications
 */

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_postsave()
 */
function hook_post_action_telegram_entity_postsave(EntityInterface $entity, $op) {
  // ID for the entity (post, comment or something else)
  $id = $entity->id();
  $entity_type = $entity->getEntityTypeId();

  // write some info to log (you can view log at admin menu Reports -> Recent log messages)
  \Drupal::logger('hook_post_action')->info("[telegram] {$op} entity {$entity_type} with ID '{$id}' from " . __FUNCTION__);
    
    // we want to notify only about new posts, ignoring comments
    if ($entity_type == "node" && ($op == "insert" || $op == "update"))
    {
        try
        {
          // Telegram user or channel ID (not the bot token)
          $chatID = SOME-TELEGRAM-ID-HERE;
          
          // some info about the post
          $node = node_load($id);
          $ttl = $node->getTitle();
          
          // URL to the post
          global $base_url;
          $posturl = $base_url . $entity->url();
          
          // notify only about published posts
          if ($node->isPublished() == 1)
          {
              // message will be with Markdown
              //$msg = "{$entity_type} / {$op} with ID '{$id}': " . $posturl;
              $msg = "New post: \"_{$ttl}_\". " . str_replace("_", "\_", $posturl);
              
              // cURL stuff
              $ch = curl_init("https://api.telegram.org/TELEGRAM-BOT-TOKEN-HERE/sendMessage?chat_id=" . $chatID . "&text=" . trim(preg_replace('/\s+/', ' ', $msg)) . "&parse_mode=Markdown&disable_web_page_preview=true");
              curl_setopt($ch, CURLOPT_POST, 1);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
              curl_exec($ch);
              curl_close ($ch);
          }
        }
        catch(Exception $ex)
        {
            // log exception
            \Drupal::logger('hook_post_action')->info("[telegram] Error: " . $ex->getMessage());
        }
    }
}

Obviously, you need to have a Telegram channel (or your Telegram ID) to send notifications to, and you need to have a Telegram bot (knowing his token is enough, you don’t need to implement the whole bot). And of course, you need to add the bot as administrator to your channel or start a chat with it.

You can get notifications about comments too - just delete the condition about entity_type. Or, if you want, you can send notifications about new comments to other chat, for example. Also note, that condition $op == "update" will trigger not only for drafts being published, but for any changes of already published posts as well, so you need to find a way how to handle that. I just wanted to check possibility of integrating Telegram to Drupal and I did everything fast and dirty.

If you want other post’s stuff, not only title, check the documentation about class Node. You may also find some useful variables in Globals.

And here’s all my CMS plugins for Telegram integration.