Esempio n. 1
0
def price_alert_appeared(best_product_list):
    if len(best_product_list) > 0:
        if SHOW_PRICE_ALERT_IN_CMD:
            print("\n[" + Fore.MAGENTA + "PRICE ALERT!!" + Fore.RESET + "]")
            for product in best_product_list:
                print(product.get_name() + " " + Fore.GREEN +
                      str(product.get_price()) + product.get_currency() + " " +
                      Fore.RESET +
                      (product.get_url()[:width] + '...' if
                       len(product.get_url()) > width else product.get_url()))

        if FIREBASE_INTEGRATION and FCM_ENABLED and len(FIREBASE_TOKENS) > 0:
            try:
                for product in best_product_list:
                    mess = messaging.MulticastMessage(data={
                        "name":
                        product.get_name(),
                        "price":
                        str(product.get_price()),
                        "price_alert":
                        str(product.get_price_alert()),
                        "currency":
                        str(product.get_currency()),
                        "product_id":
                        str(products_names.index(product.get_name())),
                        "url":
                        product.get_url()
                    },
                                                      tokens=FIREBASE_TOKENS)
                    messaging.send_multicast(mess)
            except Exception:
                # sometimes firebase needs to be initialized again
                setFirebaseReferences()
                # again try to send messages
                for product in best_product_list:
                    mess = messaging.MulticastMessage(data={
                        "name":
                        product.get_name(),
                        "price":
                        str(product.get_price()),
                        "price_alert":
                        str(product.get_price_alert()),
                        "currency":
                        str(product.get_currency()),
                        "product_id":
                        str(products_names.index(product.get_name())),
                        "url":
                        product.get_url()
                    },
                                                      tokens=FIREBASE_TOKENS)
                    messaging.send_multicast(mess)
def _send_android_notification(token_shops: dict, coupon_description: str):
    if not token_shops:
        return

    body = coupon_description or "Смотри подробнее в приложении!"

    android_params = messaging.AndroidConfig(
        ttl=datetime.timedelta(seconds=3600), priority='high')

    failed_tokens = []

    for chunk in chunks(list(token_shops.items()), 500):
        registration_tokens = []

        for token, shops in chunk:
            registration_tokens.append(token)

            notification = messaging.Notification(
                title=f"Новый купон в {', '.join(shops)}🔥", body=body)

            multicast_message = messaging.MulticastMessage(
                notification=notification,
                android=android_params,
                tokens=registration_tokens,
            )

        batch_failed_tokens = _send_firebase_request(registration_tokens,
                                                     multicast_message)
        failed_tokens.extend(batch_failed_tokens)
        batch_failed_tokens = []

    users.delete_tokens(failed_tokens, is_ios=False)
Esempio n. 3
0
def send_notif_multiple(registration_tokens=[],
                        data={},
                        title="Notification Order",
                        body="hey you, you have some order "):
    if len(registration_tokens) == 0:
        return

    message = messaging.MulticastMessage(
        # for id user divice
        tokens=registration_tokens,
        # for data payload
        data=data,

        # notification body
        notification=messaging.Notification(title=title, body=body),

        # android notification
        android=messaging.AndroidConfig(
            ttl=datetime.timedelta(seconds=3600),
            notification=messaging.AndroidNotification(title=title,
                                                       body=body,
                                                       color='#f45342')),

        # apns
        apns=messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42), ), ),
    )
    response = messaging.send_multicast(message, app=firebase)
    # See the BatchResponse reference documentation
    # for the contents of response.
    return '{0} messages were sent successfully'.format(response.success_count)
Esempio n. 4
0
def notification_send(req, mentors):
    sender = req.student
    message = req.problem_title
    type = req.category
    registration_tokens = []
    for mentor in mentors:
        print(mentor)
        registration_tokens.append(Token.objects.get(user=mentor))
        notification = Notification.objects.create(
            recipients=User.objects.get(id=mentor),
            message=message,
            type=type,
            sender=sender)
        notification.save()
        serializer = CreateNotificationSerializer(notification)
    message = messaging.MulticastMessage(
        data={
            'sender': sender.name,
            'type': type,
            'message': message
        },
        tokens=registration_tokens,
    )
    response = messaging.send_multicast(message)
    print('{0} messages were sent successfully'.format(response.success_count))
    return Response(serializer.data, status=status.HTTP_201_CREATED)
