Sending Notifications
Sending a Notification
The Airship Python Library strives to match the standard Airship API v3 JSON format for specifying notifications. When creating a notification, you:
Select the audience
Define the notification payload
Specify device types.
Deliver the notification.
This example performs a broadcast with the same alert to all recipients to a specific device type which can be list of types:
import urbanairship as ua
airship = ua.Airship(app_key, master_secret)
push = airship.create_push()
push.audience = ua.all_
push.notification = ua.notification(alert='Hello, world!')
push.device_types = ua.device_types('android', 'ios')
push.send()
Audience Selectors
An audience should specify one or more devices. An audience can be a
device, such as a channel
, a tag,
alias, segment, location, or a combination. Audience selectors are
combined with and_
, or_
, and not_
.
- urbanairship.push.all_
Select all, to do a broadcast.
push.audience = ua.all_
- urbanairship.push.audience.ios_channel(uuid: str) Dict[str, str]
Select a single iOS Channel
- urbanairship.push.audience.android_channel(uuid: str) Dict[str, str]
Select a single Android Channel
- urbanairship.push.audience.amazon_channel(uuid: str) Dict[str, str]
Select a single Amazon Channel
- urbanairship.push.audience.device_token(token: str) Dict[str, str]
Select a single iOS device token
- urbanairship.push.audience.apid(uuid: str) Dict[str, str]
Select a single Android APID
- urbanairship.push.audience.channel(uuid: str) Dict[str, str]
Select a single channel. This selector may be used for any channel_id, regardless of device type
- urbanairship.push.audience.open_channel(uuid: str) Dict[str, str]
Select a single Open Channel
- urbanairship.push.audience.sms_sender(sender: str) Dict[str, str]
Select an SMS Sender
- urbanairship.push.audience.sms_id(msisdn: str, sender: str) Dict[str, Dict]
Select an SMS MSISDN
- urbanairship.push.audience.wns(uuid: str) Dict[str, str]
Select a single Windows 8 APID
- urbanairship.push.audience.tag(tag: str) Dict[str, str]
Select a single device tag.
- urbanairship.push.audience.tag_group(tag_group: str, tag: str) Dict[str, str]
Select a tag group and a tag.
- urbanairship.push.audience.alias(alias: str) Dict[str, str]
Select a single alias.
- urbanairship.push.audience.segment(segment: str) Dict[str, str]
Select a single segment.
- urbanairship.push.audience.named_user(name: str) Dict[str, str]
Select a Named User ID
- urbanairship.push.audience.subscription_list(list_id: str) Dict[str, str]
Select a subscription list
- urbanairship.push.audience.static_list(list_id: str) Dict[str, str]
Select a static list
- urbanairship.push.audience.date_attribute(attribute: str, operator: str, precision: str | None = None, value: str | int | None = None) Dict[str, Any]
Select an audience to send to based on an attribute object with a DATE schema type, including predefined and device attributes. Please refer to https://docs.airship.com/api/ua/?http#schemas-dateattribute for more information about using this selector, including information about required data formatting for values. Custom attributes must be defined in the Airship UI prior to use.
- urbanairship.push.audience.text_attribute(attribute: str, operator: str, value: str) Dict[str, Any]
Select an audience to send to based on an attribute object with a TEXT schema type, including predefined and device attributes.
Please refer to https://docs.airship.com/api/ua/?http#schemas-textattribute for more information about using this selector, including information about required data formatting for values.
Custom attributes must be defined in the Airship UI prior to use.
- urbanairship.push.audience.number_attribute(attribute: str, operator: str, value: int) Dict[str, Any]
Select an audience to send to based on an attribute object with a INTEGER schema type, including predefined and device attributes.
Please refer to https://docs.airship.com/api/ua/?http#schemas-numberattribute for more information about using this selector, including information about required data formatting for values.
Custom attributes must be defined in the Airship UI prior to use.
- urbanairship.push.audience.or_(*children: Any) Dict[str, Any]
Select devices that match at least one of the given selectors.
>>> or_(tag('sports'), tag('business')) {'or': [{'tag': 'sports'}, {'tag': 'business'}]}
- urbanairship.push.audience.and_(*children: Any) Dict[str, Any]
Select devices that match all of the given selectors.
>>> and_(tag('sports'), tag('business')) {'and': [{'tag': 'sports'}, {'tag': 'business'}]}
- urbanairship.push.audience.not_(child: Any) Dict[str, Any]
Select devices that does not match the given selectors.
>>> not_(and_(tag('sports'), tag('business'))) {'not': {'and': [{'tag': 'sports'}, {'tag': 'business'}]}}
Notification Payload
The notification payload determines what message and data is sent to a
device. At its simplest, it consists of a single string-valued
attribute, alert
, which sends a push notification consisting of a
single piece of text:
push.notification = ua.notification(alert='Hello, world!')
You can override the payload with platform-specific values as well.
- urbanairship.push.payload.notification(alert: str | None = None, ios: Dict | None = None, android: Dict | None = None, amazon: Dict | None = None, web: Dict | None = None, wns: Dict | None = None, actions: Dict | None = None, interactive: Dict | None = None, in_app: Dict | None = None, open_platform: Dict | None = None, sms: Dict | None = None, email: Dict | None = None) Dict[str, Any]
Create a notification payload.
- Parameters:
alert – A simple text alert, applicable for all platforms.
ios – An iOS platform override, as generated by
ios()
.android – An Android platform override, as generated by
android()
.amazon – An Amazon platform override, as generated by
amazon()
.web – A web platform override, as generated by
web()
.wns – A WNS platform override, as generated by
wns()
.sms – An Sms platform override as generated by
sms()
.actions – Used to perform a defined task.
interactive – A dictionary with two attributes – “type” and “button_actions”, as generated by
interactive()
.open_platform – A dictionary with open platform name keys, and open platform overrides, as generated by
open_platform()
.
- urbanairship.push.payload.ios(alert: str | Dict | None = None, badge: str | int | None = None, sound: str | Dict | None = None, content_available: bool = False, extra: Dict[str, Any] | None = None, expiry: str | int | None = None, interactive: Dict[str, Any] | None = None, category: str | None = None, title: str | None = None, mutable_content: bool | None = None, subtitle: str | None = None, media_attachment: Dict | None = None, priority: int | None = None, collapse_id: str | None = None, thread_id: str | None = None, interruption_level: str | None = None, relevance_score: float | None = None, target_content_id: str | None = None, live_activity: Dict[str, Any] | None = None) Dict[str, Any]
iOS specific platform override payload.
- Parameters:
alert – iOS format alert, as either a string or dictionary. If a dictionary, the accepted keys must match those in Apple’s Payload Key Reference. Some options are only available with certain iOS versions on the device being sent to.
badge – An integer badge value or an autobadge string.
sound – If a string, the name of a sound file in the app bundle. If a dict, the ‘name’ key specifies the name of the sound file. Some options require iOS 12 or above on the device.
content_available – If true, the payload is delivered to your app in the background. This flag is automatically set to true if there is an In-App Message in the payload.
extra – A set of key/value pairs to include in the push payload sent to the device.
expiry – An integer or time set in UTC as a string
interactive – A dictionary with two attributes – “type” and “button_actions”, as generated by
interactive()
.category – A keyword used to categorize the notification. Must be a string
title – Sets the title of the notification for Apple Watch. Must be a string
mutable_content – Optional, a boolean. Defaults to false. When set to true, content may be modified by an extension. This flag will be automatically set to true if there is a media_attachment in the payload. iOS 10 or above.
subtitle – Optional, a string that will display below the title of the notification. This is provided as a convenience for setting the subtitle in the alert JSON object. If a subtitle is also defined in the alert JSON object, this value is ignored. iOS 10 or above.
media_attachment – Optional, a dictionary object Media Attachment. Specifies a media attachment to be handled by the UA Media Attachment Extension.
collapse_id – Optional, a string. When there is a newer message that renders an older, related message irrelevant to the client app, the new message replaces the older message with the same collapse_id. Similar to the GCM collapse_key. The value of this key must not exceed 64 bytes. iOS 10 or above.
thread_id – Optional, a string. A unique identifier used to group notifications into separate threads in the Notification Center and on the lock screen. Grouped notifications are available beginning with iOS 12.
interruption_level – Optional, a string. Indicates the importance and delivery timing of a notification. Must be one of: passive, active, time-sensitive, critical. Note: Use of the ‘critical’ levels requires an entitlement grant from Apple. Once this grant has been enabled, contact Airship Support to enable support with our APIs.
relevance_score – Optional, a number from 0.0 to 1.0. Used to sort notifications for an app. The notification with highest score is featured in the notification summary.
live_activity – Optional, JSON object that represents the content sent to a Live Activity Notification.
- Target_content_id:
Optional, a string. The identifier of the window to bring forward when the notification is opened. Used for multi-window content, such as App Clips.
>>> ios(alert='Hello!', sound='cat.caf', ... extra={'articleid': '12345'}) {'sound': 'cat.caf', 'extra': {'articleid': '12345'}, 'alert': 'Hello!'}
- urbanairship.push.payload.android(alert: str | None = None, collapse_key: str | None = None, time_to_live: int | None = None, delay_while_idle: bool | None = False, extra: Dict | None = None, interactive: Dict | None = None, local_only: bool | None = None, wearable: Dict | None = None, delivery_priority: str | None = None, style: Dict | None = None, title: str | None = None, summary: str | None = None, sound: str | None = None, priority: int | None = None, category: str | None = None, visibility: int | None = None, public_notification: Dict | None = None, notification_tag: str | None = None, notification_channel: str | None = None, icon: str | None = None, icon_color: str | None = None, live_update: Dict[str, Any] | None = None) Dict[str, Any]
Android specific platform override payload.
All keyword arguments are optional.
- Parameters:
alert – String alert text.
collapse_key – String
time_to_live – Integer
delay_while_idle – Boolean
extra – A set of key/value pairs to include in the push payload sent to the device. All values must be strings.
interactive – A dictionary with two attributes – “type” and “button_actions”, as generated by
interactive()
.local_only – Optional value for not showing the notification on wearable devices. Defaults to False.
wearable – Optional object to define a wearable notification with the following optional fields: background_image, extra_pages, and interactive.
delivery_priority – Optional string of either ‘high’ or ‘normal’. Sets the GCM priority.
style – Optional object. Defines an advanced style.
title – Optional string. Represents the title of the notification.
summary – Optional string. Represents a summary of the notification.
sound – Optional string. Represents a sound file name included in the app resources.
priority – Optional integer between -2 and 2. An Android L feature that determines location sort order.
category – Optional string. An Android category.
visibility – Optional integer between -1 and 1.
public_notification – Optional object. A notification to show on the lock screen instead instead of the redacted one.
notification_tag – Optional string. A string identifier used to replace an existing notification in the notification drawer.
notification_channel – Optional string. An identifier of a notification channel predefined by the application.
icon – Optional string. The name of a drawable in the application’s resource directory.
icon_color – Optional. A string in the format of #rrggbb that defines the notification accent color.
live_update – Optional, a JSON object that represents the content sent to a Live Update notification.
See GCM Advanced Topics for details on
collapse_key
,time_to_live
, anddelay_while_idle
.>>> android(alert='Hello!', extra={'articleid': '12345'}) {'extra': {'articleid': '12345'}, 'alert': 'Hello!'}
- urbanairship.push.payload.amazon(alert: str | None = None, consolidation_key: str | None = None, expires_after: str | int | None = None, extra: Dict | None = None, title: str | None = None, summary: str | None = None, interactive: Dict | None = None, style: str | None = None, sound: str | None = None, icon: str | None = None, icon_color: str | None = None, notification_channel: str | None = None, notification_tag: str | None = None) Dict[str, Any]
Amazon specific platform override payload.
All keyword arguments are optional.
- Parameters:
alert – String alert text.
consolidation_key – String
expires_after – Integer or UTC time (string)
extra – A set of key/value pairs to include in the push payload sent to the device. All values must be strings.
title – String
summary – String
interactive – A dictionary with two attributes – “type” and “button_actions”, as generated by
interactive()
.notification_tag – Optional string. A string identifier used to replace an existing notification in the notification drawer.
notification_channel – Optional string. An identifier of a notification channel predefined by the application.
icon – Optional string. The name of a drawable in the application’s resource directory.
icon_color – Optional. A string in the format of #rrggbb that defines the notification icon accent color.
>>> amazon(alert='Hello!', title='My Title', ... extra={'articleid': '12345'}) {'title': 'My Title', 'extra': {'articleid': '12345'}, 'alert': 'Hello!'}
- urbanairship.push.payload.web(alert: str | None = None, extra: Dict | None = None, icon: Dict | None = None, title: str | None = None, interactive: Dict | None = None, time_to_live: str | int | None = None, require_interaction: bool | None = None) Dict[str, Any]
Web specific platform override payload.
All keyword arguments are optional
- Parameters:
alert – An optional string alert text.
extra – An optional set of key/value pairs to include in the push payload sent to the device.
icon – An optional JSON dictionary of string key and value pairs. Key must be ‘url’ and value, an HTTPS URL to the icon resource.
title – Optional string. Represents the title of the notification.
interactive – An optional dictionary with two attributes –
type
andbutton_actions
, as generated byinteractive()
time_to_live – An optional integer or time set in UTC as a string
require_interaction – An optional boolean value that requires user interaction on the notification before it is dismissed.
>>> web(extra={'articleid': '12345'}, ... icon={'url': 'https://example.com/icon.png'}, ... title='This is a title!') {'title': 'This is a title!', 'extra': {'articleid': '12345'}, 'icon': {'url': 'https://example.com/icon.png'}, 'alert': 'Hello!'}
- urbanairship.push.payload.sms(alert: str | None = None, expiry: str | int | None = None, template_alert: str | None = None, shorten_links: bool | None = None) Dict[str, Any]
Sms platform specific override payload See: https://docs.airship.com/api/ua/#schemas-smsoverrideobject One of alert or template_alert must be used.
- Parameters:
alert – An optional string. Overrides the alert provided at the top level of the notification for Sms channels. The maximum length of an Sms alert is 1600 characters.
template_alert – for use with CreateAndSendPush. Substitutions must be added to the Sms objects passed to CreateAndSendPush that match the bracketed fields in this alert string.
expiry – Optional. Delivery expiration, as either absolute UTC timestamp (string), or number of seconds from now (integer).
shorten_links – Optional. If true, Airship will shorten http/https links (space delimited) in the message text fields, producing unique, 25 character URLs for each member of your audience. If using this feature, please see the documentation linked above.
>>> sms(alert='sms override alert!', expiry='2018-04-01T12:00:00') {'alert': 'sms override alert!', 'expiry': '2018-04-01T12:00:00'}
- urbanairship.push.payload.mms(fallback_text: str, content_type: str, url: str, shorten_links: bool | None = None, content_length: int | None = None, text: str | None = None, subject: str | None = None) Dict[str, Any]
Provides the content for a push to MMS channels. If sms is in the device_type array, your request may include this object. It cannot be combined with an SMS Platform Override as a single push can only include either an SMS or MMS payload. Please see the documentation here: https://docs.airship.com/api/ua/#schemas-mmsoverrideobject
- Parameters:
fallback_text – Required. If a member of your audience cannot receive MMS messages, they will receive your fallback text with a link to the original content.
content_type – Required. The MIME type of the image specified in the URL. The MIME type must match the extension in the url.
url – Required. The http or https URL of the media attachment for the slide. The URL must end in one of .gif, .jpeg, .jpg, .png, or .vcf (case-insensitive). While the content_length field is optional, your image must still be under 2MB for JPEGs and PNGs, 1 MB for GIFs, or 2048000 bytes for text/vcard.
shorten_links – Optional. If true, Airship will shorten http/https links (space delimited) in the message text fields, producing unique, 25 character URLs for each member of your audience. If using this feature, please see the documentation linked above.
content_length – Optional. The length of the attachment in bytes. If using this feature, please see the documentation linked above.
text – Optional. Text that you want to display along with the media attachment. The order of media and text in the message is not guaranteed.
subject – Optional. The subject for the MMS message, normally displayed in bold. The subject might not appear for recipients if the Sender is a Toll-Free number.
- urbanairship.push.payload.email(message_type: str, plaintext_body: str, reply_to: str, sender_address: str, sender_name: str, subject: str, attachments: List[str] | None = None, html_body: str | None = None, variable_defaults: Dict[str, str] | None = None, bcc: List[str] | None = None, bypass_opt_in_level: bool | None = None, click_tracking: bool | None = None, open_tracking: bool | None = None)
Required platform override when email in ua.device_types. Specifies content of the email being sent. All other notification fields are not used in the email if included.
See https://docs.airship.com/api/ua/#schemas-emailoverrideobject for additional caveats.
- Parameters:
message_type – Required. One of transactional or commercial.
plaintext_body – Required. The plain text body of the email. May include variable substitution fields for use with create and send inline templates.
reply_to – Required. The reply-to address.
sender_address – Required. The email address of the sender. The domain of the email must be enabled in the email provider at the delivery tier.
sender_name – Required. The common name of the email sender.
subject – Required. The subject line of the email. May include variable substitution fields for use with create and send inline templates.
html_body – Optional. The HTML content of the email.
variable_details – Required for CreateAndSendPush with inline templates. a list of dicts of default values for inline template variables.
attachments – Optional. A list of attachment_id values from the API.
bcc – Optional. A list of email addresses that you want to blind copy on this email. Using addresses that Airship has not enabled for BCC will return a 400.
bypass_opt_in_level – Optional. You can set this toggle when message_type is set to transactional to send a business critical email. If true, the message will be sent to your entire audience, ignoring transactional_opted_out status.
click_tracking – Optional. True by default. Set to False to prevent click tracking for GDPR compliance.
open_tracking – Optional. True by default. Set to False to prevent “open” tracking for GDPR compliance.
- urbanairship.push.payload.open_platform(alert: str | None = None, title: str | None = None, extra: Dict[str, Any] | None = None, summary: str | None = None, media_attachment: str | None = None, interactive: Dict[str, Any] | None = None, template_alert: str | None = None) Dict[str, Any]
Open platform specific override payload.
All keyword arguments are optional.
- Parameters:
alert – String alert text.
title – String, represents the title of the notification.
summary – A string value for providing a content summary.
media_attachment – A URI for an image or video somewhere on the internet.
extra – A set of key/value pairs to include in the push payload sent to the device.
interactive – An interactive payload override, as generated by
interactive()
. Included button actions must be of typeadd_tag
,remove tag
,app_defined
, oropen
with subtypeurl
.template_alert – For use with CreateAndSendPush. A string with inline template substitution fields. The name of these must match subsititutions on the OpenChannel objects used with CreateAndSendPush.
>>> sms_overrides = open_platform( ... alert='Hello!', ... title='See my new homepage!', ... summary='A longer summary of some content', ... media_attachment='https://example.com/cat_standing_up.jpeg', ... extra={'some_info': 'for sms only'}, ... interactive=interactive( ... type='ua_yes_no_foreground', ... button_actions={ ... 'yes': actions(open_={ ... 'type':'url', ... 'content':'https://www.urbanairship.com' ... }), ... 'no': actions(app_defined={'foo': 'bar'}) ... } ... ) {'alert': 'Hello!', 'title': 'See my new homepage!', 'summary': 'A longer summary of some content', 'media_attachment': 'https://example.com/cat_standing_up.jpeg', 'extra': {'some_info': 'for sms only'}, 'interactive': {'type': 'ua_yes_no_foreground', 'button_actions': { 'yes': {'open': {'type': 'url', 'content': 'http://www.urbanairship.com'}}, 'no': {'app_defined': {'foo': 'bar'}}}}}
>>> notification(open_platform={'sms': sms_overrides})
- urbanairship.push.payload.wns_payload(alert: str | None = None, toast: str | None = None, tile: str | None = None, badge: str | None = None) Dict[str, Any]
WNS specific platform override payload.
Must include exactly one of
alert
,toast
,tile
, orbadge
.
- urbanairship.push.payload.message(title: str, body: str, content_type: str | None = None, content_encoding: str | None = None, extra: Dict[str, Any] | None = None, expiry: str | int | None = None, icons: Dict | None = None, options: Dict[Any, Any] | None = None, campaigns: Dict[str, Any] | None = None) Dict[str, Any]
Rich push message payload creation.
- Parameters:
title – Required, string
body – Required, string
content_type – Optional, MIME type of the body
content_encoding – Optional, encoding of the data in body, e.g.
utf-8
.extra – Optional, dictionary of string values.
expiry – time when message will delete from Inbox (UTC time or in seconds)
icons – Optional JSON dictionary of string key and value pairs. Values must be URIs or URLs to the icon resources
options – Optional JSON dictionary of key and value pairs specifying non-payload options
campaigns – Optional dictionary containing list of 1 to 10 ‘categories’
- urbanairship.push.payload.in_app(alert: str, display_type: str, expiry: str | None = None, display: Dict[str, Any] | None = None, actions: Dict[str, Any] | None = None, interactive: Dict[str, Any] | None = None, extra: Dict[str, Any] | None = None) Dict[str, Any]
In-App push message payload creation.
- Parameters:
alert – Required, string
display_type – Required, String. List of valid display_type attributes.
expiry – Optional, String specifying an expiry value.
display – Optional, A dictionary specifying the display appearance of the in-app message.
actions – Optional, Used to perform a defined task.
interactive – Optional, A dictionary with two attributes – “type” and “button_actions”, as generated by interactive().
extra – Optional, Object.
- urbanairship.push.payload.options(expiry: str | int | None = None, bypass_frequency_limits: bool | None = None, bypass_holdout_groups: bool | None = None, no_throttle: bool | None = None, omit_from_activity_log: bool | None = None, personalization: bool | None = None, redact_payload: bool | None = None) Dict[str, Any]
Options payload creation.
- Parameters:
expiry – If true, Delivery expiration, as either absolute ISO UTC timestamp, or number of seconds from now.
bypass_frequency_limits – If true, the push ignores any message limits that would otherwise apply to your message.
bypass_holdout_groups – Indicates whether users that are part of a holdout group should be included in a push if a holdout experiment is active at send time.
no_throttle – If true, the push will ignore global throttling rates that have been configured for the application.
omit_from_activity_log – If true, the push is omitted from the Activity Log.
personalization – If true, enables Handlebars-style template syntax for eligible fields in a notification or message center objects.
redact_payload – If true, the push payload will not appear in Airship’s logs.
- Returns:
A dictionary representing the options payload.
- urbanairship.push.payload.campaigns(categories: Dict | List | None = None) Dict[str, Any]
Campaigns payload creation.
>>> campaigns(categories=['kittens', 'tacos', 'horse_racing']) {'categories': ['kittens', 'tacos', 'horse_racing']}
- urbanairship.push.payload.actions(add_tag: str | List[str] | None = None, remove_tag: str | List[str] | None = None, open_: Dict[str, Any] | None = None, share: str | None = None, app_defined: Dict[str, Any] | None = None) Dict[str, Any]
Actions payload creation.
- Parameters:
add_tag – Adds a tag to the device. Expects a string or a list of strings.
remove_tag – Removes a tag from the device. Expects a string or a list of strings.
open – Opens type url, deep_link or landing_page. Expects a dictionary with “type” and “content”. See API docs for more information.
share – Sends a share notification. Expects a string.
app_defined – Sends application defined actions. Expects a dictionary.
>>> actions(add_tag='new_tag', remove_tag='old_tag', ... open_={'type': 'url', ... 'content': 'http://www.urbanairship.com'}) {'open': {'type': 'url', 'content': 'http://www.urbanairship.com}, 'add_tag': 'new_tag', 'remove_tag': 'old_tag'}
- urbanairship.push.payload.interactive(type: str | None = None, button_actions: Dict[str, Any] | None = None) Dict[str, Any]
Interactive payload creation.
- Parameters:
type – The name of one of the predefined interactive notifications or a custom defined interactive notification. Expects a string.
button_actions – A button_actions object that maps button IDs to valid action objects. Expects a dictionary.
- urbanairship.push.payload.wearable(background_image: str | None = None, extra_pages: List[str] | None = None, interactive: Dict[str, Any] | None = None) Dict[str, Any]
Android wearable payload builder.
- Parameters:
background_image – Optional string. A URL that specifies the background image to display on a wearable device.
extra_pages – Optional array of objects.
interactive – Optional object. Override the interactive notification payload for the wearable device.
- urbanairship.push.payload.public_notification(title: str | None = None, alert: str | None = None, summary: str | None = None) Dict[str, Any]
Android L public notification payload builder.
- Parameters:
title – Optional string. The notification title.
alert – Optional string. The notification alert.
summary – Optional string. The notification summary.
- urbanairship.push.payload.style(style_type: str | None, content: str | List[str] | None, title: str | None = None, summary: str | None = None) Dict[str, Any]
Android/Amazon style builder.
- Parameters:
style_type – String. Must be one of “big_text”, “big_picture”, or “inbox”.
content – String or array of strings. Content of the style object. If style_type is set to “inbox”, this will be an array of strings. Otherwise, it will be a single string.
title – Optional string. Override the notification.
summary – Optional string. Override the summary of the notification.
- urbanairship.push.payload.media_attachment(url: str, content: Dict[str, Any] | None = None, options: Dict[str, Any] | None = None) Dict[str, Any]
iOS media_attachment builder.
- Parameters:
url – String. Specifies the URL to be downloaded by the UA Media Attachment extension.
content – Optional dictionary. Describes portions of the notification that should be modified if the media attachment succeeds. See
content()
.options – Optional dictionary. Describes how to display the resource given by the URL. See
options()
.
- urbanairship.push.payload.content(title: str | None = None, subtitle: str | None = None, body: str | None = None) Dict[str, Any]
iOS content builder. Each argument describes the portions of the notification that should be modified if the media_attachment succeeds.
- Parameters:
title – String.
subtitle – String.
body – String.
- urbanairship.push.payload.crop(x: float | None = None, y: float | None = None, width: float | None = None, height: float | None = None) Dict[str, Any]
iOS crop builder.
- Parameters:
x – Optional float. The X offset where the crop begins.
y – Optional float. The Y offset where the crop begins.
width – Optional float. The width of the final crop.
height – Optional float. The height of the final crop.
- urbanairship.push.payload.localization(language: str | None = None, country: str | None = None, notification: Dict[str, Any] | None = None, message: Dict[str, Any] | None = None, in_app: Dict[str, Any] | None = None) Dict[str, Any]
Localized content for a push notification, message center message, or in app message. Localization must include at least one of language or country. Localization content must include at least one of notification, message, or in_app.
- Parameters:
language – Optional. The ISO 639-1 two-letter language code for this localization.
country – Optional. The ISO 3166-2 two-letter country code for this localization.
notification – Optional. An urbanairship.notification containing localized push notification content.
message – Optional. An urbanairship.message containing localized message center content.
in_app – Optional. An urbanarship.in_app containing localized in_app content.
- urbanairship.push.payload.live_activity(name: str, event: LiveActivityEvent, alert: Dict[str, Any] | None = None, priority: int | None = None, content_state: Dict[str, Any] | None = None, relevance_score: float | None = None, stale_date: int | None = None, dismissal_date: int | None = None, timestamp: int | None = None) Dict[str, Any]
Generates the Live Activity payload.
- Parameters:
name – The name of the Live Activity.
event – The event type. Expected values: “update” or “end”.
alert – The alert object. Expects a dictionary with keys “body”, “sound”, and “title”.
priority – The APNs priority. Valid values: 5 or 10.
content_state – A dictionary of string keys to arbitrary JSON values that represents the content state to be updated by the Live Activity notification.
dismissal_date – Optional epoch timestamp for ending the Live Activity.
relevance_score – Optional relevance score.
stale_date – Optional timestamp indicating when the Live Activity becomes outdated.
timestamp – Optional timestamp for the Live Activity update.
- Returns:
A dictionary representing the Live Activity payload.
- urbanairship.push.payload.live_update(name: str, event: LiveUpdateEvent, content_state: Dict[str, Any] | None = None, type_: str | None = None, dismissal_date: int | None = None, timestamp: int | None = None) Dict[str, Any]
Generates the Live Update payload.
- Parameters:
name – The name of the Live Update to target. When event is “update” or “end”, the audience is limited to devices that have a Live Update started for the specified name.
event – The event type for the Live Update. Expected values are members of the LiveUpdateEvent enum: “start”, “update”, or “end”.
content_state – A dictionary of string keys to arbitrary JSON values that represents the content state to be updated by the Live Update notification.
type – Used to map Live Update events to the corresponding handler in your app. This is required to identify what kind of live update is being sent, so the application knows how to handle it.
dismissal_date – Optional epoch timestamp for ending the Live Update.
timestamp – Optional timestamp for the Live Update update.
- Returns:
A dictionary representing the Live Update payload.
Device Types
In addition to specifying the audience, you must specify the device types you wish to target with one or more strings:
push.device_types = ua.device_types('ios')
push.device_types = ua.device_types('android', 'ios', 'web')
- urbanairship.push.payload.device_types(*types: Any) List[str]
Create a device type specifier.
>>> device_types('ios', 'wns') ['ios', 'wns'] >>> device_types('ios', 'symbian') Traceback (most recent call last): ... ValueError: Invalid device type 'symbian'
Immediate Delivery
Once you have set the audience
, notification
, and device_types
attributes, the notification is ready for delivery. Use Push.send()
to send immediately.
push.send()
If the request is unsuccessful, an AirshipFailure
exception
will be raised.
If the connection is unsuccessful, an ConnectionFailure
exception
will be raised.
- class urbanairship.push.core.Push(airship: BaseClient)
A push notification. Set audience, message, etc, and send.
- validate() PushResponse
Test push payload against the validate endpoint. No sends will result from this method being called. This method is otherwise identical to the send method.
- send() PushResponse
Send the notification.
- Returns:
PushResponse
object withpush_ids
and other response data.- Raises:
AirshipFailure – Request failed.
Unauthorized – Authentication failed.
ValueError – Required keys missing or incorrect values included.
ConnectionFailure – Connection failed.
Scheduled Delivery
Schedule notifications for later delivery.
Examples can be found in the documentation here.
- class urbanairship.push.core.ScheduledPush(airship: BaseClient)
A scheduled push notification. Set schedule, push, and send.
- send() PushResponse
Schedule the notification
- Returns:
PushResponse
object withschedule_url
and other response data.- Raises:
AirshipFailure – Request failed.
Unauthorized – Authentication failed.
ConnectionFailure – Connection failed.
- validate() PushResponse
Validates a scheduled push for sending
- pause() Response
Pause a recurring schedule
- resume() Response
Resume a paused recurring schedule
- cancel() Response
Cancel a previously scheduled notification.
Scheduled Time Builders
- urbanairship.push.schedule.scheduled_time(timestamp: datetime) Dict[str, Any]
Specify a time for the delivery of this push.
- Parameters:
timestamp – A
datetime.datetime
object.
- urbanairship.push.schedule.local_scheduled_time(timestamp: datetime) Dict[str, Any]
Specify a time for the delivery of this push in device local time.
- Parameters:
timestamp – A
datetime.datetime
object.
- urbanairship.push.schedule.best_time(timestamp: datetime) Dict[str, Any]
Specify a date to send the push at the best time per-device. Only YYYY_MM_DD are needed. Hour/minute/second information is discarded.
- Parameters:
timestamp – A
datetime.datetime
object.
- urbanairship.push.schedule.recurring_schedule(count: int, type: str, end_time: datetime | None = None, days_of_week: List[str] | None = None, exclusions: List[Dict[str, Any]] | None = None, paused: bool | None = False) Dict[str, Any]
Sets the cadence, end time, and excluded times for a recurring scheduled message.
- Parameters:
count – Required. The frequency of messaging corresponding to the type. For example, a count of 2 results in a message every 2 hours, days, weeks, months, etc based on the type.
type – Required. The unit of measurement for the cadence. Possible values: hourly, daily, monthly, yearly.
days_of_week – Required when type is weekly. The days of the week on which Airship can send your message.
end_time – Optional. A datetime.datetime object representing when the scheduled send will end and stop sending messages.
exclusions – Optional. A list of urbanaiship.schedule_exclusion defining times in which Airship will not send your message.
paused – Optional. A boolean value respesnting the paused state of the scheduled message.
- urbanairship.push.schedule.schedule_exclusion(start_hour: int | None = None, end_hour: int | None = None, start_date: datetime | None = None, end_date: datetime | None = None, days_of_week: List[str] | None = None) Dict[str, Any]
Date-time ranges when messages are not sent. at least one of start_hour and end_hour, start_date and end_date, or days_of_week must be included. All dates and times are inclusive.
- Parameters:
start_hour – Optional. An integer 0-23 representing the UTC hour to start exclusion.
end_hour – Optional. An integer 0-23 representing the UTC hour to stop exclusion. Must be included if start_hour is used.
start_date – Optional. A datetime.datetime object representing the UTC date to start exclusion. Hour/minute/seconds will be excluded.
start_date – Optional. A datetime.datetime object representing the UTC date to stop exclusion. Hour/minute/seconds will be excluded. Must be included if start_date is used.
days_of_week – Optional. A list of the days of the week to exclude on. Possible values: monday, tuesday, wednesday, thursday, friday, saturday, sunday
List Scheduled Notifications
- class urbanairship.push.schedule.ScheduledList(airship: BaseClient, limit: int | None = None)
Iterator for listing all scheduled messages.
- Parameters:
limit – Number of entries to fetch in a paginated request.
- Returns:
Each
next
returns aScheduledPush
object.
Personalization
Send a notification with personalized content.
Examples can be found in the schedules documentation here.
- class urbanairship.push.core.TemplatePush(airship)
A personalized push notification. Set details and send.
- send() PushResponse
Send the personalized notification.
- Returns:
PushResponse
object withpush_ids
and other response data.- Raises:
AirshipFailure – Request failed.
Unauthorized – Authentication failed.
ConnectionFailure – Connection failed.
Template
- class urbanairship.push.template.Template(airship: BaseClient, name: str | None = None, description: str | None = None, variables: List[Dict[str, Any]] | None = None, push: Type[Push] | None = None)
Information object for a template.
- Parameters:
template_id – UUID; the ID of this template, set automatically.
created_at – UTC datetime when the template was created.
modified_at – UTC datetime when the template was last modified.
last_used – UTC datetime when the template was last used for a push notification. Will be set to ‘UNKNOWN’ if never used.
name – Required, name of the template, set during creation/modification.
description – Optional, description of the template, set during creation/modification.
variables – Required, an array of Template Variable Objects.
push – Optional, a push specification object, as defined by the Push Object specification, but does not include
audience
ordevice_types
since those are set when push messages are sent. Message Centermessage
is also not supported in Templates at this time.
- create() Response
Create a notification template with the API.
- Raises:
AirshipFailure – Request failed.
Unauthorized – Authentication failed.
ConnectionFailure – Connection failed.
- update(template_id: str | None = None) Response
Update a template with the API.
- Raises:
AirshipFailure – Request failed.
Unauthorized – Authentication failed.
ConnectionFailure – Connection failed.
- delete(template_id: str | None = None) Response
Delete a previously created template.
- Raises:
AirshipFailure – Request failed.
Unauthorized – Authentication failed.
ConnectionFailure – Connection failed.
Template Lookup
- class urbanairship.push.template.Template(airship: BaseClient, name: str | None = None, description: str | None = None, variables: List[Dict[str, Any]] | None = None, push: Type[Push] | None = None)
Information object for a template.
- Parameters:
template_id – UUID; the ID of this template, set automatically.
created_at – UTC datetime when the template was created.
modified_at – UTC datetime when the template was last modified.
last_used – UTC datetime when the template was last used for a push notification. Will be set to ‘UNKNOWN’ if never used.
name – Required, name of the template, set during creation/modification.
description – Optional, description of the template, set during creation/modification.
variables –
Required, an array of Template Variable Objects.
push –
Optional, a push specification object, as defined by the Push Object specification, but does not include
audience
ordevice_types
since those are set when push messages are sent. Message Centermessage
is also not supported in Templates at this time.
- lookup(template_id)
Fetch metadata from a template ID
Template Listing
- class urbanairship.push.template.TemplateList(airship, limit=None)
Iterator for listing all templates for this application.
- Parameters:
limit – Number of entries to fetch in each page request.
- Returns:
Each
next
returns aTemplate
object.
Merge Data
- urbanairship.push.template.merge_data(template_id: str, substitutions: Dict[str, Any]) Dict[str, Any]
Template push merge_data creation.
- Parameters:
template_id – Required, UUID.
substitutions – Required, dictionary of template variables and their substitutions, e.g. {“FIRST_NAME”: “Bob”, “LAST_NAME”: “Smith”}
Create and Send
Simultaneously send a notification to an audience of SMS, email, or open channel addresses and register channels for new addresses in your audience.
Examples can be found in the create and send documentation here.
- class urbanairship.push.core.CreateAndSendPush(airship: BaseClient, channels: List)
Creates and sends to email, sms or open channels. Channel ids are created but not returned by this request. Use lookup/listing endpoints to find channel_id values. Opt-in date attributes are required on Sms and Email objects passed in.
- Parameters:
airship – Required. An urbanairship.Airship object instantiated with master authentication.
channels – Required. A list of Sms, Email or OpenChannel objects. channels may only be of one type and must match the single value for CreateAndSend.device_types.
- send() PushResponse
Send the notification.
- Returns:
PushResponse
object withpush_ids
and other response data.- Raises:
AirshipFailure – Request failed.
Unauthorized – Authentication failed.
ValueError – Required keys missing or incorrect values included.
ConnectionFailure – Connection failed.
Automation
With the automation pipelines endpoint you can manage automations for an Airship project. Pipelines define the behavior to be triggered on user-defined events. For more information, see the documentation on Automation.
- class urbanairship.automation.core.Automation(airship: BaseClient)
An object for getting and creating automations.
- Parameters:
airship – An urbanairship.Airship instance, instantiated with the key corresponding to the airship project you wish to use.
- create(pipelines: Pipeline | List[Pipeline]) Response
Create an automation with one or more Pipeline payloads
- Parameters:
pipelines – A single Pipeline payload or list of Pipeline payloads
- validate(pipelines: Pipeline | List[Pipeline]) Response
Validate a Pipeline payloads
- Parameters:
pipelines – A single Pipeline payload or list of Pipeline payloads
- update(pipeline_id: str, pipeline: Pipeline) Response
Update an existing Automation Pipeline
- Parameters:
pipeline_id – A Pipeline ID
pipeline – Full Pipeline payload; partial updates are not supported
- delete(pipeline_id: str) Response
Delete an existing Automation Pipeline
- Parameters:
pipeline_id – A Pipeline ID
- lookup(pipeline_id: str) Response
Lookup an Automation Pipeline
- Parameters:
pipeline_id – A Pipeline ID
- list_automations(limit: int | None = None, enabled: bool = False) Response
List active Automations
- Parameters:
limit – Optional, maximum pipelines to return
enabled – Optional, boolean limiter for results to only enabled Pipelines
- list_deleted_automations(start: str | None = None) Response
List deleted Automation Pipelines
- Parameters:
start – Optional starting timestamp for limiting results in ISO-8601 format
Pipeline
A pipeline object encapsulates the complete set of objects that define an Automation pipeline: Triggers, Outcomes, and metadata.
- class urbanairship.automation.pipeline.Pipeline(enabled: bool | None = None, name: str | None = None, historical_trigger: Dict | None = None, timing: Dict | None = None, immediate_trigger: Dict | List | None = None, cancellation_trigger: Dict | List | None = None, constraint: Dict | List | None = None, condition: Dict | List | None = None, outcome: Dict | List | None = None)
Pipeline object encapsulates the complete set of objects that define an Automation pipeline
Create Pipeline object for Automation payload
- Parameters:
enabled – boolean value determines active status of the pipeline
outcome – a push object to be sent as outcome of the pipeline
name – [optional] descriptive string for pipeline identification
immediate_trigger – [optional] single event identifier or list of event identifiers that trigger the outcome of the pipeline - trigger list can be combination of simple and compound identifiers
cancellation_trigger – [optional] single event identifier or list of event identifiers that trigger cancellation of the pipeline outcome - can be combination of simple and compound identifiers
historical_trigger – [optional] single or list of historical trigger objects that currently match only inactive triggers
constraint – [optional] single or list of constraint objects that limit the number of pushes sent to a device in a given time period
condition – [optional] one or a list of condition sets with an and/or operator for combining the conditions
timing – [optional] a timing object defining times allowable for outcome delivery
- property payload: Dict
JSON serialized Pipeline object
- append_outcome_object(push_object: Dict) None
Append outcome object to current Pipeline outcome
- Parameters:
push_object – A push object that will be an outcome for this Pipeline object
- remove_outcome_object(push_object: Dict) None
Remove outcome push object from current outcome
- Parameters:
push_object – A push object to remove from the outcome of this Pipeline object
- append_immediate_trigger_identifier(event_identifier: Dict) None
Append event identifier to immediate triggers for Pipeline
- Parameters:
event_identifier – Event identifier object
- remove_immediate_trigger_identifier(event_identifier: Dict) None
Remove event identifier to immediate triggers for Pipeline
- Parameters:
event_identifier – Even identifier object
- append_cancellation_trigger_identifier(event_identifier: Dict) None
Append event identifier to immediate triggers for Pipeline
- Parameters:
event_identifier – Event identifier object
- remove_cancellation_trigger_identifier(event_identifier: Dict) None
Remove event identifier from immediate triggers for Pipeline
- Parameters:
event_identifier – Event identifier object
- append_constraint_object(constraint_object: Dict) None
Append constraint object to constraint for Pipeline
- Parameters:
constraint_object – Constraint object to append to Pipeline constraint
- append_condition_set(condition_set: Dict) None
Append condition set to Pipeline condition
- Parameters:
condition_set – One or list of condition sets
- remove_condition_set(condition_set: Dict) None
Remove condition set from Pipeline condition
- Parameters:
condition_set – One or list of condition sets
A/B Tests
An A/B test is a set of distinct push notification variants sent to subsets of an audience. You can create up to 26 notification variants and send each variant to an audience subset
Examples can be found in the A/B Tests documentation here.
- class urbanairship.experiments.core.ABTest(airship: BaseClient)
- list_experiments() Response
List experiments, sorted by created_at date/time from newest to oldest
- Parameters:
limit – Positive maximum number of elements to return per page. Default limit is 10. Max: 100 and Min: 1.
- create(experiment: Experiment) Response
Create an experiment
- list_scheduled_experiment() Response
List scheduled experiments in order, from closest to the current date-time to farthest
- delete(experiment_id: str) Response
Delete a scheduled experiment. You can only delete experiments before they start
- Parameters:
experiment_id – The unique identifier of the experiment, type string
- validate(experiment: Experiment) Response
Accepts the same range of payloads as /api/experiments, but only parses and validates the payload without creating the experiment. An experiment may validate and still fail to be delivered. For example, you may have a valid experiment with no devices in your audience.
- Parameters:
experiment – Body of the experiment you want to validate
- lookup(experiment_id: str) Response
Look up an experiment (A/B Test)
- Parameters:
experiment_id – The unique identifier of the experiment, type string
Experiment
- class urbanairship.experiments.experiment.Experiment(audience: Dict[str, Any], device_types: List[str], variants: List[Variant], name: str | None = None, description: str | None = None, weight: int | None = None, campaigns: Dict[str, Any] | None = None, control: float | None = None)
An experiment object describes an A/B test, including the audience and variant portions.
- Parameters:
audience – [required] The audience for the experiment
device_types – A list containing one or more strings identifying targeted platforms. Accepted platforms are ios, android, amazon, wns, web, sms, email, and open::<open_platform_name>
variants – [required] The variants for the experiment. An experiment must have at least 1 variant and no more than 26.
name – [optional] A name for the experiment
description – [optional] A description of the experiment
campaigns – [optional] Campaigns object that will be applied to resulting pushes
control – [optional] The proportional subset of the audience that will not receive a push
- property payload: Dict[str, Any]
JSON serialized experiment object
Variant
- class urbanairship.experiments.variant.Variant(push, description=None, name=None, schedule=None, weight=None)
The variants for the experiment. An experiment must have at least 1 variant and no more than 26.
- Parameters:
push – [required] A push object without audience and device_types fields. These two fields are not allowed because they are already defined in the experiment object
description – [optional] A description of the variant.
name – [optional] A name for the variant unless either message or in_app is present. You can provide an alert and any platform overrides that apply to the device_type platforms you specify.
schedule – [optional] The time when the push notification should be sent
weight – [optional] The proportion of the audience that will receive this variant. Defaults to 1.