Plugin Development
Introduction
Section titled “Introduction”Apprise plugins, also called services, are Python classes that inherit from NotifyBase. The fastest way to build a new one is to start from a working plugin that resembles your target integration, then adapt its URL shape, parsing, and send logic.
Exceptions
Section titled “Exceptions”Use Apprise exceptions so applications can handle failures consistently.
| Exception | Description |
|---|---|
AppriseException |
The base for every Apprise exception. Catch it to handle all Apprise errors together. |
AppriseImproperlyConfigured |
A required setting is missing or invalid. Use this for plugin constructor checks. |
ApprisePluginException |
The plugin failed for a reason unrelated to its settings. |
AppriseInvalidData |
Stored or received data cannot be used safely. |
AppriseDiskIOError |
A file or disk operation failed. It can also be caught as OSError. |
Import exceptions from apprise.exception. Existing applications that catch TypeError, ValueError, or AttributeError remain compatible with AppriseImproperlyConfigured.
This pattern is ideal for:
- Writing to a local destination (stdout, file, syslog)
- Prototyping a URL schema before adding networking
from .base import NotifyBasefrom ..common import NotifyTypefrom ..locale import gettext_lazy as _
class NotifyDemo(NotifyBase): service_name = _("Apprise Demo Notification") protocol = "demo" setup_url = "https://appriseit.com/services/demo/"
# Disable throttling for a purely local plugin request_rate_per_sec = 0
templates = ( "{schema}://", )
def url(self, *args, **kwargs): params = self.url_parameters(*args, **kwargs) return "{schema}://?{params}".format( schema=self.protocol, params=self.urlencode(params), )
def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs): self.throttle() print(f"{notify_type} - {title} - {body}") return True
@staticmethod def parse_url(url): # demo:// has no host, so verify_host must be False return NotifyBase.parse_url(url, verify_host=False)This pattern is ideal for:
- Webhook-style integrations
- REST APIs with tokens and optional authentication
import jsonimport requests
from ..common import NotifyTypefrom ..exception import AppriseImproperlyConfiguredfrom ..utils import parse_boolfrom ..locale import gettext_lazy as _from .base import NotifyBase
class NotifyDemoHTTP(NotifyBase): service_name = _("Apprise Demo Notification") protocol = "demo" secure_protocol = "demos" setup_url = "https://appriseit.com/services/demo/"
templates = ( "{schema}://{host}/{apikey}", "{schema}://{host}:{port}/{apikey}", "{schema}://{user}@{host}/{apikey}", "{schema}://{user}@{host}:{port}/{apikey}", "{schema}://{user}:{password}@{host}/{apikey}", "{schema}://{user}:{password}@{host}:{port}/{apikey}", )
template_tokens = dict( NotifyBase.template_tokens, **{ "host": { "name": _("Hostname"), "type": "string", "required": True, }, "port": { "name": _("Port"), "type": "int", "min": 1, "max": 65535, }, "user": { "name": _("Username"), "type": "string", }, "password": { "name": _("Password"), "type": "string", "private": True, }, "apikey": { "name": _("API Key"), "type": "string", "private": True, }, }, )
def __init__(self, apikey, **kwargs): super().__init__(**kwargs)
self.apikey = apikey if not self.apikey: raise AppriseImproperlyConfigured( f"An invalid API key ({apikey}) was specified." )
@property def url_identifier(self): """A stable tuple used by url_id() and persistent storage.
It should uniquely identify the URL configuration so stored/cached data does not clobber different configurations.
Do not include: - targets (channels, recipients, endpoints) - most GET parameters, unless they fundamentally change upstream behaviour """ default_port = 443 if self.secure else 80 return ( self.secure_protocol if self.secure else self.protocol, self.user, self.password, self.host, self.port if self.port else default_port, str(self.apikey), )
def url(self, privacy=False, *args, **kwargs): params = self.url_parameters(privacy=privacy, *args, **kwargs)
# Determine Authentication auth = self.url_auth(privacy)
default_port = 443 if self.secure else 80 schema = self.secure_protocol if self.secure else self.protocol port = ( "" if self.port is None or self.port == default_port else f":{self.port}" )
return "{schema}://{auth}{hostname}{port}/{apikey}?{params}".format( schema=schema, auth=auth, hostname=self.host, port=port, apikey=self.quote(self.apikey, safe=""), params=self.urlencode(params), )
def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs): headers = { "User-Agent": self.app_id, "Content-Type": "application/json", "Authorization": f"Bearer {self.apikey}", }
payload = { "type": notify_type.value, "title": title, "body": body, }
self.throttle()
# prepare our port formatting port = f":{self.port}" if self.port else ""
try: r = requests.post( f"http://{self.host}{port}", data=json.dumps(payload), headers=headers, verify=self.verify_certificate, timeout=self.request_timeout, allow_redirects=self.redirects, ) if r.status_code < 200 or r.status_code >= 300: return False
except requests.RequestException: return False
return True
@staticmethod def parse_url(url): results = NotifyBase.parse_url(url) if not results: return results
try: results["apikey"] = NotifyDemoHTTP.split_path(results["fullpath"])[0] except IndexError: results["apikey"] = None
return resultsThis pattern is ideal for:
- Sending the same message to several rooms, numbers, or addresses
- Any service where one target can fail while the others succeed
import requests
from .base import NotifyBasefrom ..common import NotifyTypefrom ..locale import gettext_lazy as _from ..utils.parse import parse_list
class NotifyDemoTargets(NotifyBase): service_name = _("Apprise Demo Targets") secure_protocol = "demotargets" setup_url = "https://appriseit.com/services/demotargets/"
notify_url = "https://example.com/api/send"
templates = ( "{schema}://{token}/{targets}", )
template_tokens = dict( NotifyBase.template_tokens, **{ "token": { "name": _("Token"), "type": "string", "private": True, "required": True, }, "targets": { "name": _("Targets"), "type": "list:string", }, }, )
def __init__(self, token, targets=None, **kwargs): super().__init__(**kwargs) self.token = token self.targets = parse_list(targets)
def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs): has_error = False
for target in self.targets: # This target already got the message on an earlier attempt if self.is_delivered(target): continue
self.throttle() r = requests.post( self.notify_url, data={"to": target, "message": body}, headers={"Authorization": self.token}, verify=self.verify_certificate, timeout=self.request_timeout, allow_redirects=self.redirects, )
if r.status_code != requests.codes.ok: self.logger.warning("Failed to notify %s.", target) has_error = True continue
self.logger.info("Sent notification to %s.", target)
# Record it so a retry skips this target self.mark_delivered(target)
return not has_error
def url(self, privacy=False, *args, **kwargs): return "{schema}://{token}/{targets}?{params}".format( schema=self.secure_protocol, token=self.pprint(self.token, privacy, safe=""), targets="/".join( NotifyDemoTargets.quote(x, safe="") for x in self.targets ), params=NotifyDemoTargets.urlencode( self.url_parameters(privacy=privacy, *args, **kwargs) ), )
def __len__(self): return len(self.targets) if self.targets else 1
@staticmethod def parse_url(url): results = NotifyBase.parse_url(url, verify_host=False) if not results: return results
results["token"] = NotifyDemoTargets.unquote(results["host"]) results["targets"] = NotifyDemoTargets.split_path( results["fullpath"] ) return resultsCopy and paste this as a starting point. Search for TODO: and fill in the blanks.
## TODO: Rename this file and class.# TODO: Add unit tests and update documentation.#import refrom typing import Any
from ..common import NotifyTypefrom ..exception import AppriseImproperlyConfiguredfrom ..locale import gettext_lazy as _from ..url import PrivacyModefrom .base import NotifyBase
class NotifyMyService(NotifyBase): """TODO: One line summary of the service."""
# TODO: Update these 3 fields service_name = _("My Service") protocol = "myservice" secure_protocol = "myservices"
# TODO: Add a public service landing page when available service_url = "https://example.invalid/" setup_url = "https://appriseit.com/services/myservice/"
# TODO: Update with valid URL shapes users can type templates = ( "{schema}://{host}/{token}", "{schema}://{host}:{port}/{token}", "{schema}://{user}:{password}@{host}/{token}", "{schema}://{user}:{password}@{host}:{port}/{token}", )
# Tokens must map to __init__ arguments (directly or via map_to) template_tokens = dict(NotifyBase.template_tokens, **{ "token": { "name": _("Access Token"), "type": "string", "private": True, "required": True, # Optional validation, must be a 2-tuple: (pattern, flags) "regex": (r"^.+$", None), }, })
# Optional query string arguments. # If you define an argument here, it should be consumed in parse_url(). template_args = dict(NotifyBase.template_args, **{ "mode": { "name": _("Mode"), "type": "choice:string", "values": ("a", "b", "c"), "default": "a", }, "batch": { "name": _("Batch"), "type": "bool", "default": False, }, # Example alias, it must point to a real template_token or template_arg: "t": { "alias_of": "token", }, })
# Optional key/value injection patterns: # ?+Header=Value&-param=value&:extra=value template_kwargs = { "+": {"name": _("Header"), "prefix": "+"}, "-": {"name": _("GET Parameter"), "prefix": "-"}, ":": {"name": _("Payload Extra"), "prefix": ":"}, }
def __init__( self, token: str, mode: str | None = None, batch: bool | None = None, headers: dict[str, str] | None = None, params: dict[str, str] | None = None, payload: dict[str, str] | None = None, **kwargs: Any, ) -> None: super().__init__(**kwargs)
# TODO: Store required token(s) self.token = token if not self.token: raise AppriseImproperlyConfigured( _("An invalid access token was specified.") )
# TODO: Apply defaults using template_args where reasonable self.mode = ( self.template_args["mode"]["default"] if mode is None else str(mode).lower() ) if self.mode not in self.template_args["mode"]["values"]: raise AppriseImproperlyConfigured(_("Invalid mode specified."))
self.batch = ( self.template_args["batch"]["default"] if batch is None else parse_bool(batch) )
# TODO: Store any custom key/value injections self.headers = headers or {} self.params = params or {} self.payload = payload or {}
def __len__(self) -> int: """Return how many targets this plugin will notify.
If you do not override this, the base implementation returns 1. """ # TODO: If you support targets, return len(self.targets) or 1 return 1
@property def url_identifier(self) -> tuple[Any, ...]: """Return a tuple that uniquely identifies this URL configuration.
This powers persistent storage, caching, and stable url_id() values. Do not include: - targets (channels, recipients, endpoints) - most GET parameters """ default_port = 443 if self.secure else 80 return ( self.secure_protocol if self.secure else self.protocol, self.user, self.password, self.host, self.port if self.port else default_port, self.token, )
def url(self, privacy: bool = False, *args: Any, **kwargs: Any) -> str: """Return a URL that can recreate the same object.""" params: dict[str, Any] = { "mode": self.mode, "batch": "yes" if self.batch else "no", }
# Add common URL parameters (format, overflow, emojis, store, tz, verify, rto, cto, etc.) params.update(self.url_parameters(privacy=privacy, *args, **kwargs))
# Add key/value injections (optional) params.update({f"+{k}": v for k, v in self.headers.items()}) params.update({f"-{k}": v for k, v in self.params.items()}) params.update({f":{k}": v for k, v in self.payload.items()})
# Determine Authentication auth = self.url_auth(privacy)
default_port = 443 if self.secure else 80 schema = self.secure_protocol if self.secure else self.protocol port = ( "" if self.port is None or self.port == default_port else f":{self.port}" )
return "{schema}://{auth}{host}{port}/{token}?{params}".format( schema=schema, auth=auth, host=self.host, port=port, token=self.pprint(self.token, privacy, mode=PrivacyMode.Secret, safe=""), params=self.urlencode(params), )
def send( self, body: str, title: str = "", notify_type: NotifyType = NotifyType.INFO, **kwargs: Any, ) -> bool: """TODO: Implement the upstream call(s).""" self.throttle()
# TODO: Replace with a real implementation. For multiple targets, # use is_delivered()/mark_delivered() as shown above. self.logger.debug( "Sending %s notification to %s", notify_type, self.host ) return True
@staticmethod def parse_url(url: str) -> dict[str, Any] | None: """Parse a URL into __init__ arguments.
Guideline: - Every template_args entry should be extracted here - Return keys should match __init__ parameters """ results = NotifyBase.parse_url(url) if not results: return results
# token is the first path element try: results["token"] = NotifyMyService.split_path(results["fullpath"])[0] except IndexError: results["token"] = None
# Example: consume query string args qsd = results.get("qsd", {}) if "mode" in qsd: results["mode"] = NotifyMyService.unquote(qsd.get("mode"))
if "batch" in qsd: results["batch"] = parse_bool(qsd.get("batch"))
# We allow for 't=' as defined in our kwargs as a token # The general rule of thumb is kwargs trump everything - always # so even if a token is defined above, we'll over-ride it now if "t" in qsd: results["token"] = NotifyMyService.unquote(qsd.get("t"))
# Consume key/value injections, if you support them results["headers"] = { NotifyMyService.unquote(k): NotifyMyService.unquote(v) for k, v in results.get("qsd+", {}).items() } results["params"] = { NotifyMyService.unquote(k): NotifyMyService.unquote(v) for k, v in results.get("qsd-", {}).items() } results["payload"] = { NotifyMyService.unquote(k): NotifyMyService.unquote(v) for k, v in results.get("qsd:", {}).items() }
return resultsModel Overview
Section titled “Model Overview”URL Parsing
Section titled “URL Parsing”Apprise determines what the schema:// it has been provided and then launches the Notification Plugin’s YourPlugin.parse_url() call to do the rest.
Usually the first call made in your parse_url() function is to call the parent one (from NotifyBase). Doing so allows Apprise to extract further common URL parts such as schema, host, port, user, password, and fullpath. Your parse_url() should focus on the pieces that are specific to your service, then return a dict whose keys match your __init__() signature.
A key rule that the unit tests enforce is that your template metadata must map cleanly to __init__() arguments, either directly (same name) or through map_to.
Throttling, Verification, Redirects, and Timeouts
Section titled “Throttling, Verification, Redirects, and Timeouts”URLBase defines common SSL verification, redirect behaviour, and socket timeouts as URL arguments. Always pass the corresponding attributes into every requests.* call your plugin makes:
verifycontrolsverify_certificate– pass asverify=self.verify_certificateredirectcontrolsredirects– pass asallow_redirects=self.redirectsrtocontrols the socket read timeoutctocontrols the socket connect timeout
Basic Authentication
Section titled “Basic Authentication”When your service uses the URL’s user and password as HTTP Basic credentials, let URLBase handle both directions instead of building them yourself:
- Pass
auth=self.request_authinto eachrequests.*call. It isNonewhen the URL has no credentials. - In
url(), write them back withself.url_auth(privacy). It returns theuser:password@part, with the password hidden whenprivacy=True, or an empty string.
Both follow RFC 7617, where the user or the password may be empty:
| URL | Sent as Basic Auth | Written Back by url_auth() |
|---|---|---|
user:pass@host |
user:pass |
user:pass@ |
user@host |
user: |
user@ |
user:@host |
user: |
user@ |
:pass@host |
:pass |
:pass@ |
host |
nothing | an empty string |
def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs): r = requests.post( self.notify_url, data=payload, headers=headers, auth=self.request_auth, verify=self.verify_certificate, timeout=self.request_timeout, allow_redirects=self.redirects, )
def url(self, privacy=False, *args, **kwargs): params = self.url_parameters(privacy=privacy, *args, **kwargs)
return "{schema}://{auth}{host}/?{params}".format( schema=self.secure_protocol, auth=self.url_auth(privacy), host=self.host, params=self.urlencode(params), )Hiding Secrets in url()
Section titled “Hiding Secrets in url()”Every plugin’s url() method takes a privacy flag. When it is True, the URL is headed for a log or a screen, so passwords and tokens must be masked. Wrap each sensitive value in self.pprint() and pick a mode that decides how much of it stays visible:
| Mode | privacy=True Output for i-am-a-token |
Use It For |
|---|---|---|
PrivacyMode.Outer (default) |
i...n |
Tokens, API keys and webhook IDs. Enough is left to tell two of them apart. |
PrivacyMode.Tail |
...oken |
Values people recognize by their last digits, such as phone or account numbers. |
PrivacyMode.Secret |
**** |
Passwords. Nothing is shown, not even the length. |
With privacy=False, pprint() returns the value URL-encoded instead, the same as self.quote(). Pass safe="" for values that sit in the URL path so a / inside them is encoded too. An empty value comes back as an empty string in Outer and Tail mode, while Secret always returns ****.
from ..url import PrivacyMode
def url(self, privacy=False, *args, **kwargs): params = self.url_parameters(privacy=privacy, *args, **kwargs)
return "{schema}://{user}:{password}@{token}/?{params}".format( schema=self.secure_protocol, user=self.quote(self.user, safe=""), password=self.pprint( self.password, privacy, mode=PrivacyMode.Secret, safe="" ), token=self.pprint(self.token, privacy, safe=""), params=self.urlencode(params), )| Call | Result |
|---|---|
url() |
myservice://joe:pass123@abcdef1234/?... |
url(privacy=True) |
myservice://joe:****@a...4/?... |
When the user and password are Basic auth credentials, self.url_auth(privacy) already masks the password this way. See Basic Authentication.
Mark the same values with "private": True in template_tokens or template_args. That is what tells the URL Builder to hide them, and the unit tests check that nothing marked private shows up in the privacy URL.
Rate Limits
Section titled “Rate Limits”Fixed Delay
Section titled “Fixed Delay”Call self.throttle() right before every request your plugin makes. It sleeps just long enough that at least request_rate_per_sec seconds pass between two requests from the same plugin instance.
class NotifyMyService(NotifyBase): # The vendor allows one request per second request_rate_per_sec = 1.0
def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs): # Always throttle before talking to the server self.throttle() r = requests.post(...)NotifyBase sets this to 1.0 second, which suits most online services. Always set it on your plugin to match the vendor’s documented limit, and set it to 0 for local plugins or for plugins that track the limit themselves (see below).
Delay That Depends on the Mode
Section titled “Delay That Depends on the Mode”When the right delay depends on where the plugin sends, make request_rate_per_sec a property, the same way body_maxlen can be one. ntfy does this: the public ntfy.sh service is shared by everyone and must not be flooded, while a private ntfy server belongs to the user.
class NotifyMyService(NotifyBase): @property def request_rate_per_sec(self) -> float: """Seconds to wait between requests for the active mode.""" # Pace ourselves on the shared public service only return 1.0 if self.mode == MyServiceMode.CLOUD else 0.0self.throttle() reads the value before every request, so the property can use anything __init__() has set, such as self.mode or self.host.
self.throttle(wait=10) sleeps for exactly 10 seconds instead of the usual interval. That is how a plugin waits out a limit the server told it about.
Server-Reported Limits
Section titled “Server-Reported Limits”Some services tell you how close you are to their limit, or how long to back off after you hit it. Plugins that read this use two instance attributes, set in __init__():
| Attribute | Type | Meaning |
|---|---|---|
ratelimit_remaining |
float |
How many more requests the server allows. 0 or less means the plugin is blocked until ratelimit_reset. |
ratelimit_reset |
datetime (UTC) |
When the server reopens the window. Stored without a timezone (.replace(tzinfo=None)). |
These are not built into NotifyBase. They are a shared convention, so reuse these names. Discord, Fluxer, Mastodon, Bluesky, Reddit, Revolt and Twitter all use them, in one of two styles:
The server sends X-RateLimit-Remaining and X-RateLimit-Reset (a Unix timestamp) on every response. The plugin copies them after each request, so it knows it is out of requests before it gets a 429.
from datetime import datetime, timedelta, timezone
class NotifyMyService(NotifyBase): # The server reports its limits, so skip the fixed delay request_rate_per_sec = 0
# Our clock and the server's may differ slightly; wait a bit longer clock_skew = timedelta(seconds=10)
def __init__(self, **kwargs): super().__init__(**kwargs)
# Not blocked yet self.ratelimit_reset = datetime.now(timezone.utc).replace(tzinfo=None) self.ratelimit_remaining = 1.0
def _send(self, payload, rate_limit=1): wait = None if self.ratelimit_remaining <= 0.0: now = datetime.now(timezone.utc).replace(tzinfo=None) if now < self.ratelimit_reset: wait = abs( (self.ratelimit_reset - now + self.clock_skew) .total_seconds() )
self.throttle(wait=wait)
r = requests.post(...)
try: # Remember what the server told us for the next request self.ratelimit_remaining = float( r.headers.get("X-RateLimit-Remaining") ) self.ratelimit_reset = datetime.fromtimestamp( int(r.headers.get("X-RateLimit-Reset")), timezone.utc ).replace(tzinfo=None)
except (TypeError, ValueError): # Headers missing or unreadable; keep the old values pass
if r.status_code == requests.codes.too_many_requests and rate_limit > 0: # Try once more. The check at the top now waits for the reset. return self._send(payload, rate_limit=rate_limit - 1)
# ...normal status handlingThe server says nothing until you hit the limit. Then it answers 429 with a Retry-After header holding the number of seconds to wait. The plugin blocks itself for that long, retries, and clears the block once a send succeeds.
from datetime import datetime, timedelta, timezone
class NotifyMyService(NotifyBase): # The server reports its limits, so skip the fixed delay request_rate_per_sec = 0
# Wait at least this long after a 429, even without Retry-After default_delay_sec = 1.0
def __init__(self, **kwargs): super().__init__(**kwargs)
# Not blocked yet self.ratelimit_reset = datetime.now(timezone.utc).replace(tzinfo=None) self.ratelimit_remaining = 1.0
def _send(self, payload, rate_limit=1): wait = None if self.ratelimit_remaining <= 0.0: now = datetime.now(timezone.utc).replace(tzinfo=None) if now >= self.ratelimit_reset: # The block has passed; clear it self.ratelimit_remaining = 1.0 else: wait = (self.ratelimit_reset - now).total_seconds()
self.throttle(wait=wait)
r = requests.post(...)
if r.status_code == requests.codes.too_many_requests: delay = self.default_delay_sec try: delay = float(r.headers.get("Retry-After")) except (TypeError, ValueError): pass
# Block ourselves until the server is ready again now = datetime.now(timezone.utc).replace(tzinfo=None) self.ratelimit_remaining = 0.0 self.ratelimit_reset = now + timedelta( seconds=max(self.default_delay_sec, delay) )
if rate_limit > 0: # The check at the top now waits out the delay return self._send(payload, rate_limit=rate_limit - 1)
return False
# ...normal status handlingBoth styles share a few rules:
- Set
request_rate_per_sec = 0, or the fixed delay is added on top of the server’s. - Retry a
429a limited number of times. Therate_limitcounter above allows one retry, so a server that keeps refusing cannot hold the plugin forever. - Close any open file handles (attachments) before calling
_send()again. - This retry is separate from the user’s
retry=URL option, which repeats a whole send after it fails.
Notification Images
Section titled “Notification Images”Apprise ships an icon for each notification type (info, success, warning and failure). Setting image_size tells Apprise which size your service should get. Leave it as None and your plugin never sends one.
| Value | Size |
|---|---|
NotifyImageSize.XY_32 |
32 x 32 |
NotifyImageSize.XY_72 |
72 x 72 |
NotifyImageSize.XY_128 |
128 x 128 |
NotifyImageSize.XY_256 |
256 x 256 |
Pick the size closest to what the service displays. Three helpers return the icon for a notification type:
| Helper | Returns | Use When |
|---|---|---|
self.image_url(notify_type) |
A public URL to the icon | The service downloads the image itself. |
self.image_path(notify_type) |
A path to the icon on local disk | A local library needs a file (desktop pop-ups). |
self.image_raw(notify_type) |
The icon as bytes |
You upload or embed the image yourself. |
Each one returns None when image_size is not set or the user turned images off in their AppriseAsset, so always check the result. Most plugins also offer an image= URL option (mapped to include_image) so a user can turn the icon off per URL:
from ..common import NotifyImageSize
class NotifyMyService(NotifyBase): image_size = NotifyImageSize.XY_256
def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs): payload = {"text": body}
image_url = self.image_url(notify_type) if self.include_image and image_url: payload["icon"] = image_urlurl_identifier
Section titled “url_identifier”The url_identifier property exists to uniquely identify one configuration from another so cached or persistent data does not clobber different configurations. It is also how Apprise generates a consistent, stable unique id from a URL.
- Include scheme or protocol, credentials, and upstream connection identity.
- Exclude targets (channels, recipients, endpoints).
- Exclude most GET parameters. Only include a GET parameter if it fundamentally changes how the upstream communication works.
If two URLs describe the same effective configuration, they should generate the same url_identifier, and therefore the same url_id().
Also note the storage switch:
- If
store=nois set,url_id()returnsNone, andurl()should preservestore=noin its output.
Example:
@propertydef url_identifier(self): return ( self.secure_protocol if self.secure else self.protocol, self.user, self.password, self.host, self.port if self.port else (443 if self.secure else 80), )Persistent storage opt-in (storage_mode)
Section titled “Persistent storage opt-in (storage_mode)”If your plugin performs repeated upstream lookups (OAuth tokens, discovery calls, resolved identifiers, capability checks), you should consider enabling persistent storage. It will save you from doing the check down the road and make your plugin that much faster!
To opt in, set a class-level storage_mode:
from apprise.common import PersistentStoreMode
class NotifyMyService(NotifyBase): # ... storage_mode = PersistentStoreMode.AUTOGuidance:
- Use
PersistentStoreMode.AUTOfor most plugins. - Use
PersistentStoreMode.FLUSHonly when the cached data is expensive to recompute and you want stronger durability. - Leave the default behaviour (memory-only) if your plugin should never persist state, or if caching provides little benefit.
When combined with a well-formed url_identifier (configuration identity only), multiple instances targeting different recipients can reuse the same cache for the same upstream configuration.
Targets and __len__
Section titled “Targets and __len__”__len__() allows authors and tooling to identify how many targets are loaded into a plugin.
- If you do not override it, the base implementation returns
1. - Override it in plugins that support multiple targets, usually returning
len(self.targets)with a minimum of1.
Delivering to More Than One Target
Section titled “Delivering to More Than One Target”If send() loops over several targets, record each successful target. A retry then contacts only the targets that failed.
for target in self.targets: if self.is_delivered(target): continue
if not self._post(target, body): has_error = True continue
self.mark_delivered(target)is_delivered() checks whether a target already received the message. Call mark_delivered() only after the target accepts it.
The key identifies the target, such as a phone number, room ID, token, or email address. Lists and dictionaries also work.
Notes:
- Both methods do nothing when
retry=0, which is the default. - Each piece of a split message is tracked on its own.
- A piece that
send()returnedTruefor is not sent again on a retry. Your own tracking only decides who receives a piece that partly failed. - Tracking is dropped when the notification finishes.
- Something sent once for the whole notification, such as an image, uses
per_message=Trueso it is not repeated for every piece:
image_key = ("image", target)if not self.is_delivered(image_key, per_message=True): if self.send_image(target): self.mark_delivered(image_key, per_message=True)- For batches, use a stable key such as
(category, batch_position)so each batch remains distinct. - If one target needs several requests, include the request position in the key and mark each request only after it succeeds.
- If you count successes, count a skipped target too:
if self.is_delivered(target): delivered += 1 continueOnly sending loops need this tracking. Loops that build a payload, split a message, or collect recipients for one request do not.
To share other values between attempts, see Carrying State Across Retries below.
Carrying State Across Retries
Section titled “Carrying State Across Retries”remember() and recall() share a value across one notification’s attempts. The value is discarded when the notification ends, so the next notification starts clean.
Use them for values a retry should reuse, such as a request ID, upload handle, or temporary token.
| Situation | Behaviour |
|---|---|
| Retries are enabled | Every attempt of this notification reads back what an earlier one remembered. |
| Retries are disabled | remember() keeps nothing and recall() returns its default. No later attempt would read it. |
An idempotency key prevents a service from acting twice. Reuse the original key when retrying a request that never returned.
from hashlib import sha256from json import dumpsfrom uuid import uuid4
data = dumps(payload)
# One notification can send several requests, so name this one toofingerprint = sha256(data.encode("utf-8")).hexdigest()
key = self.recall(fingerprint)if key is None: key = str(uuid4()) self.remember(fingerprint, key)
headers["Idempotency-Key"] = keyAnything expensive a retry should not redo, such as uploading a file before the message that references it.
def _media_id(self, attachment): """Upload once per notification rather than once per attempt."""
# per_message, because one upload serves every piece of a # split message media_id = self.recall(attachment.path, per_message=True) if media_id is None: media_id = self._upload(attachment) if media_id: self.remember(attachment.path, media_id, per_message=True)
return media_idUse remember() and recall() for shared retry state. Use is_delivered() and mark_delivered() to track which targets already accepted the notification.
def send(self, body, title="", notify_type=NotifyType.INFO, attach=None, **kwargs): """Upload once, then reach every target that is still waiting."""
has_error = False
# Uploaded on the first attempt and reused by the rest media_id = self._media_id(attach) if attach else None
for target in self.targets: # Accepted on an earlier attempt, so leave it alone if self.is_delivered(target): continue
if not self._post(target, body, media_id): has_error = True continue
self.mark_delivered(target)
return not has_errorNotes:
- Both methods are inert when retries are disabled, so the default
retry=0path costs nothing and needs no guard of your own. - Each split piece keeps its own value, even when its content matches another piece. Set
per_message=Trueonly for state shared by the whole notification, such as one uploaded file used by every piece. - When one notification makes several requests, use a distinct key for each request. A hash of the request body usually works well.
- Key types stay distinct, so
1,"1"and["1"]do not share state.
Requirements and Optional Dependencies
Section titled “Requirements and Optional Dependencies”If your plugin needs extra packages, declare them in requirements so Apprise can report what is required or recommended.
from ..locale import gettext_lazy as _
requirements = { "details": _("This plugin requires cryptography for message signing."), "packages_required": ["cryptography>=42"], "packages_recommended": ["orjson>=3"],}runtime_deps(): Memory Eviction Hint
Section titled “runtime_deps(): Memory Eviction Hint”If your plugin conditionally imports a heavy third-party library, also override runtime_deps() to tell the plugin manager which top-level package names it loaded.
class NotifyMyService(NotifyBase): # ...
@staticmethod def runtime_deps(): return ("mylibrary",)The return value is a tuple of importable top-level package names, the same string you would pass to import, not the pip install name (e.g. "paho" for paho-mqtt).
The Notification Manager tracks a reference count for each declared library. When every plugin that uses a given library is disabled and N_MGR.evict_on_disable is True, the manager removes that library, and all of its submodules, from sys.modules, releasing the associated Python objects from memory.
- Return the base-class default
()(an empty tuple) if your plugin has no optional runtime dependencies worth evicting. - Submodules are handled automatically; declare only the top-level name.
- This is separate from
requirements, which names pip packages for human-readable dependency reporting.runtime_deps()names importable packages for runtime memory management.
Plugin Base Defaults
Section titled “Plugin Base Defaults”The following identifies the default values of variables defined in your plugin automatically if not otherwise overridden.
URLBase Defaults
Section titled “URLBase Defaults”NotifyBase inherits from the URLBase object which sets these defaults:
| Attribute | Default | Purpose | When To Override |
|---|---|---|---|
request_rate_per_sec |
0 |
Base throttle interval (seconds). 0 disables throttling at the URLBase level. |
Typically override at NotifyBase or your plugin, not at URLBase. |
socket_connect_timeout |
4.0 |
Default connect timeout, used when cto is not provided. |
If your service routinely needs longer TCP handshakes. |
socket_read_timeout |
4.0 |
Default read timeout, used when rto is not provided. |
If your service returns slowly or streams responses. |
verify_certificate |
True |
SSL certificate verification, used when verify is not provided. |
Only if your service runs in controlled networks with self-signed certs and you are comfortable allowing verify=no. |
redirects |
True |
HTTP redirect following, used when redirect is not provided. Falls back to asset.http_redirects. |
Set to False on the asset to disable redirects globally if your environment requires it. |
templates |
() |
Documentation templates. | Almost always, so tooling and docs can describe the plugin accurately. |
template_tokens |
{} |
Metadata describing URL path tokens. | Almost always, for non-trivial schemas. |
template_args |
{ verify, redirect, rto, cto } |
Common URL args and their defaults. | Usually extend rather than replace. |
template_kwargs |
{} |
Metadata for prefixed key/value arguments. | If you support +headers, :payload, -params, etc. |
NotifyBase Defaults
Section titled “NotifyBase Defaults”Your plugin should be configured to inherit from NotifyBase granting you these defaults
| Attribute | Default | Purpose | When To Override |
|---|---|---|---|
enabled |
True |
If False, the plugin is not used. |
Disable for platform-specific or dependency-specific reasons. |
category |
"native" |
Classifies plugin origin (native vs custom). |
Usually leave as-is. |
requirements.details |
None |
Human-friendly requirements text. | If you need to explain optional or required packages. |
requirements.packages_required |
[] |
Required packages for full function. | If your plugin requires extra libraries. |
requirements.packages_recommended |
[] |
Optional packages that improve function. | If you can run without them, but benefit from them. |
service_url |
None |
Vendor or upstream product URL. | For public services, set this. |
setup_url |
None |
Apprise setup page for your service. | Set this to your appriseit.com/services/<service>/ page. |
request_rate_per_sec |
1.0 |
Default throttle interval (seconds). | Tune for vendor rate limits, or set to 0 for local-only. |
image_size |
None |
Size of the notification-type icon to send. None sends no icon. |
Set when your service can show an icon. See Notification Images. |
body_maxlen |
32768 |
Max body characters before truncation. | Set based on upstream constraints. |
title_maxlen |
250 |
Max title characters. Set 0 if titles are not supported. |
Set to 0 for title-less endpoints, or tune to vendor constraints. |
body_max_line_count |
0 |
Max number of lines to keep. 0 disables line truncation. |
If upstream is line-sensitive. |
persistent_storage |
True |
Allows the persistent store to be used. | If your plugin must never store identifiers or state. |
storage_mode |
memory |
Default persistent store mode. | Rare, but can be tuned for special behaviours. |
timezone |
None |
Uses server-detected timezone when None. |
If your service must always operate in a specific timezone. |
notify_format |
text |
Default message format(s); one value or an ordered tuple/list. | If your service is Markdown or HTML-first, or natively renders more than one format. |
overflow_mode |
upstream |
Default overflow strategy. | If you want Apprise to split, truncate, or alter overflow behaviour. |
interpret_emojis |
False |
Emoji interpretation. | If the upstream service benefits from emoji conversion. |
attachment_support |
False |
Attachment enablement. | Set to True if you accept attachments. |
default_html_tag_id |
"b" |
Used to inject title into body for title-less services. | Rare, unless you want different formatting. |
Templates and Metadata
Section titled “Templates and Metadata”Template Types
Section titled “Template Types”Apprise validates types using a strict pattern: ((choice|list):)?(string|bool|int|float|email).
| Type | Where used | Meaning | Required directives | Notes |
|---|---|---|---|---|
string |
tokens, args | A single string | none | Common for hostnames, tokens, and names. |
email |
tokens, args | A single email address | none | Use when url() preserves the address’s @ character. |
int |
tokens, args | A single integer | none | Use min and max to bound port values, counts, etc. |
float |
tokens, args | A single float | none | Use min and max for bounds. |
bool |
tokens, args | A boolean flag | default |
Boolean entries must provide a default. |
choice:string |
tokens, args | One value from a fixed set | values |
Choice entries must provide values, and default must be one of them if specified. |
choice:int |
tokens, args | One integer from a fixed set | values |
Use for mode selectors or enumerations. |
choice:float |
tokens, args | One float from a fixed set | values |
Rare, but supported. |
choice:email |
tokens, args | One email from a fixed set | values |
Preserve the selected address’s @ character. |
list:string |
tokens, args | A list of strings | delim |
List entries must provide delimiters. |
list:bool |
tokens, args | A list of boolean values | delim |
Use bool for a single boolean value. |
list:int |
tokens, args | A list of integers | delim |
Split and then coerce to int. |
list:float |
tokens, args | A list of floats | delim |
Split and then coerce to float. |
list:email |
tokens, args | A list of email addresses | delim |
Preserve each address’s @ character. |
Additional rules that matter:
choice:boolis not allowed, useboolinstead.regexmust be a 2-tuple(pattern, option), and patterns must start with^and end with$. |- If
requiredorprivateare not provided, they default toFalse. - If
valuesis a dictionary, it is converted to a list of keys.
Template layout patterns
Section titled “Template layout patterns”These examples focus only on how template metadata, __init__(), and parse_url() connect.
No tokens are required when the templates do not include custom {token} entries.
class MyPlugin(NotifyBase): ## Plugin variables here (intentionally omitted)
secure_protocol = "foobar"
templates = ("{schema}://",)
def __init__(self, *args, **kwargs): # Rest of code here super().__init__(*args, **kwargs)If you only use built-in tokens like host, port, user, and password, you can omit template_tokens. Those tokens are already known to the framework.
class MyPlugin(NotifyBase): ## Plugin variables here (intentionally omitted)
secure_protocol = "foobar"
templates = ("{schema}://",)
def __init__(self, host, *args, **kwargs): # Rest of code here super().__init__(host=host, *args, **kwargs)If you define a template_token, template_arg, or template_kwarg, you should handle it in parse_url(), because the dict returned from parse_url() is used to initialize the class.
import re
from apprise.utils import parse_bool # example helper
class MyPlugin(NotifyBase): ## Plugin variables here (intentionally omitted)
secure_protocol = "foobar"
templates = ("{schema}://{token}",)
template_tokens = dict( NotifyBase.template_tokens, **{ "token": { "name": _("Auth Token"), "type": "string", "private": True, "required": True, "regex": (r"^[a-z0-9]+$", "i"), }, }, )
template_args = dict( NotifyBase.template_args, **{ "image": { "name": _("Include Image"), "type": "bool", "default": True, "map_to": "include_image", }, }, )
def __init__(self, host, token, include_image, *args, **kwargs): # Rest of code here super().__init__(host=host, *args, **kwargs)
@staticmethod def parse_url(url): results = NotifyBase.parse_url(url, verify_host=False)
# Token is in the host position in this example results["token"] = MyPlugin.unquote(results["host"])
results["include_image"] = parse_bool(results["qsd"].get( "image", MyPlugin.template_args['image']['default']))
return resultsMultiple token names can map to the same __init__() argument using map_to. Tests ensure all map_to values are valid __init__() arguments (or one of the framework-recognized keywords).
import re
from apprise.utils import parse_bool # example helper
class MyPlugin(NotifyBase): ## Plugin variables here (intentionally omitted)
secure_protocol = "foobar"
templates = ("{schema}://{targets}",)
template_tokens = dict( NotifyBase.template_tokens, **{ "target_user": { "name": _("Target User"), "type": "string", "map_to": "targets", }, "target_stream": { "name": _("Target Stream"), "type": "string", "map_to": "targets", }, "targets": { "name": _("Targets"), "type": "list:string", "delim": ("/",), }, }, )
template_args = dict( NotifyBase.template_args, **{ "to": { "alias_of": "targets", }, }, )
def __init__(self, targets, *args, **kwargs): # Rest of code here super().__init__(*args, **kwargs)
@staticmethod def parse_url(url): results = NotifyBase.parse_url(url, verify_host=False)
# Store our targets results["targets"] = [MyPlugin.unquote(results["host"])] results["targets"].extend(MyPlugin.split_path(results["fullpath"]))
# Support an alias that is easier to express in YAML if "to" in results["qsd"] and len(results["qsd"]["to"]): results["targets"] += list( filter( bool, re.split(r"[ \t\r\n,#\\/]+", MyPlugin.unquote(results["qsd"]["to"])), ) )
return resultsTemplate directives Reference
Section titled “Template directives Reference”The unit tests enforce allowed keys and type constraints.
| Directive | Where used | Meaning |
|---|---|---|
name |
tokens, args, kwargs | Human-friendly label, usually wrapped in gettext_lazy(). |
type |
tokens, args | Value type, validated by the strict type regex. |
required |
tokens, args | Marks an entry as mandatory. If omitted, defaults to False. |
private |
tokens, args | Marks an entry as sensitive. If omitted, defaults to False. |
default |
args | Default used when the URL does not specify a value. Required for bool args. |
values |
choice types | Allowed values for choice types, required for any choice:* type. |
min, max |
int, float | Bounds for numeric types. |
regex |
tokens, args | Validation regex, always (pattern, option) with ^...$ anchoring. |
delim |
list types | Delimiters used for list splitting, required for list:* types. |
prefix |
kwargs | Required for kwargs, must be one of :, +, or -. |
map_to |
tokens, args, kwargs | Maps a key to a different __init__() argument name. Tests enforce it maps to a function argument (or a framework keyword). |
alias_of |
args, kwargs | Declares an alias for an existing token or arg, often used to make YAML configuration easier. |
group |
tokens | Used for grouping when multiple tokens map into a list-style entry. |
Framework-recognized map targets include common URL fields and shared arguments, even if they are not in your plugin __init__(), such as user, password, host, port, schema, fullpath, format, overflow, emojis, tz, verify, cto, rto, and store.
Mapping Rules
Section titled “Mapping Rules”Apprise uses your template metadata as a contract, and tests enforce consistency:
- Every item in
template_tokensmust map to a real__init__()argument, either directly (same key name) or usingmap_to. - Aliases (
alias_of) are allowed in args and kwargs, not in tokens. - Every
alias_ofmust point to a real token or arg, and cannot just point to itself unless it also exists in tokens. - For kwargs entries,
prefixis required, and must be one of:,+, or-.
alias_of Inheritance Rule
Section titled “alias_of Inheritance Rule”Alias entries must never redeclare properties that are inherited from the target. The following keys are forbidden on any entry that contains alias_of:
private, type, required, regex, default, min, max, map_to, prefix, group
These are resolved at runtime by following the alias chain. Consumers such as the URL Builder read them from the target, not from the alias itself. The only permitted extras alongside alias_of are:
| Extra key | When allowed |
|---|---|
name |
Required when alias_of lists multiple targets, to provide a grouping label for the UI. |
delim |
Allowed when the aliased target is a list:* type, to override the delimiter character(s). |
Valid approaches:
-
Single alias: only alias_of
"t": {"alias_of": "token"}, -
Multiple aliases: alias_of + name for grouping label
"tok": {"name": _("Token"),"alias_of": ("access_token", "token_a", "token_b"),}, -
List alias with delimiter override
"to": {"alias_of": "targets","delim": (",", " "),},
Additional tokens outside of what was identified above can not be used. For example, the following is not valid:
# do NOT redeclare inherited properties"t": { "alias_of": "token", "private": True, # <-- This should have been defined in what is being inherited},Round-Trip Requirements
Section titled “Round-Trip Requirements”Two functions should work together:
parse_url()should extract every argument you expose throughtemplate_argsandtemplate_kwargs.url()should emit a URL that can recreate the same object, and should generate the sameurl_identifierwhen re-instantiated.
Recipients that were refused
Section titled “Recipients that were refused”Some services send to the sender, source number or account owner when no recipients are given. If your plugin does this, keep three cases apart so a round trip through url() never changes who receives the message:
- No recipients given: send to the sender, as before.
- Recipients given, but every one refused: send to nobody. Keep each refused entry in
self.invalid_targetsand haveurl()write it back after the valid ones. On reload it is refused again, so the plugin still has nobody to send to. - Only separators given (such as
;or, ,): treat it as no recipients given. Decide the fallback on the parsed list, not on the raw input.
self.invalid_targets = []
# Parse first, so text holding only separators counts as none giventargets = parse_phone_no(targets)if not targets: targets = [self.source]
for target in targets: result = is_phone_no(target) if not result: self.logger.warning("Dropped invalid phone # (%s).", target) self.invalid_targets.append(target) continue
self.targets.append(result["full"])In url(), write self.targets + self.invalid_targets so the refused entries survive the round trip. If your send() falls back instead (for example self.targets or [self.source]), have it return False when every recipient was refused.
Template Schema Reference
Section titled “Template Schema Reference”This table documents the most common directives supported by template_tokens, template_args, and template_kwargs.
| Directive | Where used | Meaning |
|---|---|---|
name |
tokens, args, kwargs | Human-friendly label, usually wrapped in gettext_lazy(). |
type |
tokens, args | Value type: string, bool, int, float, email, choice:<type>, or list:<type>. |
required |
tokens, args | Marks an entry as mandatory for initialization or validation. |
default |
args | Default used when the URL does not specify a value. Required for bool types. |
private |
tokens, args | Marks a value as sensitive and should be hidden or masked in privacy views. |
regex |
tokens, args | A 2-tuple (pattern, flags) used to validate values. Patterns should be anchored with ^ and $. |
values |
choice types | Allowed values for choice:* types. If a default is provided, it must be in values. |
delim |
list types | Allowed delimiters for list:* types. |
prefix |
kwargs | Required for kwargs entries, defines injection prefix :, +, or -. |
map_to |
tokens, args, kwargs | Maps the directive key to a different __init__() argument name. |
alias_of |
args, kwargs | Provides an alternative name that behaves exactly like another token or argument. |
templates
Section titled “templates”- A tuple of URL patterns (strings) showing valid forms.
- Use
{schema}in templates, and keep tokens consistent across templates.
It is documentation and structured metadata that can be used by tooling to describe supported URL shapes.
template_tokens
Section titled “template_tokens”Variables taken from the URL core structure such:
schema://credentials/direction/?options= | | | variables here |template_args
Section titled “template_args”Args describe query string arguments. NotifyBase already provides format, overflow, emojis, store, and tz. URLBase already provides verify, rto, and cto.
Common patterns:
- Use
alias_ofto add synonyms. - Use
map_toto map user-facing arg names onto your__init__()parameter names. - Use a
defaultto clearly document behaviour.
template_kwargs
Section titled “template_kwargs”Kwargs are for prefixed arguments that can appear multiple times, typically used for key/value injection:
+is often used for headers-is often used for URL parameters:is often used for payload extras
Each template_kwargs entry requires a prefix and a name, and those are also surfaced in the URL Builder as a Custom Parameters table where users can add any number of key/value rows.
template_kwargs = dict( NotifyBase.template_kwargs, **{ "headers": { "name": _("HTTP Header"), "prefix": "+", }, "params": { "name": _("GET Parameter"), "prefix": "-", }, "payload": { "name": _("Payload Extra"), "prefix": ":", }, },)In a URL these look like: ?+X-Custom-Header=foo&-debug=1&:extra=bar
Requirements And Optional Dependencies
Section titled “Requirements And Optional Dependencies”If your plugin needs extra packages, declare them in requirements so Apprise can report what is required or recommended.
Example:
from ..locale import gettext_lazy as _
requirements = { "details": _("This plugin requires cryptography for message signing."), "packages_required": ["cryptography>=42"], "packages_recommended": ["orjson>=3"],}Attachment Support
Section titled “Attachment Support”Plugins that support file attachments must explicitly declare support by setting the following class attribute:
class NotifyExample(NotifyBase): attachment_support = TrueWhen enabled, attachments are provided to the plugin as a list of AppriseAttachment objects. These objects abstract file access and may be backed by local files, in-memory data, or remote HTTP resources.
Full details on attachment handling, lifecycle management, size limits, and common implementation patterns are documented here:
Authors are strongly encouraged to review the attachment documentation before implementing support, as incorrect handling can easily lead to excessive memory usage or failed deliveries.
URL Builder Integration
Section titled “URL Builder Integration”The Apprise URL Builder generates its form entirely from the metadata exported by your plugin. Well-formed metadata leads to a polished, user-friendly experience.
Checklist for URL Builder quality
Section titled “Checklist for URL Builder quality”| What to set | Why it matters |
|---|---|
service_name |
Shown as the service display name in search results. |
service_url |
Powers the “Service website” link next to the form. |
setup_url |
Powers the “Setup guide” link for step-by-step instructions. |
name on every token/arg |
Appears as the form field label. Without it the raw key name is shown. |
private: True on secrets |
Renders the field as a password input with a reveal toggle, and prevents the value from leaking into the browser address bar. |
required: True on mandatory tokens |
Marks fields with an asterisk (*) and blocks URL generation until filled. |
regex on validated tokens |
Provides client-side format hints (not enforced in the browser, but surfaced in schema metadata). |
default on optional args |
Shown as the placeholder in dropdowns and number inputs. |
templates ordered simple to complex |
The URL Builder defaults to the most complex template so all fields are visible from the start. |
template ordering
Section titled “template ordering”The URL Builder picks the most complex template by default (the one with the most {token} slots). As the user fills fields it switches to the simplest template that covers every filled token.
Order your templates tuple from simplest to most complex:
templates = ( "{schema}://{token}", # simplest, no targets "{schema}://{token}/{targets}", # adds optional targets "{schema}://{botname}@{token}/{targets}", # most complex)private flag matters
Section titled “private flag matters”Mark every API key, token, password, or secret with "private": True in both template_tokens and template_args. The URL Builder:
- Renders the input as a password field with an eye-toggle button.
- Shows
••••••in the assembled URL display instead of the real value. - Excludes the value from the browser address bar (share links never expose secrets).
Alias entries (alias_of) inherit the private flag from their target. Do not redeclare it on the alias.
service_url vs setup_url
Section titled “service_url vs setup_url”| Attribute | Purpose |
|---|---|
service_url |
Links to the upstream vendor or product landing page (e.g. https://discord.com/). Shown in the URL Builder as “Service website”. |
setup_url |
Links to the Apprise-specific integration guide on appriseit.com (e.g. https://appriseit.com/services/discord/). Shown as “Setup guide”. You can create or update this documentation in the Apprise documentation repository. |
Both should always be set. Generic or local-only plugins (e.g. MQTT, Windows notifications) may omit service_url if there is no applicable upstream URL.
Format and Overflow
Section titled “Format and Overflow”NotifyBase supplies shared URL options such as format, overflow, emojis, and persistent storage (store). A plugin should normally reuse these options instead of defining its own versions.
During delivery, body_format is the resolved format the plugin must send. body_passthrough=True means the caller did not declare a source format, so Apprise skipped source-format conversion and dialect repair. It does not disable message limits, overflow handling, escaping, transport encoding, or payload assembly.
The framework handles ordinary character limits and the upstream, truncate, and split modes. A plugin with byte-based limits, escaping, multiple body representations, or encryption overhead should calculate its final budget from the payload it will actually send and verify the result after conversion.
Do not assume arbitrary pass-through content can be split safely. JSON documents, ciphertext, signatures, and unknown markup may become invalid when divided. Honour the requested overflow mode, but treat splitting as best effort and avoid format-specific repair when body_passthrough is true.
Testing Your Plugin
Section titled “Testing Your Plugin”Apprise aims for 100% test coverage, so every plugin ships with a tests/test_plugin_<name>.py file. Most of the work is done by AppriseURLTester. You give it a list of URLs and what each one should do. For every URL it:
- Loads the URL and checks that the right class (or the right error) comes back.
- Rebuilds the URL with
url()and checks that it loads as the same service. - Checks that
url(privacy=True)hides every value markedprivate. - Sends a notification against a mocked
requestslibrary and checks the result.
Throttling is turned off during these tests, so a high request_rate_per_sec will not slow them down.
import requests
from apprise.exception import AppriseImproperlyConfiguredfrom apprise.plugins.myservice import NotifyMyService
from helpers import AppriseURLTester
apprise_url_tests = ( # No token given ( "myservice://", { "instance": AppriseImproperlyConfigured, }, ), # A working URL; check how it prints with privacy on ( "myservice://joe:pass123@abcdef1234", { "instance": NotifyMyService, "privacy_url": "myservice://joe:****@a...4", }, ), # The server answers 500 ( "myservice://joe:pass123@abcdef1234", { "instance": NotifyMyService, "response": False, "requests_response_code": requests.codes.internal_server_error, }, ), # The connection fails outright ( "myservice://joe:pass123@abcdef1234", { "instance": NotifyMyService, "test_requests_exceptions": True, }, ),)
def test_plugin_myservice_urls(): """URLs load, print and send as expected.""" AppriseURLTester(tests=apprise_url_tests).run_all()Each URL’s dictionary accepts these keys. Leave out any you do not need.
| Key | Default | What It Checks |
|---|---|---|
instance |
(required) | The class the URL should load as, or the exception it should raise. None means the URL should not load at all. |
privacy_url |
not checked | The start of url(privacy=True). Only the start is compared, so leave off the query string. |
url_matches |
not checked | A regular expression that url() must match. |
self |
not checked | A dict of attributes and the values they should hold after loading, such as {"token": "abcdef1234"}. |
response |
True |
What notify() should return. |
notify_response |
same as response |
Overrides response for the plain notify() call only. |
attach_response |
same as notify_response |
What notify() should return when an attachment is sent. |
requests_response_code |
200, or 404 if response is False |
The HTTP status the mocked server answers with. |
requests_response_text |
empty | The body the mocked server answers with. A dict is sent as JSON. |
test_requests_exceptions |
False |
Set to True to make every request raise a connection error, and check the plugin handles it. |
notify_type |
NotifyType.INFO |
The notification type to send. |
include_image |
True |
Set to False to send with images turned off in the asset. |
check_attachments |
True |
Set to False to skip the attachment send. |
fields_round_trip |
True |
Set to False to skip checking that the URL’s fields rebuild the same URL. |
storage_mode |
memory |
The persistent storage mode to load the plugin with. |
pdb |
False |
Set to True to stop in the Python debugger just before this URL loads. |
AppriseURLTester covers the common paths. Behavior it cannot reach, such as a 429 retry or a multi-step login, gets its own test function that patches requests.post (or get) directly and inspects the calls. Look at the existing tests for a plugin that works like yours for examples. See Running Tests for how to run them.
Questions or Feedback?
Technical Issues
Having trouble with the code? Open an issue on GitHub: