platypush/platypush/plugins/ifttt.py

70 lines
2.1 KiB
Python
Raw Normal View History

2018-07-23 02:49:53 +02:00
import requests
from platypush.plugins import Plugin, action
2019-12-30 19:04:13 +01:00
2018-07-23 02:49:53 +02:00
class IftttPlugin(Plugin):
"""
This plugin allows you to interact with the IFTTT maker API
<https://ifttt.com/maker_webhooks> to programmatically trigger your own
IFTTT hooks from Platypush - e.g. send a tweet or a Facebook post, create a
Todoist item or a Trello task, trigger events on your mobile device, or run
any action not natively supported by Platypush but available on your IFTTT
configuration.
Requires:
* **requests** (``pip install requests``)
2018-07-24 09:06:05 +02:00
An example::
2018-07-23 02:49:53 +02:00
2018-07-24 09:06:05 +02:00
# Trigger an IFTTT event named "at_home"
2018-07-23 02:49:53 +02:00
{
"type": "request",
2018-07-24 09:06:05 +02:00
"action": "ifttt.trigger_event",
2018-07-23 02:49:53 +02:00
"args": {
2018-07-24 09:06:05 +02:00
"event_name": "at_home"
2018-07-23 02:49:53 +02:00
}
}
"""
_base_url = 'https://maker.ifttt.com/trigger/{event_name}/with/key/{ifttt_key}'
2019-12-30 19:04:13 +01:00
def __init__(self, ifttt_key, **kwargs):
2018-07-23 02:49:53 +02:00
"""
2019-12-30 19:04:13 +01:00
:param ifttt_key: Your IFTTT Maker API key. Log in to IFTTT and get your key from
`here <https://ifttt.com/maker_webhooks>`_. Once you've got your key, you can start creating IFTTT rules
using the Webhooks channel.
2018-07-23 02:49:53 +02:00
:type ifttt_key: str
"""
2019-12-30 19:04:13 +01:00
super().__init__(**kwargs)
2018-07-23 02:49:53 +02:00
self.ifttt_key = ifttt_key
@action
def trigger_event(self, event_name, values=None):
"""
Send an event to your IFTTT account
:param event_name: Name of the event
:type event_name: str
2019-12-30 19:04:13 +01:00
:param values: Optional list of values to be passed to the event. By convention IFTTT names the values as
``value1,value2,...``.
2018-07-23 02:49:53 +02:00
:type values: list
"""
url = self._base_url.format(event_name=event_name, ifttt_key=self.ifttt_key)
if not values:
values = []
2019-12-30 19:04:13 +01:00
response = requests.post(url, json={'value{}'.format(i + 1): v
for (i, v) in enumerate(values)})
2018-07-23 02:49:53 +02:00
if not response.ok:
2019-12-30 19:04:13 +01:00
raise RuntimeError("IFTTT event '{}' error: {}: {}".format(
event_name, response.status_code, response.reason))
2018-07-23 02:49:53 +02:00
# vim:sw=4:ts=4:et: