notifiers

repository·main·Indexed 25 days ago

https://github.com/liiight/notifiers

A unified Python notification library providing a single interface for numerous third-party providers including Slack, Telegram, Pushover, Gmail, and Twilio. It features a CLI for terminal notifications, a custom logging handler (NotificationHandler) for the Python standard library, and support for configuration via environment variables. Version 1.3.6.

Tokens
16.4K
Snippets
45
Records
103
Agent score
82%

What's inside notifiers

  1. Overview of the notifiers interface

    main

    The notifiers library provides a common interface for many notification providers (including built-in ones like SMTP) with a minimal set of dependencies.

    Key interface characteristics:

    • Consistent Naming: While most provider-specific properties retain their original API names (e.g., api_key vs token), the message property is standardized across all notifiers and is handled internally.
    • Snake Case Normalization: The library normalizes request properties to snake case, converting them to the required format for the specific provider behind the scenes.
  2. Configure NotificationHandler with fallback notifiers

    main

    To ensure you receive notifications even if your primary provider fails, you can configure a fallback notifier in NotificationHandler.

    When a notifiers.exceptions.NotifierException occurs, the handler will attempt to send the notification via the specified fallback provider using the fallback_defaults dictionary. The handler respects the standard logging raiseExceptions flag to determine if the fallback should be triggered.

    from notifiers.logging import NotificationHandler
    
    fallback_defaults = {
        'host': 'http://localhost',
        'port': 80,
        'username': 'foo',
        'password': 'bar'
    }
    
    # If 'pushover' fails, it will attempt to send via 'email'
    hdlr = NotificationHandler('pushover', fallback='email', fallback_defaults=fallback_defaults)
  3. Register a custom provider as an entry point

    main

    To make your custom provider installable and discoverable by get_notifier, register it in your setup.py using the notifiers entry point group. The format is provider_name = module.path:ClassName.

    from setuptools import setup, find_packages
    
    setup(
        name="myproject",
        version="0.1.0",
        packages=find_packages(),
        install_requires=[
            "notifiers>=1.0.0"
        ],
        # Register your provider as an entry point
        entry_points={
            "notifiers": [
                "my_provider = myproject.provider:MyCustomProvider"
            ]
        },
        # ... other setup fields
    )
  4. Configure provider arguments via environment variables

    main

    You can replace any provider argument by setting an environment variable. The default naming convention is NOTIFIERS_[PROVIDER_NAME]_[ARGUMENT_NAME].

    For example, to set a Pushover token and user, use: export NOTIFIERS_PUSHOVER_TOKEN=FOO and export NOTIFIERS_PUSHOVER_USER=BAR.

    You can also set the MESSAGE argument via an environment variable.

    To use a custom prefix instead of NOTIFIERS_, pass the env_prefix argument to the notify method.

  5. Use NotificationHandler as a stdlib logging handler

    main

    You can log directly to a notifier by using the NotificationHandler from notifiers.logging as a standard Python logging handler. This allows you to receive notifications for specific log levels (e.g., ERROR) without modifying your application's core logic.

    To use it, instantiate NotificationHandler with the provider name and a defaults dictionary containing the provider's required arguments, then add it to your logger.

    import logging
    from notifiers.logging import NotificationHandler
    
    log = logging.getLogger(__name__)
    defaults = {
        'token': 'foo',
        'user': 'bar'
    }
    
    hdlr = NotificationHandler('pushover', defaults=defaults)
    hdlr.setLevel(logging.ERROR)
    
    log.addHandler(hdlr)
    log.error('And just like that, you get notified about all your errors!')
  6. Handle data and notification errors

    main

    Notifiers distinguishes between two types of errors:

    1. Data/Schema Errors: Raised immediately if the arguments provided do not match the provider's schema (e.g., missing required fields or invalid formats). These raise a notifiers.exceptions.BadArguments exception.
    2. Notification Errors: Occur when the data is valid according to the schema, but the underlying service returns an error (e.g., an invalid API token). These are captured in the Response object.

    By default, Response objects do not raise exceptions for notification errors. To handle them, you can:

    • Check the .ok property (returns False if there were errors).
    • Inspect the .errors list for error messages.
    • Call .raise_on_errors() on the response object to raise a notifiers.exceptions.NotificationError.
    • Pass raise_on_errors=True directly to the notification method.
  7. Install notifiers via pip

    main

    Install the notifiers package using pip. Python 3.6 or higher is required.

    To install the stable version:

    pip install notifiers

    To install from the master branch source:

    pip install https://github.com/notifiers/notifiers/master.zip

    To install the cutting edge develop branch (not recommended):

    pip install https://github.com/notifiers/notifiers/develop.zip
  8. Handle Python reserved words in notification data

    main

    When a notification provider requires a property name that is a Python reserved word (such as from), you can use one of two methods to pass the data to the notify method:

    1. Dictionary Unpacking: Construct a dictionary containing the reserved key and unpack it using **.
    2. Underscore Suffix: Use the reserved keyword followed by a trailing underscore (e.g., from_).
    # Method 1: Dictionary unpacking
    data = {
        'to': 'foo@bar.com',
        'from': 'bar@foo.com'
    }
    provider.notify(**data)
    
    # Method 2: Underscore suffix
    provider.notify(to='foo@bar.com', from_='bar@foo.com')
  9. Send emails using the Gmail notifier

    main

    The Gmail notifier allows you to send emails via Google's SMTP server. It is a specialized private use case of the notifiers.providers.email.SMTP provider.

    To use it, retrieve the notifier using get_notifier('gmail') and call .notify() with the required to and message arguments.

    from notifiers import get_notifier
    
    gmail = get_notifier('gmail')
    gmail.notify(to='email@addrees.foo', message='hi!')
  10. Install notifiers via Docker

    main

    You can use DockerHub to pull the notifiers image.

    To pull the stable image:

    docker pull liiight/notifiers

    To pull the cutting edge develop tag (not recommended):

    docker pull liiight/notifiers:develop

    Alternatively, you can build the image locally using the provided DockerFile.