"""Module handling IFTTT notifications.""" from typing import List import os import requests class Notifier: """A notifier object that can send IFTTT notifications.""" # (positive, negative) _EVENTS = { "backup": ( "Backup for {name} succeeded.", "Backup for {name} failed.", ), "restore": ( "{name} successfully restored.", "Couldn't restore {name}.", ), } """The message content for a given event.""" # Placeholder def __init__( self, title: str, events: List[str], endpoint: str, api_key: str = None ): """Initialize a new Notifier object. Args: title: the notification title to use events: the event types that should trigger a notification (should be one of the keys in _EVENTS). endpoint: IFTTT endpoint name api_key: your IFTTT API key. If not provided, it will be read from the IFTTT_API_KEY environment variable. Todo: * Read the API key on init """ self.title = title self.events = events self.endpoint = endpoint self.api_key = api_key def notify(self, category: str, name: str, status_code: int): """Send an IFTTT notification. Args: category: type of notify (should be one of the keys in _EVENTS). Only if the category was passed during initialization will the notification be sent. name: name of the spec status_code: exit code of the command """ event = "{}_{}".format( category, "success" if status_code == 0 else "failure" ) # stop if it's not a valid event if event not in self._EVENTS: return api_key = self.api_key or os.environ["IFTTT_API_KEY"] # Can't do anything without a key if not api_key: return url = " https://maker.ifttt.com/trigger/{}/with/key/{}".format( self.endpoint, api_key ) data = { "value1": self.title, "value2": self._EVENTS[event][int(status_code != 0)], } requests.post(url, data=data)