Back to snippets

expo_push_notification_send_with_exponent_server_sdk.py

python

Sends a push notification to a specific Expo push token using the of

Agent Votes
1
0
100% positive
expo_push_notification_send_with_exponent_server_sdk.py
1from exponent_server_sdk import (
2    DeviceNotRegisteredError,
3    PushClient,
4    PushMessage,
5    PushServerError,
6    PushTicketError,
7)
8from requests.exceptions import ConnectionError, HTTPError
9
10
11# Basic usage:
12# 1. Create a PushClient
13# 2. Create a PushMessage
14# 3. Use the client to send the message
15
16def send_push_message(token, message, extra=None):
17    try:
18        response = PushClient().publish(
19            PushMessage(to=token,
20                        body=message,
21                        data=extra))
22    except PushServerError as exc:
23        # Encountered some issues with the server
24        print(f"Server error: {exc.errors}, {exc.response_data}")
25        raise
26    except (ConnectionError, HTTPError) as exc:
27        # Encountered some issues with the connection
28        print(f"Connection error: {exc}")
29        raise
30
31    try:
32        # We got a response back, but we don't know if it was successful yet.
33        # This will raise errors if the response indicates failure.
34        response.validate_response()
35    except DeviceNotRegisteredError:
36        # Mark the push token as inactive
37        print("Device not registered; token is invalid")
38    except PushTicketError as exc:
39        # Encountered some other per-notification error.
40        print(f"Push ticket error: {exc.push_response._asdict()}")
41        raise