通过Pushover将Drupal网站的活动推送到手机

本文介绍了如何集成Pushover应用程序与Drupal网站,以便在网站发生特定事件时,如匿名用户发表评论或管理员登录,实时发送手机通知。文章详细阐述了设置Pushover账户、创建自定义Drupal模块和实现相关钩子的过程。
摘要由CSDN通过智能技术生成

In this article I am going to show you how you can integrate Pushover with your Drupal site. I will illustrate a couple of examples of how you can use Pushover to notify yourself as soon as something happens on your site.

在本文中,我将向您展示如何将Pushover与Drupal网站集成。 我将举例说明几个示例,说明一旦网站上发生问题,您如何使用Pushover通知自己。

The code I write in this article is also available in this repository so you can just clone that if you want to follow along.

我在本文中编写的代码也可以在此存储库中找到,因此如果您想继续,可以克隆它们。

alt

什么是Pushover? (What is Pushover?)

Pushover is a web and mobile application that allows you to get real time notifications on your mobile device. The way it works is that you install an app on your Android or Apple device and using a handy API you can send that app notifications. The great thing about this is that it happens more or less in real time (depending on your internet connection) as Pushover uses the Google and Apple servers to send the notifications.

Pushover是一个Web和移动应用程序,可让您在移动设备上获取实时通知。 它的工作方式是在Android或Apple设备上安装应用程序,然后使用便捷的API可以发送该应用程序通知。 这样做的好处是,随着Pushover使用Google和Apple服务器发送通知,它或多或少地实时发生(取决于您的Internet连接)。

The price is also very affordable. At a rate of $4.99 USD per platform (Android, Apple or desktop) paid only once, you can use it on any number of devices under that platform. And you also get a 5 day trial period for free the moment you create your account.

价格也很实惠。 每个平台(Android,Apple或台式机)仅需支付一次$ 4.99美元的费率,即可在该平台下的任何设备上使用它。 创建帐户后,您还可以免费获得5天的试用期。

我在这是要干嘛? (What am I doing here?)

In this article I am going to set up a Pushover application and use it from my Drupal site to notify my phone of various events. I will give you two example use cases that Pushover can be handy with:

在本文中,我将设置一个Pushover应用程序,并从我的Drupal网站使用它来通知我的电话各种事件。 我将为您提供两个可以方便使用Pushover的用例示例:

  • Whenever an anonymous user posts a comment that awaits administrative approval, I’ll send a notification to my phone

    每当匿名用户发表评论等待行政批准时,我都会向手机发送通知
  • Whenever the admin user 1 logs into the site, I’ll send an emergency notification to my phone (useful if you are the only user of that admin account).

    每当管理员用户1登录该站点时,我都会向手机发送紧急通知(如果您是该管理员帐户的唯一用户,则将很有用)。

Naturally, these are examples and you may not find them useful. But they only serve as illustration of the power you can have by using Pushover.

当然,这些只是示例,您可能不会发现它们有用。 但是它们仅是使用Pushover可以提供的功能的说明。

推入帐户 (Pushover account)

First, a quick look at creating your Pushover account. To follow along, go on over to Pushover and sign up if you haven’t already and you can start your 5 day free trial. Then, go to Google Play or the App Store and install the app on your device. You’ll need to log in to your account and give the device a name. Mine is called simply Nexus (hint: I don’t have an iPhone).

首先,快速浏览一下创建您的Pushover帐户。 要继续进行下去,请继续进行Pushover并注册(如果尚未注册),然后可以开始5天免费试用。 然后,转到Google PlayApp Store并在您的设备上安装该应用。 您需要登录到您的帐户并为设备命名。 我的简称为Nexus (提示:我没有iPhone)。

Go back then to the Pushover website and you can already test it out by sending yourself a test notification to one or all of your active devices. You can even specify which sound it should make.

然后返回Pushover网站,您已经可以通过向一个或所有活动设备发送测试通知自己来对其进行测试。 您甚至可以指定应该发出的声音。

Next, if you want to use the API, you’ll need to create an application. This will generate for you an app_token to use later on. And that should be pretty much it.

接下来,如果要使用API​​,则需要创建一个应用程序 。 这将为您生成一个app_token以供以后使用。 那应该差不多了。

Drupal (Drupal)

Now that the Pushover account creation is taken care of, the device app is installed (Android in my case) and I have my Pushover application, it’s time to see how I can achieve the goal set out in the beginning. As a brief roadmap, I will do the following:

现在已经完成了创建Pushover帐户的工作,已经安装了设备应用程序(在我的情况下为Android),并且我有我的Pushover应用程序,现在该看看如何实现开始提出的目标了。 作为一个简短的路线图,我将执行以下操作:

  • Create a custom Drupal module

    创建一个自定义的Drupal模块
  • Add to it the Pushover class created by Chris Schalenborgh (a handy wrapper over the curl calls to the API)

    将Chris Schalenborgh创建的Pushover类添加到其中(方便地包装对API的curl调用)

  • Implement some hooks that will trigger the notifications based on certain conditions

    实现一些挂钩,这些挂钩将根据特定条件触发通知
  • Profit

    利润