Esempio n. 5
0
def send_notification(title, message, to=[], data={}):
    data.update({
        "body": message,
        "title": title,
        'type':
        'confimar_embarque',  # aqui vai a informacao sobre o tipo da notificacao
        'email': '*****@*****.**',  # aqui vai o email do usuário
        "click_action": "FLUTTER_NOTIFICATION_CLICK",
        'data': json.dumps({'email': '*****@*****.**'})
    })
    registration_tokens = to

    message = messaging.MulticastMessage(
        notification=messaging.Notification(
            title=title,
            body=message,
        ),
        android=messaging.AndroidConfig(
            ttl=datetime.timedelta(seconds=5 * 60),
            priority='high',
            notification=messaging.AndroidNotification(
                icon='stock_ticker_update',
                color='#f45342',
                sound='default',
                # click_action='FLUTTER_NOTIFICATION_CLICK',
            ),
        ),
        data=data,
        tokens=registration_tokens,
    )
    response = messaging.send_multicast(message)
    print('data: {}\n'.format(data))
    print('{0} messages were sent successfully'.format(response.success_count))
Esempio n. 6
0
    def send_notification_to_user(self, title, message, uid, data=None):
        title = pymysql.escape_string(bleach.clean(title))
        message = pymysql.escape_string(bleach.clean(message))

        #Connect to MySQL
        conn = pymysql.connect(self.host,
                               self.username,
                               self.password,
                               self.database,
                               cursorclass=pymysql.cursors.DictCursor,
                               charset='utf8mb4')
        cursor = conn.cursor()

        cursor.execute("SELECT * FROM devices WHERE uid='{}';".format(uid))

        devices = cursor.fetchall()

        conn.commit()
        conn.close()

        device_tokens = [device["device_id"] for device in devices]

        push_notification = messaging.MulticastMessage(
            device_tokens,
            notification=messaging.Notification(title=title, body=message),
            data=data,
            apns=messaging.APNSConfig(
                payload=messaging.APNSPayload(messaging.Aps(sound="default"))),
            android=messaging.AndroidConfig(
                notification=messaging.AndroidNotification(
                    sound="default", click_action="OPEN_FROM_NOTIFICATION")))

        response = messaging.send_multicast(push_notification)
Esempio n. 7
0
def sendPush(title, msg, image, registration_token, dataObject=None):
    date = datetime.datetime.fromtimestamp(int(time.time()))
    # See documentation on defining a message payload.
    message = messaging.MulticastMessage(
        notification=messaging.Notification(
            title=title,
            body=msg,
            image=image
        ),
        data={
            "date": date.strftime('%Y-%m-%d %H:%M:%S'),
            "station_id": "2",
            "title": title,
            "body": msg,
            "image": image,
            "icon": "",
            "click_action": "https://capital.pe/"
        },
        tokens=registration_token,
        fcm_options=messaging.FCMOptions(analytics_label="tokens_label")
    )

    # Send a message to the device corresponding to the provided
    # registration token.
    response = messaging.send_multicast(message)
    # Response is a message ID string.
    print('{0} messages were sent successfully'.format(response.success_count))
Esempio n. 8
0
def send_fcm_notifications(tokens=None, topic=None, title=None, body=None, data=None):
  global firebase_app
  if not firebase_app:
    firebase_app = firebase_admin.initialize_app(get_firebase_certificate())

  noti = messaging.Notification(title=title, body=body)
  response = None
  if tokens and len(tokens):
    print("Sending to tokens: {}".format(tokens))
    multicast_msg = messaging.MulticastMessage(
        tokens=tokens, notification=noti, data=data)
    # send_multicast returns a BatchResponse
    # https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging#firebase_admin.messaging.BatchResponse
    response = messaging.send_multicast(
        multicast_message=multicast_msg, app=firebase_app)
    print("FCM Response: Success: {} Failed: {} ".format(
        response.success_count, response.failure_count))
    fcm_error_handler(tokens=tokens, topic=topic, title=title, body=body, data=data,
                      responses=response.responses, recipient_count=len(tokens), success_count=response.success_count)
    delete_invalid_tokens(tokens, response.responses)
  elif topic:
    message = messaging.Message(topic=topic, notification=noti, data=data)
    response = messaging.send_all(messages=[message], app=firebase_app)
    print("Sent TOPIC {} Msg: {}".format(topic, response))
    fcm_error_handler(tokens=tokens, topic=topic, title=title, body=body, data=data,
                      responses=response.responses, recipient_count=1, success_count=0)

  return response
