Notifiers Module
The notifiers module provides comprehensive notification functionality for sending messages to individual recipients or groups. It supports multiple notification channels and respects user preferences and permissions.
Functions
notifiers.recipient(id_or_handle, subject, message)
Sends a notification to a specific recipient through their configured channels.
Parameters:
id_or_handle(string): Recipient UUID or handle identifiersubject(string): Notification subject line (max 200 characters recommended)message(string): Notification message body (supports plain text or HTML)
Returns:
boolean:trueif notification was queued successfully,falseotherwise
Basic Examples:
lua
-- Simple notification
local success = notifiers.recipient(
"user-123",
"Welcome to CoCoCo!",
"Thank you for joining our service. Your account is now active."
)
if success then
print("Welcome notification sent")
else
print("Failed to send notification")
end
-- HTML formatted message
local html_message = [[
<h2>Order Confirmation</h2>
<p>Your order #12345 has been confirmed.</p>
<ul>
<li>Total: $99.99</li>
<li>Delivery: 3-5 business days</li>
</ul>
<p><a href="https://example.com/track/12345">Track your order</a></p>
]]
notifiers.recipient(user_id, "Order Confirmed", html_message)
-- Using template rendering for dynamic content
local template_output = template.render("order-confirmation", {
order_id = "12345",
total = 99.99,
items = order_items
})
if template_output then
notifiers.recipient(customer_id, "Order #12345 Confirmed", template_output)
endnotifiers.group(id_or_handle, subject, message)
Sends a notification to all active members of a recipient group.
Parameters:
id_or_handle(string): Group UUID or handle identifiersubject(string): Notification subject linemessage(string): Notification message body
Returns:
boolean:trueif notifications were queued for all group members,falseif any failed
Group Notification Examples:
lua
-- Notify entire team
local success = notifiers.group(
"operations-team",
"Printer Maintenance Required",
"Printer XYZ-001 requires immediate maintenance. Please check the dashboard."
)
-- System-wide announcement
notifiers.group(
"all-users",
"Scheduled Maintenance",
"The system will be under maintenance from 2 AM to 4 AM EST tonight."
)
-- Department-specific alert
local alert_message = [[
<strong>Urgent: Large Order Received</strong>
<p>Order #98765 requires immediate attention:</p>
<ul>
<li>Customer: Acme Corp</li>
<li>Quantity: 10,000 units</li>
<li>Deadline: Tomorrow 5 PM</li>
</ul>
<p>Please coordinate production immediately.</p>
]]
notifiers.group("production-team", "Urgent: Large Order", alert_message)Notification Patterns
Priority and Urgency Levels
lua
function send_priority_notification(recipient_id, level, subject, message)
-- Add priority indicators to subject
local priority_prefix = {
urgent = "🔴 URGENT: ",
high = "⚠️ HIGH: ",
normal = "",
low = "ℹ️ LOW: "
}
local prefixed_subject = (priority_prefix[level] or "") .. subject
return notifiers.recipient(recipient_id, prefixed_subject, message)
end
-- Usage
send_priority_notification(
"manager-123",
"urgent",
"Production Line Stopped",
"Line 3 has stopped due to material shortage. Immediate action required."
)Batch Notifications with Personalization
lua
function notify_order_updates(orders)
local results = {}
for _, order in ipairs(orders) do
-- Personalize message for each recipient
local message = string.format(
"Hello %s,\n\nYour order #%s status has changed to: %s\n\nThank you for your business!",
order.customer_name,
order.id,
order.status
)
local success = notifiers.recipient(
order.customer_id,
"Order Status Update",
message
)
table.insert(results, {
order_id = order.id,
success = success
})
end
return results
endScheduled Notifications
lua
function schedule_reminder(recipient_id, reminder_type, data)
local reminders = {
payment_due = {
subject = "Payment Reminder",
template = "payment-reminder"
},
appointment = {
subject = "Appointment Reminder",
template = "appointment-reminder"
},
deadline = {
subject = "Deadline Approaching",
template = "deadline-reminder"
}
}
local reminder = reminders[reminder_type]
if not reminder then
return false
end
-- Render template with data
local message = template.render(reminder.template, data)
if message then
return notifiers.recipient(recipient_id, reminder.subject, message)
end
return false
endError Notification System
lua
function notify_error_chain(error_data)
local levels = {
{
threshold = 1,
recipient = "on-call-engineer",
delay = 0
},
{
threshold = 5,
recipient = "engineering-team",
delay = 300 -- 5 minutes
},
{
threshold = 10,
recipient = "management-team",
delay = 900 -- 15 minutes
}
}
for _, level in ipairs(levels) do
if error_data.count >= level.threshold then
-- Check if already notified (using cache)
local cache_key = "error_notified:" .. error_data.id .. ":" .. level.recipient
if not cache.get(cache_key) then
notifiers.group(
level.recipient,
"System Error Alert - Level " .. level.threshold,
format_error_message(error_data)
)
-- Mark as notified for 1 hour
cache.put_ttl(cache_key, true, 3600)
end
end
end
endIntegration Examples
Order Processing Pipeline
lua
function process_order_notifications(order_id)
-- Fetch order details
local success, response = graphql.query([[
query($id: ID!) {
getOrder(id: $id) {
id
customer {
id
name
email
preferences {
notifications {
orderConfirmation
shipping
marketing
}
}
}
items {
name
quantity
price
}
total
}
}
]], { id = order_id })
if not success or not response.data then
print("Failed to fetch order")
return false
end
local order = response.data.getOrder
local prefs = order.customer.preferences.notifications
-- Send confirmation if enabled
if prefs.orderConfirmation then
local confirmation_message = template.render("order-confirmation", {
customer_name = order.customer.name,
order = order
})
notifiers.recipient(
order.customer.id,
"Order #" .. order.id .. " Confirmed",
confirmation_message
)
end
-- Notify warehouse team
notifiers.group(
"warehouse-team",
"New Order for Processing",
"Order #" .. order.id .. " is ready for fulfillment. Total items: " .. #order.items
)
return true
endMulti-Channel Notification Strategy
lua
function send_multi_channel_notification(recipient_id, notification_data)
local channels = {
email = function(data)
return notifiers.recipient(
recipient_id,
data.subject,
data.email_body
)
end,
sms = function(data)
-- SMS typically has shorter message
local short_message = data.sms_body or
string.sub(data.email_body, 1, 160)
return notifiers.recipient(
recipient_id .. ":sms",
data.subject,
short_message
)
end,
push = function(data)
return notifiers.recipient(
recipient_id .. ":push",
data.subject,
data.push_body or data.email_body
)
end
}
local results = {}
for channel, send_func in pairs(channels) do
if notification_data.channels[channel] then
results[channel] = send_func(notification_data)
end
end
return results
endBest Practices
Use templates for consistency: Maintain message templates for common notifications
lua-- Store templates centrally and reuse local templates = { welcome = "welcome-email", order_confirm = "order-confirmation", password_reset = "password-reset" } function send_templated_notification(recipient, template_key, data) local template_id = templates[template_key] if not template_id then return false end local message = template.render(template_id, data) return notifiers.recipient(recipient, data.subject, message) endImplement retry logic: Handle temporary failures gracefully
luafunction send_with_retry(recipient, subject, message, max_retries) max_retries = max_retries or 3 local retry_count = 0 while retry_count < max_retries do local success = notifiers.recipient(recipient, subject, message) if success then return true end retry_count = retry_count + 1 -- Exponential backoff: 1s, 2s, 4s local sleep_time = math.pow(2, retry_count - 1) -- Note: Actual sleep would require coroutine support print("Retry " .. retry_count .. " after " .. sleep_time .. "s") end return false endRate limit notifications: Prevent notification spam
luafunction rate_limited_notify(recipient, subject, message, limit_key, window_seconds) local rate_key = "notify_rate:" .. recipient .. ":" .. limit_key local count = cache.get(rate_key, 0) if count >= 5 then -- Max 5 notifications per window print("Rate limit exceeded for " .. recipient) return false end local success = notifiers.recipient(recipient, subject, message) if success then cache.put_ttl(rate_key, count + 1, window_seconds or 3600) end return success endLog notification events: Track delivery and engagement
luafunction tracked_notification(recipient, subject, message, tracking_id) local success = notifiers.recipient(recipient, subject, message) -- Log to database database.query( "analytics-db", "INSERT INTO notification_log (tracking_id, recipient, subject, sent_at, success) VALUES (?, ?, ?, NOW(), ?)", {tracking_id or generate_uuid(), recipient, subject, success} ) return success end
Security and Performance
Security:
- Requires actor permissions to access recipient/group
- Recipients can only be notified if actor has appropriate permissions
- Message content is sanitized to prevent injection attacks
- Rate limiting prevents abuse
Performance:
- Notifications are queued asynchronously
- Bulk operations are optimized for group notifications
- Failed notifications may be retried automatically
- Consider batching for large recipient lists