The custom module I’ll be working with in this example is called pushover and it contains a pushover.info and a pushover.module file (as required). Additionally, I will create a lib/Pushover folder in it to store the external class I will use to connect to Pushover. There are other – more recommended ways – of importing external libraries into Drupal modules (see the Libraries API), but for the sake of brevity, this will work just fine.

在此示例中,我将使用的自定义模块称为pushover ,其中包含pushover.infopushover.module文件(根据需要)。 此外,我将在其中创建一个lib/Pushover文件夹,以存储将用于连接到Pushover的外部类。 还有其他(建议使用的其他方式)将外部库导入Drupal模块(请参阅Libraries API ),但是为了简洁起见,这很好用。

The first thing I want to do in my pushover.module file is to import this external class. Based on my folder structure, I can do so with this line:

我要在pushover.module文件中做的第一件事是导入此外部类。 根据我的文件夹结构,我可以使用以下代码行:

require_once(DRUPAL_ROOT . '/' . drupal_get_path('module', 'pushover') . '/lib/Pushover/Pushover.php');

Next, I want to create a reusable helper function that will return a pushable object. That is an object already populated with my own defaults (such as credentials) and that takes some parameters for the more common properties. But first, I want to put my Pushover account credentials into the settings.php file because they do not belong in my git repository:

接下来,我想创建一个可重用的辅助函数,该函数将返回一个可推送对象。 那是一个已经使用我自己的默认值(例如凭据)填充的对象,并且为更常见的属性采用了一些参数。 但是首先,我想将我的Pushover帐户凭据放入settings.php文件中,因为它们不属于我的git存储库:

$conf['pushover_credentials'] = array(
  'user_token' => 'uCpygdjfsndfi7233sdasdo33Yv',
  'app_token' => 'aKH8Nwsdasdanl342jmsdaBWgoVe',
);

Obviously neither of these tokens are now valid but if you are following along, you should replace them with yours: the user_token you get on the main page as you log in to the Pushover website and the app_token is the one generated for your application.

显然,没有这些标记的现在是有效的,但如果你是以下沿,你应该用你替换他们: user_token你当你登录到网站推倒和主页上app_token是应用程序生成的一个。

Then I can continue with my helper function I mentioned earlier:

然后,我可以继续前面提到的辅助函数:

/**
 * Helper function that returns a pushable object using the Pushover class
 * 
 * @param $vars
 * @return bool|Pushover
 */
function pushover_get_pushable($vars) {
  global $conf;
  if (isset($conf['pushover_credentials'])) {
    $push = new Pushover();
    $push->setToken($conf['pushover_credentials']['app_token']);
    $push->setUser($conf['pushover_credentials']['user_token']);
    $push->setTitle($vars['title']);
    $push->setMessage($vars['message']);
    if (isset($vars['url'])) {
      $push->setUrl($vars['url']);
    }
    if (isset($vars['device'])) {
      $push->setDevice($vars['device']);
    }
    $push->setTimestamp(time());

    return $push;
  }
  else {
    return FALSE;
  }
}

In this function I instantiate a new Pushover object if there are credentials in my settings.php file. Otherwise, I fail silently by returning false. The function takes some parameters that are set on the object: title and message are mandatory whereas the url and device are not. The device is actually the name of the device to which you want to restrict this notification.

如果我的settings.php文件中有凭据,则在此函数中实例化一个新的Pushover对象。 否则,我会通过返回false静默失败。 该函数采用在对象上设置的一些参数:标题和消息是必需的,而URL和设备不是必需的。 该设备实际上是您想要将此通知限制到的设备的名称。

Additionally, I set the current timestamp and then return the object.

此外,我设置了当前时间戳,然后返回该对象。

Next, it’s time to use this function inside some hooks. The first one is going to be hook_comment_insert():

接下来,是时候在某些挂钩中使用此功能了。 第一个将是hook_comment_insert()

/**
 * Implements hook_comment_insert().
 */
function pushover_comment_insert($comment) {

  // Send a push notification if a new comment is created by an anonymous user
  // and it is not yet published.
  if ($comment->status == 0 && $comment->is_anonymous == TRUE) {
    global $base_url;
    $vars = array(
      'title' => 'New comment on ' . variable_get('site_name') . '!',
      'message' => 'Subject: ' . $comment->subject,
      'url' => $base_url . '/node/' . $comment->nid . '#comment-' . $comment->cid,
      'device' => 'Nexus'
    );
    $pushable = pushover_get_pushable($vars);
    if ($pushable) {
      $pushed = $pushable->send();
      if ($pushed == false) {
        watchdog('Pushover', t('A comment has been created but there was an error pushing that over.'), array(), WATCHDOG_ERROR, NULL);
      }
    }
  }
}