def send_multicast_and_handle_errors():
    # [START send_multicast_error]
    # These registration tokens come from the client FCM SDKs.
    registration_tokens = [
        'YOUR_REGISTRATION_TOKEN_1',
        # ...
        'YOUR_REGISTRATION_TOKEN_N',
    ]

    message = messaging.MulticastMessage(
        data={
            'score': '850',
            'time': '2:45'
        },
        tokens=registration_tokens,
    )
    response = messaging.send_multicast(message)
    if response.failure_count > 0:
        responses = response.responses
        failed_tokens = []
        for idx, resp in enumerate(responses):
            if not resp.success:
                # The order of responses corresponds to the order of the registration tokens.
                failed_tokens.append(registration_tokens[idx])
        print('List of tokens that caused failures: {0}'.format(failed_tokens))
 def send_message(self, tokens: Sequence[str],
                  data: Dict[str, any]) -> Tuple[int, int, Sequence[str]]:
     """
     Send multicast message using firebase cloud messaging service
     :param tokens: Firebase token of recipient
     :param data: Dictionary with the notification data
     :return: Success count, failure count, invalid tokens
     """
     logger.debug("Sending data=%s with tokens=%s", data, tokens)
     message = messaging.MulticastMessage(
         android=self._build_android_config(),
         apns=self._build_apns_config(),
         data=data,
         tokens=tokens,
     )
     batch_response: BatchResponse = messaging.send_multicast(message,
                                                              app=self.app)
     responses: List[SendResponse] = batch_response.responses
     # Check if there are invalid tokens
     invalid_tokens = [
         token for token, response in zip(tokens, responses)
         if not response.success
         and isinstance(response.exception, messaging.UnregisteredError)
     ]
     return batch_response.success_count, batch_response.failure_count, invalid_tokens
Esempio n. 11
0
    def _fcm_message(self):
        platform_config = self.notification.platform_config

        from consts.fcm.platform_type import PlatformType
        android_config = self.notification.android_config if self.notification.android_config \
            else platform_config and platform_config.platform_config(platform_type=PlatformType.ANDROID)
        apns_config = self.notification.apns_config if self.notification.apns_config \
            else platform_config and platform_config.platform_config(platform_type=PlatformType.APNS)
        webpush_config = self.notification.webpush_config if self.notification.webpush_config \
            else platform_config and platform_config.platform_config(platform_type=PlatformType.WEBPUSH)
        # `platform_config and platform_config` is to short circuit execution if platform_config is None

        # Add `notification_type` to data payload
        data_payload = self.notification.data_payload if self.notification.data_payload else {}
        # Remove `None` from data payload, since FCM won't accept them
        data_payload = {k: v for k, v in data_payload.items() if v is not None}
        from consts.notification_type import NotificationType
        data_payload['notification_type'] = NotificationType.type_names[
            self.notification.__class__._type()]

        return messaging.MulticastMessage(
            tokens=self.tokens,
            data=data_payload,
            notification=self.notification.fcm_notification,
            android=android_config,
            webpush=webpush_config,
            apns=apns_config)
Esempio n. 12
0
def send(title, msg, token, dataObject=None):
    message = messaging.MulticastMessage(notification=messaging.Notification(
        title=title, body=msg),
                                         data=dataObject,
                                         tokens=token)

    response = messaging.send_multicast(message)
    print('sent message', response)
Esempio n. 13
0
def sendPush(title, msg, registration_token, dataObject=None):
    message = messaging.MulticastMessage(
        notification=messaging.Notification(title=title, body=msg),
        data=dataObject,
        tokens=registration_token,
    )

    response = messaging.send_multicast(message)
