Last Updated: November 2026 · Plugin API: 1.3 · Capabilities: notify:in-app, notify:push, notify:email, notify:email-address
registry.notify lets a plugin reach a player through the engine’s own channels: the notification bell (in-app), push to the player’s registered devices, and email. Each channel needs its own capability, has its own daily limit, and goes through the same core service the engine uses, so the player’s preferences, the push and email circuit breakers and the SMTP configuration all apply.
Declare the channels you use in your manifest, for example "capabilities": ["notify:in-app", "notify:push"]. A channel you did not declare, or that the admin did not grant at activation, throws PluginCapabilityError on every call. See capabilities.md.
API
registry.notify.inApp(userId, {
subject: string, // 1-200 characters
content: string, // 1-4000 characters, plain text
category?: string, // ^[a-z0-9][a-z0-9_-]{0,63}$; a registered category key applies the player's choice (API 1.3)
link?: string, // relative in-app path, e.g. '/progression' (no other origins)
data?: Record<string, string>, // API 1.3: public data for your notifications.item.actions fill; same limits as push data
}): Promise<{ delivered: true, messageId: string } | { delivered: false, reason: 'opted_out' }>
registry.notify.push(userId, {
title: string, // 1-100 characters
body: string, // 1-500 characters
data?: Record<string, string>, // at most 20 keys (^[A-Za-z0-9_.-]{1,64}$), values up to 1024 characters
category?: string, // API 1.3: a registered category key
}): Promise<{ delivered: boolean, devicesTargeted: number, reason?: PushSkipReason, error?: string }>
registry.notify.email(userId, {
subject?: string, // 1-200 characters; required unless templateKey names a template
html?: string, // 1-100000 characters; required unless templateKey names a template
text?: string, // plain-text part; derived from html when omitted
templateKey?: string, // ^[a-z0-9_-]{1,100}$: your registered template's key, or an admin template
variables?: Record<string, string | number>, // at most 50, for {{name}} placeholders
kind?: 'transactional' | 'marketing', // API 1.2; default 'transactional'
category?: string, // API 1.3: a registered category key (a marketing category forces kind 'marketing')
}): Promise<{ delivered: boolean, reason?: EmailSkipReason, emailLogId?: string, error?: string }>
// API 1.2, capability notify:email
registry.notify.registerEmailTemplates([{
key: string, // ^[a-z0-9][a-z0-9_-]{0,63}$, unique in the call
name: string, // display name for the admin, 1-120 characters
subject: string, // 1-255 characters, {{name}} placeholders allowed
html: string, // 1-100000 characters
text?: string, // accepted; the text part is derived from the (admin-editable) html
description?: string, // up to 500 characters, shown to the admin
variables?: string[], // the {{names}} you fill in, listed in the admin editor
}]): Promise<{ created: string[], existing: string[] }> // 1-50 templates per call
// API 1.3, any notify:* capability (plus the capability of every channel listed)
registry.notify.registerCategories([{
key: string, // ^[a-z0-9][a-z0-9_-]{0,63}$, unique in the call
label: string, // shown to the player, 1-80 characters (already translated)
description?: string, // up to 300 characters
channels: ('inApp' | 'push' | 'email')[], // the channels this category uses, at least one
defaultOn?: boolean, // default true: the player's choice before they change it
marketing?: boolean, // default false: email for this category is always kind 'marketing'
}]): Promise<{ registered: string[] }> // at most 50 categories per plugin
type PushSkipReason = 'push_disabled' | 'opted_out' | 'no_devices' | 'circuit_open' | 'failed';
type EmailSkipReason = 'email_unverified' | 'opted_out' | 'not_opted_in' | 'circuit_open' | 'failed';
Strings are trimmed before the length checks. Unknown fields are rejected. Invalid input throws ValidationError (HTTP 400 if it reaches a route). An unknown userId throws NotFoundError. Types are exported by @poker-engine/plugin-sdk (PluginNotify, PluginInAppMessage, PluginPushMessage, PluginEmailMessage, the result types, since API 1.2 PluginEmailKind, PluginEmailTemplate and PluginEmailTemplateRegistration, and since API 1.3 PluginNotifyCategory, PluginNotifyCategoryRegistration, NotifyCategoryChannel and PluginInAppSkipReason).
API 1.3 type change: PluginInAppResult is now a union. Check result.delivered before reading result.messageId; it is false (with reason: 'opted_out') only for a registered category the player switched off, so plugins that never pass a registered category keep getting delivered: true.
Example
export async function register(registry) {
registry.addAction('tournament:finished', async ({ name, standings }) => {
for (const { userId, position } of standings.slice(0, 3)) {
try {
await registry.notify.inApp(userId, {
subject: `You finished #${position} in ${name}`,
content: 'Your badge is waiting on your profile.',
category: 'tournament',
link: '/progression',
});
await registry.notify.push(userId, { title: 'Podium finish', body: `#${position} in ${name}` });
} catch (error) {
// NotifyRateLimitError: this player already got today's quota from your plugin
registry.logger.warn('Notification skipped', { userId, error: (error as Error).message });
}
}
});
}
Categories and player preferences (API 1.3)
Register the kinds of notification your plugin sends, and the channels each one uses, from register(). Players see them in Settings → Notifications (/settings#notifications): one grid of category × channel, grouped by source (core’s own push and game-invite switches first, then each plugin under its display name, or the groupLabel it passes). Their choices are stored per player, source, category and channel in the notification_preferences table, and read back through GET/PUT /api/v1/user/notification-preferences.
export async function register(registry) {
await registry.notify.registerCategories([
{ key: 'friend-requests', label: 'Friend requests', channels: ['inApp', 'push'] },
{ key: 'free-chips', label: 'Free-chip offers', channels: ['inApp', 'email'], marketing: true },
{ key: 'weekly-digest', label: 'Weekly digest', channels: ['email'], defaultOn: false },
], { groupLabel: 'Friends and offers' }); // optional: the group's heading in Settings
// later, for a player:
const result = await registry.notify.inApp(userId, {
subject: 'Bob wants to be friends',
content: 'Open your friends list to accept.',
category: 'friend-requests',
link: '/profile?tab=plugin:social-friends',
});
if (!result.delivered) {
// reason 'opted_out': the player switched friend requests off for in-app
}
}
- Opted out.
inApp,pushandemailacceptcategory. When it is a key you registered and the player switched that channel off (or never switched on adefaultOn: falsecategory), the call returns{ delivered: false, reason: 'opted_out' }(push addsdevicesTargeted: 0) before a quota slot is taken. The player’s global switches still apply first: push off in their settings, or email notifications off, also returnopted_out. - Marketing categories. Email for a category registered with
marketing: trueis always sent askind: 'marketing', whateverkindyou pass, so it needs the player’s marketing consent (not_opted_inotherwise). Mark promotions, offers and win-back campaigns as marketing. - Channels must match. Using a registered category on a channel it did not list throws
ValidationError, so the grid always shows every switch that can stop a send. Register the channel, or send withoutcategory. - Unregistered categories behave as before API 1.3: no preference applies, and in-app keeps the value in
metadata.category(the player API’ssubcategory). - Group label. The second argument
{ groupLabel }(1 to 80 characters) titles your group in the grid; without it the group carries your plugin’s display name. Pick a label that describes the categories when the display name would read oddly inside the Notifications section (the notifications plugin uses "Offers and reminders"). A later call withoutgroupLabelkeeps the label set before. - Registration. Validated with zod. Idempotent: registering a key again updates its label, description, channels and flags; keys you no longer register stay until the plugin is reloaded. The call needs any
notify:*capability, plus the capability of every channel a category lists (emailneedsnotify:email), otherwisePluginCapabilityError. Categories are held per server node, like hooks: every node registers them when it loads the plugin, they disappear from the grid when the plugin is deactivated, and the players’ saved choices are kept for when it comes back. - Plugin settings that are not notification on/off switches belong in your own section of the Settings page: the
settings.sectionsslot (see extension-points.md).
Channels
In-app (notify:in-app)
Writes a player notification: a Message row with receiverId = userId, no senderId, category = GENERAL, source = "plugin:<providerType>" and metadata = { category, link, data }.
- The
MessageCategoryenum only hasGENERAL,VERIFICATION,WITHDRAWALandSUPPORT, so the row is stored asGENERAL. The player API (GET /api/v1/user/notifications) reports plugin rows withcategory: "plugin:<providerType>",sender: "plugin:<providerType>", and the extra fieldssource,subcategory(yourcategory),linkand (API 1.3)metadata(yourdata, string values only; null for other messages). datagoes to the player’s browser as is: put ids and tokens meant for that player there (a claim token), never secrets or other players’ details. The notifications page passes it to yournotifications.item.actionsfill (see Slot Fills).- The server emits the
notification_newsocket event ({ id, category, subject, source }) to the player’suser:<userId>room. The client reloads the header bell and the notifications page when it arrives. Admin messages composed in the admin panel emit the same event. contentis shown as plain text.
Push (notify:push)
Sends through sendPushNotification with type: 'plugin' (normal priority). The engine adds data.source = "plugin:<providerType>". The player’s choices are checked before the server’s push configuration, so a plugin with a push channel of its own (the Notifications plugin’s browser push) can send after any result other than opted_out and still respect them.
| Result | When | Uses quota |
|---|---|---|
delivered: true | At least one device was targeted and the provider accepted it | Yes |
reason: 'opted_out' | The player turned push notifications off in their settings, or switched off this message’s registered category for push (API 1.3), or the category is a marketing one and the player is in a self-exclusion or cool-off | No |
reason: 'push_disabled' | App push is not configured on this server (checked after the player’s choices, so opted_out always wins) | No |
reason: 'circuit_open' | The push circuit breaker is open (the provider is failing); try later | No |
reason: 'no_devices' | The player has no active device | No |
reason: 'failed' | The provider rejected the send (error has the message) | No |
Email (notify:email)
Sends through the email service, so it is logged in email_logs with sentBy = "plugin:<providerType>", rate-limited by the server-wide email limit and protected by the email circuit breaker.
- Confirmed addresses only. The player must have
isEmailConfirmed. Otherwise the result is{ delivered: false, reason: 'email_unverified' }and nothing is sent. Bot accounts are refused the same way. So are placeholder addresses (*.invalid, used by guest and Telegram accounts without an email of their own, plugin API 1.4): the email service never sends to them. - Opt-out.
User.emailNotificationsis the player’s single "email at all" switch (Settings → Email; the settings row keeps a copy). When it is off the result isreason: 'opted_out'. Since API 1.3 a registeredcategoryswitched off for email returns the same reason. - Kind (API 1.2).
kind: 'transactional'(the default) is for messages the player asked for: a claim confirmation, a reminder for a tournament they registered for, a receipt.kind: 'marketing'is for everything promotional: win-back offers, free-chip campaigns, newsletters. A marketing email also needs the player’s marketing consent (User.marketingEmails, off for everyone until the player opts in); without it the result is{ delivered: false, reason: 'not_opted_in' }, returned before a quota slot is taken. Marketing email gets theList-UnsubscribeandList-Unsubscribe-Post: List-Unsubscribe=One-Clickheaders (RFC 8058) and an unsubscribe footer (HTML and text) linking to the player’s/unsubscribepage. Do not send promotions as transactional to get around consent; operators can seesentByand the content in Email Logs. - Templates. With
templateKey, the engine uses, in order: your own registered template (plugin_<providerType>_<templateKey>, see below), then an admin template namedtemplateKeythat no other plugin owns, else yoursubject/html/text. A template is rendered withvariablesand the player’s language (phrasesemail.<camelName>.subject/body).{{name}}placeholders are filled fromvariables, plus{{username}}and (API 1.2){{siteUrl}}, the site URL from Settings › Server & Email Delivery without a trailing slash, for absolute links such as{{siteUrl}}/ext/<providerType>/claim/<token>(a variable you pass with that name wins); values are HTML-escaped inhtml. WithtemplateKeyand nosubject/html, a missing template throwsNotFoundError(no quota used). System template names (password_reset,email_verification,welcome, …) are refused withValidationError, unless you registered your own template under that key.
Registering email templates (API 1.2)
Call registry.notify.registerEmailTemplates from register() with your default templates. Each one becomes an EmailTemplate row named plugin_<providerType>_<key> (the name must fit in 100 characters), marked as owned by your plugin. The row is created only when it does not exist yet: once it is there, the admin owns the subject and body and can edit them in Site & Content › Email Templates (shown with a Plugin: <providerType> badge), and your later registrations never overwrite them. Your name, description and variables are refreshed on every registration. The call is idempotent and safe on several nodes at once. The admin cannot rename a plugin template; deleting it brings your default back on the next load.
export async function register(registry) {
await registry.notify.registerEmailTemplates([
{
key: 'free_chips',
name: 'Free chips offer',
subject: '{{username}}, {{amount}} free chips are waiting',
html: '<p>Hi {{username}},</p><p><a href="{{claimUrl}}">Claim your {{amount}} chips</a></p>',
description: 'Sent by free-chip campaigns',
variables: ['username', 'amount', 'claimUrl'],
},
]);
// later, for a player:
const result = await registry.notify.email(userId, {
templateKey: 'free_chips',
kind: 'marketing',
variables: { amount: 1000, claimUrl: 'https://example.com/notifications?claim=abc' },
});
if (result.reason === 'not_opted_in') {
// the player has not opted in to promotional email: use in-app instead
}
}
- Send errors (SMTP not configured, provider failure) return
{ delivered: false, reason: 'failed', error }rather than throwing.reason: 'circuit_open'means the email circuit breaker is open. - Outbox (API 1.2). Every email goes through the engine’s email outbox. When it can’t be sent right away (the server-wide SMTP rate limit is reached, or the SMTP server failed and a retry is scheduled) the result is
{ delivered: true, queued: true, emailLogId }: the engine owns the email now and delivers it later, so don’t send it again. It counts against your daily email limit like a delivered one. See System Emails — Delivery and Retries.
Email to addresses (notify:email-address, API 1.3)
registry.notify.emailAddress(to: string | string[], {
subject: string, // 1-200 characters, one line
text: string, // 1-50,000 characters, plain text
html?: string, // optional HTML body; an escaped copy of `text` is used when omitted
}): Promise<{ sent: boolean, sentCount: number, reason?: 'smtp_unavailable' | 'rate_limited' | 'failed', error?: string }>
For addresses that are not player accounts, typically a list an admin enters in your settings (alerts, reports). One email is sent per address through the same email service (logged in email_logs with sentBy = "plugin:<providerType>").
- At most 20 recipients per call (after removing duplicates) and 60 emails per plugin per hour, counted per recipient, in memory per server node. Over the limit nothing is sent and the call returns
reason: 'rate_limited'(logged at warn). - The subject is prefixed with your plugin’s display name, for example
[AI Bots] Daily spend cap reached. - Invalid addresses or fields throw
ValidationError. SMTP not configured, the email circuit open or a provider error never throw: you get{ sent: false, reason }. When some of several recipients fail,sentis true andsentCountis lower than the recipient count.
Rate limits
Per plugin, per player, per UTC day:
| Channel | Limit |
|---|---|
| In-app | 20 |
| Push | 5 |
| 2 |
Going over throws NotifyRateLimitError (code: 'PLUGIN_NOTIFY_RATE_LIMITED', HTTP 429, with channel and limit). It extends RateLimitError. Sends that are skipped or fail give their slot back, and refusals that happen before sending (opted out, not opted in to marketing, unconfirmed address, circuit open, push disabled) never take one.
The counters live in plugin_data under sys:notify:<userId>:<YYYY-MM-DD> with the value { inApp, push, email }. The sys: prefix is reserved for the engine, so registry.storage can neither read nor reset them. Each slot is taken in one atomic SQL upsert that only increments below the limit, so concurrent calls on several server nodes can never overshoot. Rows older than two days are pruned automatically.
Testing
createTestRegistry() from @poker-engine/plugin-sdk/testing has a notify double with the same signatures and result shapes. It enforces the same daily limits (throwing TestNotifyRateLimitError) and records every send in registry.test.notifications:
import { createTestRegistry } from '@poker-engine/plugin-sdk/testing';
const registry = createTestRegistry({ providerType: 'progression' });
await register(registry);
await registry.test.doAction('tournament:finished', payload);
expect(registry.test.notifications).toContainEqual(
expect.objectContaining({ channel: 'inApp', userId: 'u1' })
);
// Simulate a skipped push
const quiet = createTestRegistry({
overrides: { notify: { push: async () => ({ delivered: false, devicesTargeted: 0, reason: 'opted_out' }) } },
});
The double does not check capabilities or validate input. Since API 1.2 it also mirrors marketing consent and templates:
registry.test.setMarketingConsent('u1', true); // opt a test player in
await registry.notify.email('u2', { subject: 's', html: 'h', kind: 'marketing' });
// -> { delivered: false, reason: 'not_opted_in' } (no quota used)
await registry.notify.registerEmailTemplates([{ key: 'welcome', name: 'Welcome', subject: 'Hi', html: '<p>Hi</p>' }]);
registry.test.emailTemplates.get('welcome'); // first registration wins, like the engine
API 1.3: the double records categories and applies the player’s choice the way the engine does (opted out before the quota, marketing categories forced to marketing, an undeclared channel refused):
await registry.notify.registerCategories([{ key: 'friend-requests', label: 'Friend requests', channels: ['inApp', 'push'] }]);
registry.test.notificationCategories.get('friend-requests'); // { ..., defaultOn: true, marketing: false }
registry.test.setNotificationPreference('u1', 'friend-requests', 'inApp', false);
await registry.notify.inApp('u1', { subject: 's', content: 'c', category: 'friend-requests' });
// -> { delivered: false, reason: 'opted_out' }
Source
| File | Purpose |
|---|---|
src/core/plugins/plugin-notify.ts | registry.notify, validation, rate limits, NotifyRateLimitError |
src/core/plugins/plugin-notify-categories.ts | registerCategories (API 1.3), the per-node category registry, the player’s choice for a send |
src/services/notification-preferences.service.ts | Settings → Notifications: the grid (GET/PUT /api/v1/user/notification-preferences), core switches in UserSettings |
src/services/player-notifications.service.ts | createPlayerNotification, notification_new emit, player listing |
src/services/push-notification.service.ts | sendPushNotification, NotificationType 'plugin', circuit breaker |
src/services/email.service.ts | sendCustomEmail, sendEmailWithTemplate (kind, headers), email circuit breaker |
src/services/marketing-consent.service.ts | The marketing rule, consent writes, the single emailNotifications flag |
src/services/unsubscribe.service.ts | Signed unsubscribe tokens, List-Unsubscribe headers and footer |
prisma/migrations/20261107030000_plugin_notify_message_source/ | messages.source and messages.metadata |
See also: Marketing consent (admin guide), Capabilities, Realtime (for live, non-persistent messages), Plugin Development Guide.