Skip to content

Commit 69c03e3

Browse files
authored
FCM multicast snippets (#321)
1 parent a79ee97 commit 69c03e3

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

snippets/messaging/cloud_messaging.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,3 +220,72 @@ def unsubscribe_from_topic():
220220
# for the contents of response.
221221
print(response.success_count, 'tokens were unsubscribed successfully')
222222
# [END unsubscribe]
223+
224+
225+
def send_all():
226+
registration_token = 'YOUR_REGISTRATION_TOKEN'
227+
# [START send_all]
228+
# Create a list containing up to 100 messages.
229+
messages = [
230+
messaging.Message(
231+
notification=messaging.Notification('Price drop', '5% off all electronics'),
232+
token=registration_token,
233+
),
234+
# ...
235+
messaging.Message(
236+
notification=messaging.Notification('Price drop', '2% off all books'),
237+
topic='readers-club',
238+
),
239+
]
240+
241+
response = messaging.send_all(messages)
242+
# See the BatchResponse reference documentation
243+
# for the contents of response.
244+
print('{0} messages were sent successfully'.format(response.success_count))
245+
# [END send_all]
246+
247+
248+
def send_multicast():
249+
# [START send_multicast]
250+
# Create a list containing up to 100 registration tokens.
251+
# These registration tokens come from the client FCM SDKs.
252+
registration_tokens = [
253+
'YOUR_REGISTRATION_TOKEN_1',
254+
# ...
255+
'YOUR_REGISTRATION_TOKEN_N',
256+
]
257+
258+
message = messaging.MulticastMessage(
259+
data={'score': '850', 'time': '2:45'},
260+
tokens=registration_tokens,
261+
)
262+
response = messaging.send_multicast(message)
263+
# See the BatchResponse reference documentation
264+
# for the contents of response.
265+
print('{0} messages were sent successfully'.format(response.success_count))
266+
# [END send_multicast]
267+
268+
269+
def send_multicast_and_handle_errors():
270+
# [START send_multicast_error]
271+
# These registration tokens come from the client FCM SDKs.
272+
registration_tokens = [
273+
'YOUR_REGISTRATION_TOKEN_1',
274+
# ...
275+
'YOUR_REGISTRATION_TOKEN_N',
276+
]
277+
278+
message = messaging.MulticastMessage(
279+
data={'score': '850', 'time': '2:45'},
280+
tokens=registration_tokens,
281+
)
282+
response = messaging.send_multicast(message)
283+
if response.failure_count > 0:
284+
responses = response.responses
285+
failed_tokens = []
286+
for idx, resp in enumerate(responses):
287+
if not resp.success:
288+
# The order of responses corresponds to the order of the registration tokens.
289+
failed_tokens.append(registration_tokens[idx])
290+
print('List of tokens that caused failures: {0}'.format(failed_tokens))
291+
# [END send_multicast_error]

0 commit comments

Comments
 (0)