Esempio n. 14
0
 def send_to_tokens(self, registration_tokens, title, body, image, html):
     message = messaging.MulticastMessage(
         data=dict(html=html),
         notification=messaging.Notification(title=title,
                                             body=body,
                                             image=image),
         tokens=registration_tokens,
     )
     messaging.send_multicast(message)
Esempio n. 15
0
def _base_send(n_type_value, n_text, tokens, n_type):
    if not isinstance(tokens, list):
        tokens = [tokens]
    name = n_type.name
    message = messaging.MulticastMessage(
        notification=messaging.Notification(title=n_type_value, body=n_text),
        data=dict(title=n_type_value, body=n_type_value, notifType=name),
        tokens=tokens,
    )
    return messaging.send_multicast(message)
Esempio n. 16
0
def create_notifications():
    time = request.form.get('time')
    title = request.form.get('title')
    description = request.form.get('description')
    session = loadSession()
    students_id = request.form.getlist('checks[]')
    session.add(
        Notifications(notification_title=title,
                      description=description,
                      notification_time=time))
    session.commit()
    new_session = loadSession()
    result = new_session.query(Notifications).filter(
        Notifications.notification_title == title,
        Notifications.notification_time == time,
        Notifications.description == description)
    notif_id = result[0].notification_id
    for i in range(len(students_id)):
        new_session.add(
            students_notifications_bridge(notification_id=notif_id,
                                          student_id=students_id[i]))
    new_session.commit()
    session.close()
    new_session.close()
    notif_session = loadSession()
    registration_tokens = []
    print(students_id)
    print(students_id)
    for i in range(len(students_id)):
        cred_data = notif_session.query(credentials).filter(
            credentials.id == students_id[i])
        registration_tokens.append(cred_data[0].Token)
    message = messaging.MulticastMessage(
        data={
            'score': title,
            'time': description
        },
        tokens=registration_tokens,
    )
    response = messaging.send_multicast(message)
    if response.failure_count > 0:
        responses = response.responses
        failed_tokens = []
        for idx, resp in enumerate(responses):
            if not resp.success:
                # The order of responses corresponds to the order of the registration tokens.
                failed_tokens.append(registration_tokens[idx])
        print('List of tokens that caused failures: {0}'.format(failed_tokens))
    notif_session.commit()
    notif_session.close()

    return jsonify({"status": 200})
Esempio n. 17
0
def send_multicast(tokens, data):
    # [START send_multicast]
    # Create a list containing up to 500 registration tokens.
    # These registration tokens come from the client FCM SDKs.

    message = messaging.MulticastMessage(
        data=data,
        tokens=tokens,
    )
    response = messaging.send_multicast(message)
    # See the BatchResponse reference documentation
    # for the contents of response.
    print('{0} messages were sent successfully'.format(response.success_count))
Esempio n. 18
0
def sendPush(title, msg, registration_token, dataObject=None):
    # See documentation on defining a message payload.
    message = messaging.MulticastMessage(
        notification=messaging.Notification(title=title, body=msg),
        data=dataObject,
        tokens=registration_token,
    )

    # Send a message to the device corresponding to the provided
    # registration token.
    response = messaging.send_multicast(message)
    print(response.__str__())
    # Response is a message ID string.
    print('Successfully sent message:', response)
Esempio n. 19
0
def send_message(recipients, title, body, **kwargs):
    """Send message to Firebase service"""
    logger.info("Send notifications to Firebase...")
    logger.debug("Title: %s\n Body: %s", title, body)
    message = messaging.MulticastMessage(
        tokens=recipients,
        data={str(key): str(kwargs[key]) for key in kwargs},
        notification=messaging.Notification(
            title=title,
            body=body
        )
    )
    messaging.send_multicast(message)
    logger.info("Sending notifications successful...")
Esempio n. 20
0
def test_send_multicast():
    multicast = messaging.MulticastMessage(
        notification=messaging.Notification('Title', 'Body'),
        tokens=['not-a-token', 'also-not-a-token'])

    batch_response = messaging.send_multicast(multicast)

    assert batch_response.success_count is 0
    assert batch_response.failure_count == 2
    assert len(batch_response.responses) == 2
    for response in batch_response.responses:
        assert response.success is False
        assert response.exception is not None
        assert response.message_id is None
