Skip to content

Commit

Permalink
[Pushbullet]: Modernize service plugin
Browse files Browse the repository at this point in the history
- Use Python 3
- Remove external dependencies
- Use named-parameter configuration style
  • Loading branch information
amotl committed May 23, 2023
1 parent 288392f commit 93d65bf
Show file tree
Hide file tree
Showing 5 changed files with 417 additions and 26 deletions.
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ in progress

- Fix sending ntfy notifications with longer messages than 76 characters.
Thanks, @codebude.
- Modernize Pushbullet service plugin. Thanks, @DNicholai.


2023-05-15 0.34.1
Expand Down
40 changes: 30 additions & 10 deletions docs/notifier-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2287,13 +2287,15 @@ targets = {

### `pushbullet`

This service is for [PushBullet], an app for Android along with an extension for
This service is for [Pushbullet], an app for Android along with an extension for
Chrome and Firefox, which allows notes, links, pictures, addresses and files to be
sent between devices. It is based on the [PushbulletPythonLibrary] package.
sent between devices.

You can get your API key from the [Pushbullet account page] after signing up, see
also [Pushbullet » Getting an access token].

You can get your API key from the [PushBullet account page] after signing up.
You will also need the device ID to push the notifications to. To obtain this,
you will need to follow the instructions at [pyPushBullet], by running
you can, for example, follow the instructions at [pyPushBullet], by running
```shell
./pushbullet_cmd.py YOUR_API_KEY_HERE getdevices
```
Expand All @@ -2302,24 +2304,38 @@ The configuration layout looks like this.
```ini
[config:pushbullet]
targets = {
# API KEY device ID recipient_type
'warnme' : [ 'xxxxxxxxxxxxxxxxxxxxxxx', 'yyyyyy', 'tttt' ]
"warnme" : {
"access_token": "a6FJVAA0LVJKrT8k",
"recipient": "[email protected]",
"recipient_type": "email",
},
"alertme" : {
"access_token": "a6FJVAA0LVJKrT8k",
"recipient": "ujpah72o0sjAoRtnM0jc",
},
}
```

The optional _recipient_type_ could be one of `device_iden` (default), `email`, `channel` or `client`.
The optional _recipient_type_ could be one of `device` (default), `email`, `channel`
or `client`. See also [Pushbullet target parameters].

| Topic option | M/O | Description |
| ------------- | :----: |-----------------------------------------|
| `title` | O | application title (default: `mqttwarn`) |

![Pushbullet](assets/pushbullet.jpg)

[PushBullet]: https://www.pushbullet.com
[PushBullet account page]: https://www.pushbullet.com/#settings/account
[PushbulletPythonLibrary]: https://pypi.org/project/PushbulletPythonLibrary/
[Pushbullet]: https://www.pushbullet.com
[Pushbullet account page]: https://www.pushbullet.com/#settings/account
[Pushbullet target parameters]: https://docs.pushbullet.com/#target-parameters
[Pushbullet » Getting an access token]: https://docs.pushbullet.com/#getting-an-access-token
[pyPushBullet]: https://github.com/Azelphur/pyPushBullet

:::{note}
The client currently only implements sending message with `type=note`. If you have a
need to submit files or links, please let us know on the [mqttwarn issue tracker].
:::


### `pushover`

Expand Down Expand Up @@ -3241,3 +3257,7 @@ For another scenario using the `zabbix` plugin, please refer to the [Zabbix IoT
[Zabbix low-level discovery]: https://www.zabbix.com/documentation/current/en/manual/discovery/low_level_discovery
[Zabbix meets MQTT]: http://jpmens.net/2014/05/27/zabbix-meets-mqtt/
[Zabbix trapper]: https://www.zabbix.com/documentation/current/en/manual/config/items/itemtypes/trapper



[mqttwarn issue tracker]: https://github.com/mqtt-tools/mqttwarn/issues
70 changes: 55 additions & 15 deletions mqttwarn/services/pushbullet.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,74 @@
__copyright__ = 'Copyright 2014 Jan-Piet Mens'
__license__ = 'Eclipse Public License - v 1.0 (http://www.eclipse.org/legal/epl-v10.html)'

from pushbullet.pushbullet import PushBullet
import requests


def plugin(srv, item):
''' expects (apikey, device_id) in adddrs '''
"""
mqttwarn service for Pushbullet notifications.
"""

srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

recipient_type = "device_iden"
try:
apikey, device_id = item.addrs
except:
# Decode target address descriptor.
if isinstance(item.addrs, list):
try:
apikey, device_id, recipient_type = item.addrs
apikey, device_id = item.addrs
options = {"access_token": apikey, "recipient": device_id}
except:
srv.logging.warn("pushbullet target is incorrectly configured")
return False
try:
apikey, device_id, recipient_type = item.addrs
options = {"access_token": apikey, "recipient": device_id, "recipient_type": recipient_type}
except:
raise ValueError("Pushbullet target is incorrectly configured")
elif isinstance(item.addrs, dict):
options = item.addrs
else:
raise ValueError(f"Unknown target address descriptor type: {type(item.addrs).__name__}")

# Assemble keyword arguments for `send_note` function.
text = item.message
title = item.get('title', srv.SCRIPTNAME)
options.update({"title": title, "body": text})

try:
srv.logging.debug("Sending pushbullet notification to %s..." % (item.target))
pb = PushBullet(apikey)
pb.pushNote(device_id, title, text, recipient_type)
srv.logging.debug("Successfully sent pushbullet notification")
except Exception as e:
srv.logging.warning("Cannot notify pushbullet: %s" % e)
srv.logging.debug(f"Sending Pushbullet notification to {item.target}")
send_note(**options)
srv.logging.debug("Successfully sent Pushbullet notification")
except Exception:
srv.logging.exception("Sending Pushbullet notification failed")
return False

return True


def send_note(access_token, title, body, recipient, recipient_type="device"):
"""
Send a Pushbullet message with type=note.
https://docs.pushbullet.com/#push
"""
headers = {
"Access-Token": access_token,
"Content-Type": "application/json",
"User-Agent": "mqttwarn",
}
data = {"type": "note", "title": title, "body": body}
if recipient_type is None:
pass
elif recipient_type == "device":
data["device_iden"] = recipient
elif recipient_type == "email":
data["email"] = recipient
elif recipient_type == "channel":
data["channel_tag"] = recipient
elif recipient_type == "client":
data["client_iden"] = recipient
else:
raise ValueError(f"Unknown recipient type: {recipient_type}")

response = requests.post("https://api.pushbullet.com/v2/pushes", headers=headers, json=data)
response.raise_for_status()

return response.status_code == requests.codes.ok
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@
"pyprowl>=3.0.1",
],
"pushbullet": [
"PushbulletPythonLibrary>=2.3",
# TODO: Upstream `send_note` utility function.
# "pushbullet-python<2",
],
"redispub": [
"redis>=2.10.6",
Expand Down
Loading

0 comments on commit 93d65bf

Please sign in to comment.