In here I check if the commenter is anonymous and the status is 0 (to be on the safe side). If that’s the case, I build the array of parameters for my helper function with some information about the site and comment and use the send() method to send the notification. You’ll notice that I restricted this to the Nexus device.

在这里,我检查评论者是否为匿名,状态为0(为了安全起见)。 如果是这种情况,我将使用有关站点和注释的一些信息来为辅助函数构建参数数组,并使用send()方法发送通知。 您会注意到,我将其限制为Nexus设备。

At the end, I check whether the notification went out successfully (the send() method returns false if the Pushover service does not return the success status code of 1. If something went wrong, I quickly log it to the watchdog.

最后,我检查通知是否成功send()出去(如果Pushover服务未返回成功状态代码1send()方法返回false。如果出现问题,我将其快速记录到看门狗中。

So now if an anonymous user writes a comment, I get a push notification with the site name, comment subject and URL. Nifty.

因此,现在,如果匿名用户发表评论,我将收到带有网站名称,评论主题和URL的推送通知。 好漂亮

alt

Now let’s turn to the second example in which I implement an emergency notification if my admin user logs into the site. If it’s not me, I’ll know something is wrong and I probably got hacked. I do this inside a hook_user_login() implementation:

现在转到第二个示例,在该示例中,如果我的管理员用户登录到站点,则实施紧急通知。 如果不是我,我会知道出了点问题,并且我很可能被黑了。 我在hook_user_login()实现中执行此操作:

/**
 * Implements hook_user_login().
 */
function pushover_user_login(&$edit, $account) {
  // If the admin user logs in, send a push notification.
  if ($account->uid == 1) {
    $whitelist = array('1.1.1.1');
    if (!in_array(ip_address(), $whitelist)) {
      global $base_url;
      $vars = array(
        'title' => 'Admin user sign in',
        'message' => 'Admin user has logged into this site: ' . variable_get('site_name') . '!',
        'url' => $base_url,
      );
      $pushable = pushover_get_pushable($vars);
      if ($pushable) {
        $pushable->setPriority(2);
        $pushable->setRetry(30);
        $pushable->setExpire(60);
        $pushed = $pushable->send();
        if ($pushed == false) {
          watchdog('Pushover', t('An admin user has logged into the site but there was an error pushing this over.'), array(), WATCHDOG_ERROR, NULL);
        }
      }
    }
  }
}

In here, I first check if the user logging in is the one with the id of 1 (the main admin user). Then I create an array with whitelisted IPs to check against the user logging in. I don’t want to get notified if I log in from home or from the office (1.1.1.1 is just an example ip address).

在这里,我首先检查登录的用户是否是ID为1的用户(主要管理员用户)。 然后,我创建一个具有列入白名单的IP的数组,以检查用户的登录情况。如果我是在家中或办公室登录,我都不会收到通知( 1.1.1.1只是一个示例IP地址)。

Then just like before, I get my pushable object with the usual variables (no device this time, I want this to go out to all my devices). On top of those, I set a priority of 2 (marking it an emergency notification), a retry value of 30 seconds and an expire value of 60 seconds. The latter 2 in combination with the priority make it so that if left unacknowledged by my phone, the notification gets resent every 30 seconds for a total duration of 60 seconds. For more information about the possible options you have with Pushover, make sure you check out their API docs.

然后,就像以前一样,我得到了带有普通变量的可推入对象(这次没有设备,我希望这可以应用于所有设备)。 最重要的是,我将优先级设置为2(将其标记为紧急通知),重试值为30秒,到期值为60秒。 后2个与优先级结合使用,因此,如果我的手机未对其进行确认,该通知将每30秒重新发送一次,总持续时间为60秒。 有关Pushover可能使用的选项的更多信息,请确保查看其API文档

And there it is. I will now get an emergency notification if someone logs in with my admin account. Of course, not very good if many people can log in with that account, but you get the point.

在那里。 如果有人使用我的管理员帐户登录,我现在将收到紧急通知。 当然,如果许多人可以使用该帐户登录不是很好,但是您明白了。

结论 (Conclusion)

In this tutorial I showed you how you can use Pushover from your Drupal site to send notifications to your phone when certain events occur. I covered 2 examples but I’m sure you can find more. I would like to also mention that I found a contrib Drupal module called Pushover which uses Rules in order to send out Pushover notifications. I haven’t really used it, but make sure to check it out if you want to use Pushover and your site is already making use of the Rules module. Or, you know, you hate writing code.

在本教程中,我向您展示了如何在某些事件发生时使用Drupal网站上的Pushover将通知发送到手机。 我介绍了2个示例,但我相信您可以找到更多示例。 我还要提及的是,我找到了一个名为Pushover的contrib Drupal模块,该模块使用Rules来发送Pushover通知。 我还没有真正使用过它,但是如果您要使用Pushover并且您的站点已经在使用Rules模块,请确保将其签出。 或者,您知道,您讨厌编写代码。

翻译自: https://www.sitepoint.com/push-drupal-sites-events-phone-pushover/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值