Esempio n. 21
0
    def send_multicast(self, title, body):
        """
        一括のpush通知対応
        :param title:
        :param body:
        :param ids:
        :return:
        """

        notification = messaging.Notification(title=title, body=body)

        android_notification = messaging.AndroidNotification(title=title,
                                                             body=body)

        android = messaging.AndroidConfig(notification=android_notification)
        data = {
            "title": title,
            "body": body,
            "click_action": "FLUTTER_NOTIFICATION_CLICK",
            "sound": "default"
        }

        tokens = Token.objects.all().filter(is_deleted=False)

        if not tokens:
            return False

        target_tokens = list(self.__split_list(tokens, 500))

        success = 0
        failuer = 0

        for targets in target_tokens:
            base_tokens = []
            for token in targets:
                base_tokens.append(token.token)

            print(base_tokens)
            multicast_message = messaging.MulticastMessage(
                notification=notification,
                tokens=base_tokens,
                android=android,
                data=data)

            result = messaging.send_multicast(multicast_message)
            print(result.success_count)

        return True
Esempio n. 22
0
def send_to_token(msg, timestamp):
    # [START send_to_token]
    # This registration token comes from the client FCM SDKs.
    print("Send data to mobile | START: ", (time.time() - timestamp) * 1000,
          "ms")
    registration_token = 'et1Gy1YilHQ:APA91bGqIAj2gb2sdZlCEcJH5mDE7bxMmNnLW3oY2iJEExM7uYHzRHE_T0_Mbr1qhWeIlEGq7fM4V95cR4WCSW51OXnpE1q5sggsrTrYLxVNx3KiDTxsBecbohm3YeaPZ7kzBoR18tt2'

    queryTokens = recMod.Token.objects.all()
    tempList = []
    print(queryTokens)
    for entry in queryTokens:
        tempList.append(entry.identi)

    # See documentation on defining a message payload.
    noti = messaging.AndroidNotification(
        sound='/res/raw/fire_pager',
        body=msg,
        title='titel',
        priority='max',
    )

    andro = messaging.AndroidConfig(
        notification=noti,
        priority='high',
    )

    message = messaging.MulticastMessage(
        tokens=tempList,
        data={
            'score': 'alarm',
            'time': '2:45',
        },
        android=andro,
    )

    # Send a message to the device corresponding to the provided
    # registration token.

    response = messaging.send_multicast(message)
    # Response is a message ID string.
    for i in response.responses:
        if (i.success):
            print("Response code for app: ", i, " = 200")
        else:
            print("Response code for app: ", i, "= error")
    #print('Response code from Firebase: :', response.responses)
    print("Send data to mobile | END: ", (time.time() - timestamp) * 1000,
          "ms")
Esempio n. 23
0
def sendPushNotification(image=None,
                         size=(64, 64),
                         name='',
                         inout=0,
                         phone_token=tokens,
                         title='Emergency !'):
    # check parameters
    if image is None:
        raise Exception("Error of Image Data.")
    try:
        image = cv2.resize(image, size)
    except:
        raise Exception("Can't resize the person image into LargeIcon Data.")
    if name == '':
        raise Exception("Error of Person Name.")
    if phone_token.__len__() < 1:
        raise Exception("Error of Token Infos.")
    now = datetime.now()
    dtime = now.strftime("%H:%M:%S")
    msg_content = "Error!"
    if inout == 0:
        msg_content = "{} has arrived in the room at {}.".format(name, dtime)
    elif inout == 1:
        msg_content = "{} has left from the room at {}.".format(name, dtime)

    retval, img_encoded = cv2.imencode('.jpg', image)

    if not retval:
        raise Exception("Can't convert the image into the text data.")
        # Convert to base64 encoding and show start of data
    txt_image = base64.b64encode(img_encoded).decode('utf-8')

    try:
        message = messaging.MulticastMessage(
            notification=messaging.Notification(title=title, body=msg_content),
            data={"image": str(txt_image)},
            tokens=phone_token,
        )

        # Send a message to the device corresponding to the provided
        # registration token.
        response = messaging.send_multicast(message)
        print(response.__str__())
        # Response is a message ID string.
        print('Successfully sent message:', response)
    except:
        raise Exception("Failed to send the notification.")
Esempio n. 24
0
def push_notify(name, url) :
    # [START send_to_token]
    # This registration token comes from the client FCM SDKs.
    registration_tokens = []

    # This will load available registration token stored on
    # Realtime Database and will append on empty array
    dbRef = db.reference("users")
    dataSnapshot = dbRef.get()
    for key, val in dataSnapshot.items():
        registration_tokens.append(val['token'])

    # See documentation on defining a message payload.
    message = messaging.MulticastMessage(
        # notification = messaging.Notification(
        #     title = "Bajaga",
        #     body = "Terdeteksi orang tak dikenal",
        #     image = url
        # ),
        android = messaging.AndroidConfig(
            notification = messaging.AndroidNotification(
                title = "Just Test",
                body = "Hello from firebase notification",
                image = url,
                # click_action = "DetailScreenActivity",
            ),
            priority = "high",
            data = {'url': url, 'name': name},
        ),
        data = {'url': url, 'name': name},
        tokens = registration_tokens,
    )

    # Send a message to the device corresponding
    # to the provided registration token.
    response = messaging.send_multicast(message, app=default_app)
    if response.failure_count > 0 :
        responses = response.responses
        failed_tokens = []
        for idx, resp in enumerate(responses):
            if not resp.success:
                failed_tokens.append(registration_tokens[idx])

    # Failed response token
    # print("list of failures token: {0}".format(failed_tokens))
    # Response is a message ID string.
    print('Successfully sent message:', response)
Esempio n. 25
0
    def send_notification_to_users(self,
                                   title,
                                   message,
                                   uids,
                                   setting,
                                   data=None):
        settings = [
            'users.notify_new_friend_req', 'users.notify_new_friend_acc',
            'notify_new_feed_item', 'notify_new_like', 'notify_new_comment'
        ]

        title = pymysql.escape_string(bleach.clean(title))
        message = pymysql.escape_string(bleach.clean(message))

        #Connect to MySQL
        conn = pymysql.connect(self.host,
                               self.username,
                               self.password,
                               self.database,
                               cursorclass=pymysql.cursors.DictCursor,
                               charset='utf8mb4')
        cursor = conn.cursor()

        cursor.execute("""SELECT device_id, devices.uid AS uid FROM users

LEFT OUTER JOIN devices ON devices.uid = users.uid

WHERE devices.uid IN ({}) AND {} = 1;""".format(
            ",".join(["'{}'".format(uid) for uid in uids]), settings[setting]))

        conn.commit()
        conn.close()

        devices = cursor.fetchall()

        device_tokens = [device["device_id"] for device in devices]
        push_notification = messaging.MulticastMessage(
            device_tokens,
            notification=messaging.Notification(title=title, body=message),
            data=data,
            apns=messaging.APNSConfig(
                payload=messaging.APNSPayload(messaging.Aps(sound="default"))),
            android=messaging.AndroidConfig(
                notification=messaging.AndroidNotification(
                    sound="default", click_action="OPEN_FROM_NOTIFICATION")))

        response = messaging.send_multicast(push_notification)
Esempio n. 26
0
async def send_single_notify(request):
    data_request = request.json
    if data_request is None:
        return json(
            {
                'error_code': 'PARAMS_ERROR',
                'error_message': 'PARAMS_ERROR'
            },
            status=520)
    firebase_access_token = request.headers.get('UPSTART-FIREBASE-KEY', None)
    # CHECK REQUEST ACCESS PERMISSION
    if firebase_access_token != Config.UPSTART_FIREBASE_KEY:
        return json(
            {
                'error_code': 'AUTH_ERROR',
                'error_message': 'Authentication Error'
            },
            status=523)
    app = data_request.get("app", None)
    device_ids = data_request.get("device_ids", None)
    data = data_request.get("data", None)
    # print("---device_ids---",device_ids)
    # data = data.replace("\'", "\"")

    if app is None or app not in Config.ALLOWED_APPS:
        return json(
            {
                'error_code': 'APP PERMISSION DENIED',
                'error_message': 'Authentication App Error'
            },
            status=520)

    tokens = []
    for device_id in device_ids:
        token = notify_redisdb.get(app + "_" + str(device_id))
        if token is not None:
            token = token.decode('utf8')
            tokens.append(token)

    message = messaging.MulticastMessage(
        data=data,
        tokens=tokens,
    )
    response = messaging.send_multicast(message)
    # Response is a message ID string.
    return json({"ok": True}, status=200)
Esempio n. 27
0
async def __send_message_firebase__(
        current_user: int,
        chat_info: Dict[str, Any],
        message: Dict[str, Any],
        user_nick: str,
):
    token_list = await extract_tokens(current_user=current_user, users=chat_info["users"])
    # log.info(token_list)
    message_firebase = messaging.MulticastMessage(
        notification=messaging.Notification(
            title=chat_info["name"],
            body=user_nick + ": " + message["body"],
        ),
        data={'data': json.dumps({**message}, indent=4, sort_keys=True, default=str)},
        tokens=token_list
    )
    response = messaging.send_multicast(message_firebase)
Esempio n. 28
0
 def construct_multicast_message(self):
     self.data['click_action'] = 'FLUTTER_NOTIFICATION_CLICK'
     message = messaging.MulticastMessage(
         notification=messaging.Notification(
             title=self.message['title'],
             body=self.message['body'],
         ),
         android=messaging.AndroidConfig(
             ttl=datetime.timedelta(seconds=3600),
             priority='normal',
         ),
         apns=messaging.APNSConfig(payload=messaging.APNSPayload(
             aps=messaging.Aps(badge=42), ), ),
         data=self.data,
         tokens=self.tokens,
     )
     return message
def send_message(chat_room_id=None,
                 user_id=None,
                 message=None,
                 message_id=None,
                 registration_tokens=None,
                 created_at=None,
                 failed_count=0):
    if not chat_room_id or not user_id or not message_id or not registration_tokens:
        raise ValueError(
            "Invalid arguments found: chat_room_id={chat_room_id}, user_id={user_id}, "
            "message_id={message_id}, token={token}".format(
                chat_room_id=chat_room_id,
                user_id=user_id,
                message_id=message_id,
                token=registration_tokens))

    if failed_count > 3:
        return

    message = messaging.MulticastMessage(
        data=dict(
            type="MESSAGE",
            user_id=str(user_id),
            created_at=str(created_at),
            # the belows are for chatting only
            chat_room_id=str(chat_room_id),
            message_id=str(message_id),
            message=str(message)),
        tokens=registration_tokens,
        # android=messaging.AndroidConfig(priority="high"),
        apns=messaging.APNSConfig(),
        notification=messaging.Notification())

    response = messaging.send_multicast(message)
    # cBdvpdzJSIyOVKZPsWNOGs:APA91bGNyQMxmWWgNVr3LJzM2PPnjmWtfADVaGoG0RHCiFJHFm7bd534EeoWm0REzxwxuzD5hbFbzhsQgP4557WN3m2YYOaJC3FeXCFEsmI9z8qj0Jlzm6SAaQypzCyxO4UHme0yNf5T
    if response.failure_count > 0:
        responses = response.responses
        failed_tokens = []
        for idx, resp in enumerate(responses):
            if not resp.success:
                # The order of responses corresponds to the order of the registration tokens.
                failed_tokens.append(registration_tokens[idx])

        logging.error('List of tokens that caused failures: %s' %
                      failed_tokens)
Esempio n. 30
0
def send_multicast():
    # [START send_multicast]
    # Create a list containing up to 500 registration tokens.
    # These registration tokens come from the client FCM SDKs.
    registration_tokens = [
        'YOUR_REGISTRATION_TOKEN_1',
        # ...
        'YOUR_REGISTRATION_TOKEN_N',
    ]

    message = messaging.MulticastMessage(
        data={'score': '850', 'time': '2:45'},
        tokens=registration_tokens,
    )
    response = messaging.send_multicast(message)
    # See the BatchResponse reference documentation
    # for the contents of response.
    print('{0} messages were sent successfully'.format(response.success_count))