FCM – send push notifications using Python

What is FCM ?

FCM – Firebase Cloud Messaging is a cross-platform  ( Android, iOS and Chrome ) messaging solution that lets you reliably deliver messages at no cost. FCM is best suited if you want to send push notification to your app which you built to run on Android and iOS. The advantage you get is you don’t have to separately deal with GCM (Google Cloud Messaging deprecated now) and Apple’s APNS. You hand over your notification message to FCM and FCM takes care of communicating with apple’s APNS and Android messaging servers to reliably deliver those messages.

Using FCM we can send message to single device or multiple devices.  There are two different types of messages, notification and data. Notification messages include JSON keys that are understood and interpreted by phone’s operating system. If you want to include customized app specific JSON keys use data message. You can combine both notification and data JSON objects in single message. You can also send messages with different priority.

Note : – You need to set priority  to high  if you want phone to wake up and show notification on screen

Sending message with Python

We can use PyFCM to send messages via FCM. PyFCM is good for synchronous ( blocking ) python. We will discuss non-blocking option in next paragraph.

Install PyFCM using following command

pip install pyfcm

The following code will send a push notification to

from pyfcm import FCMNotification

push_service = FCMNotification(api_key="<api-key>")

# OR initialize with proxies

proxy_dict = {
          "http"  : "http://127.0.0.1",
          "https" : "http://127.0.0.1",
        }
push_service = FCMNotification(api_key="<api-key>", proxy_dict=proxy_dict)

# Your api-key can be gotten from:  https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging

registration_id = "<device registration_id>"
message_title = "Uber update"
message_body = "Hi john, your customized news for today is ready"
result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)

print result
 
# Send to multiple devices by passing a list of ids.
registration_ids = ["<device registration_id 1>", "<device registration_id 2>", ...]
message_title = "Uber update"
message_body = "Hope you're having fun this weekend, don't forget to check today's news"
result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body)

print result

So, the PyFCM API is the pretty straight forward to use.

Sending FCM push notification using Twisted

PyFCM discussed in above paragraph is good enough if you want to send messages in blocking fashion. If you have to send high number of concurrent messages then using Twisted is a good option.

Twisted Matrix

Network operations performed using twisted library don’t block. Thus it’s a good choice when network concurrency is required by program. We can use txFCM library to send FCM messages using twisted

Install txFCM using following command

pip install txfcm

Following code send FCM message using txFCM

from txfcm import TXFCMNotification
from twisted.internet import reactor

push_service = TXFCMNotification(api_key="<api-key>")

# Your api-key can be gotten from:  https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging
# Send to multiple devices by passing a list of ids.
registration_ids = ["<device registration_id 1>", "<device registration_id 2>", ...]
message_title = "Uber update"
message_body = "Hope you're having fun this weekend, don't forget to check today's news"
df = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body)

def got_result(result):
    print result

df.addBoth(got_result)
reactor.run()

txFCM is built on top of PyFCM so all the API call that are available in PyFCM are also available in txFCM.

16 thoughts on “FCM – send push notifications using Python

  1. Warning: Attempt to read property "entry" on string in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Trying to access array offset on value of type null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Attempt to read property "displayName" on null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 191
    Krasen Dimkov says:

    Are these libraries compatible with Google app engine

  2. cosmosjs – hi~ jQuery, javascript, ajax, json, html, css, html5, css3, mobileweb, photography, digital camera, 사진찍기, 홈페이지제작, 모바일웹 사이트제작, 웹 퍼블리셔, 카메라 등에 관심이 있습니다.
    jseeee says:

    Hi~
    I can’t import pyfcm on python3.

      1. Warning: Attempt to read property "entry" on string in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Trying to access array offset on value of type null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Attempt to read property "displayName" on null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 191
        priyanka shivhare says:

        i m getting mismatch sender id error while sending the push notification to android

  3. Warning: Attempt to read property "entry" on string in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Trying to access array offset on value of type null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Attempt to read property "displayName" on null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 191
    Alex Tichner says:

    So I’m trying to use the PyFCM but I can’t get the registration_id. I don’t even know how I would get it.

    1. Hi Alex,

      Using following code-snippets, you can retrieve device token-id

      For android
      String refreshedToken = FirebaseInstanceId.getInstance().getToken().

      For Object-c
      NSString *refreshedToken = [[FIRInstanceID instanceID] token];

      For swift
      let token = FIRInstanceID.instanceID().token()!

      Following are detailed docs to setup FCM at client

      Android – https://firebase.google.com/docs/cloud-messaging/android/client

      iOS – https://firebase.google.com/docs/notifications/ios/console-device

      With help of fcm console and this token-id, you can send test-notifications to your device. If you want to send notifications from your server using pyFCM, you need to deliver this token-id to server. Ideally at time of authentication with your server, you can do it.

      1. Warning: Attempt to read property "entry" on string in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Trying to access array offset on value of type null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Attempt to read property "displayName" on null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 191
        Budi says:

        Hi how can I add the code following registration_id to pyfcm ?

        I have some android apps, my push receiver build with ionic and the trigger build with pyfcm, what should I do with registration_id ? thanks.

        1. Hi Budhi, in article it is already mentioned how to use `registeration_id` aka `Registration Token` ( in fcm lingo ) –

          “`result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)
          print result“`

  4. Warning: Attempt to read property "entry" on string in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Trying to access array offset on value of type null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Attempt to read property "displayName" on null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 191
    Giridhar says:

    I have webapp in web2py, it sends email to user at some point at same time i want to sendandroid notification fro that user. How can i do it???

    1. Hi Giridhar,

      You can use original PyFCM library for it. If you want to do it async way, you can use twisted service and txFCM.

  5. Warning: Attempt to read property "entry" on string in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Trying to access array offset on value of type null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Attempt to read property "displayName" on null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 191
    izzy says:

    Hi,

    I understand the registration_id for android/iOS devices, how do I get the id for google chrome extension/websites.

  6. Warning: Attempt to read property "entry" on string in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Trying to access array offset on value of type null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Attempt to read property "displayName" on null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 191
    SAISWARUP SAHU says:

    Hello,
    I am unable to install this one on my system.can you please help me out.It’s showing the Error.

  7. Warning: Attempt to read property "entry" on string in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Trying to access array offset on value of type null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Attempt to read property "displayName" on null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 191
    Devansh says:

    hi
    i get this error HTTPSConnectionPool(host=’fcm.googleapis.com’, port=443): Max retries exceeded with url: /fcm/send (Caused by ProxyError(‘Cannot connect to proxy.’, NewConnectionError(‘: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it’,)))

  8. Warning: Attempt to read property "entry" on string in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Trying to access array offset on value of type null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 190 Warning: Attempt to read property "displayName" on null in /var/app/current/wp-content/plugins/jetpack/modules/gravatar-hovercards.php on line 191
    amiaogong says:

    I has a test server run linux, can I use c or c++ code to call some API to send message use FCM? Does there has a C or C++ API about FCM?
    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *