def notify_getoff(): fcm_messages = [] standing_users = {} vacancies_created_car_ids = set() itinerary_keys = redis.keys("itinerary:*") for itinerary_key in itinerary_keys: user_id = itinerary_key.split(':')[-1] user = get_user(user_id) itinerary = get_itinerary(user_id) train = get_train(itinerary['subway_id'], itinerary['train_id']) car_id = f"{train.subway_id}-{train.number}-{itinerary['car_number']}" if train.station_id == itinerary['destination_id']: delete_itinerary(user_id) vacancies_created_car_ids.add(car_id) if user_id.startswith('dummy'): continue # send notification to users who need to get off the train if user.get('notification_itinerary_end', 'on') == 'on' and user['platform'] == 'fcm': message = Message( notification=Notification('여정이 끝났습니다!', '하차하세요~'), token=user['token'], ) fcm_messages.append(message) else: # collect real users who are standing and whose itinerary is ongoing if user_id.startswith('dummy'): continue if itinerary['seated'] == "false": if car_id not in standing_users: standing_users[car_id] = [] standing_users[car_id].append(user) for car_id in vacancies_created_car_ids: if car_id in standing_users: for user in standing_users[car_id]: if user.get('notification_seat_vacancy', 'on') == 'on' and user['platform'] == 'fcm': message = Message( notification=Notification('자리가 생겼습니다!', '착석하세요~'), token=user['token'], ) fcm_messages.append(message) # bulk send FCM messages messaging.send_all(fcm_messages) for m in fcm_messages: click.echo(f"token: {m.token} title: {m.notification.title} body: {m.notification.body}") click.echo(f"[{datetime.now()}] {len(fcm_messages)} 개 FCM 알람 발송")
def test_send_all(): messages = [ messaging.Message( topic='foo-bar', notification=messaging.Notification('Title', 'Body')), messaging.Message( topic='foo-bar', notification=messaging.Notification('Title', 'Body')), messaging.Message( token='not-a-token', notification=messaging.Notification('Title', 'Body')), ] batch_response = messaging.send_all(messages, dry_run=True) assert batch_response.success_count == 2 assert batch_response.failure_count == 1 assert len(batch_response.responses) == 3 response = batch_response.responses[0] assert response.success is True assert response.exception is None assert re.match('^projects/.*/messages/.*$', response.message_id) response = batch_response.responses[1] assert response.success is True assert response.exception is None assert re.match('^projects/.*/messages/.*$', response.message_id) response = batch_response.responses[2] assert response.success is False assert isinstance(response.exception, exceptions.InvalidArgumentError) assert response.message_id is None
def call(self, title: str = '', body: str = ''): token = "asfdjkladjfkaldjfklajdfkl2j13klj132kljkl" messages = [] message = messaging.Message(notification=messaging.Notification( title=title, body=body), token=token, data=None, android=AndroidConfig(priority=10, ttl=45)) messages.append(message) if len(messages) == 0: batch_rsp = messaging.send_all(messages) i = 0 failed_ids = [] for rsp in batch_rsp.responses: if rsp.exception: if rsp.exception.http_response.status_code in [404, 400]: failed_ids.append(token) else: logger.warning(f"failed fcm batch send: {token}") i += 1 return failed_ids
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 pushGeneralNotification(contentNoti, title): topic = 'covidtracing' if contentNoti == "": contentNoti = "Content Test Noti" if title == "": title = "Test title" messages = [ # Gửi tin nhắn lịch trình đi lại tại đây, gửi kèm Key người bi F0 messaging.Message( data={ 'generalNotification': contentNoti, 'title': title, }, topic=topic, ), # ... # Gửi thêm tin nhắn lịch trình đi lại tại đây luôn messaging.Message( notification=messaging.Notification('Thông báo: ' + title, contentNoti), topic=topic, ), ] response = messaging.send_all(messages) # Response is a message ID string. print('Successfully sent message:', response)
def sendNotification(_title="title", _body="body",_image=image,_token=token): notification = messaging.Notification(title=_title, body= _body, image=_image) messages =[ messaging.Message( notification=notification, token=_token, ), ] response = messaging.send_all(messages) # store the response in the firebase database db.child("response/succsess").set(response.success_count) db.child("response/faliuer").set(response.failure_count)
def send_message( self, message: messaging.Message, skip_registration_id_lookup: bool = False, additional_registration_ids: Sequence[str] = None, app: "firebase_admin.App" = SETTINGS["DEFAULT_FIREBASE_APP"], **more_send_message_kwargs, ) -> FirebaseResponseDict: """ Send notification of single message for all active devices in queryset and deactivate if DELETE_INACTIVE_DEVICES setting is set to True. Bulk sends using firebase.messaging.send_all. For every 500 messages, we send a single HTTP request to Firebase (the 500 is set by the firebase-sdk). :param message: firebase.messaging.Message. If `message` includes a token/id, it will be overridden. :param skip_registration_id_lookup: skips the QuerySet lookup and solely uses the list of IDs from additional_registration_ids :param additional_registration_ids: specific registration_ids to add to the :param app: firebase_admin.App. Specify a specific app to use QuerySet lookup :param more_send_message_kwargs: Parameters for firebase.messaging.send_all() - dry_run: bool. Whether to actually send the notification to the device If there are any new parameters, you can still specify them here. :raises FirebaseError :returns FirebaseResponseDict """ registration_ids = self.get_registration_ids( skip_registration_id_lookup, additional_registration_ids, ) if not registration_ids: return self.get_default_send_message_response() responses: List[messaging.SendResponse] = [] for i in range(0, len(registration_ids), MAX_MESSAGES_PER_BATCH): messages = [ self._prepare_message(m, t) for m, t in zip( repeat(message, MAX_MESSAGES_PER_BATCH), registration_ids[i:i + MAX_MESSAGES_PER_BATCH], ) ] responses.extend( messaging.send_all(messages, app=app, **more_send_message_kwargs).responses) return FirebaseResponseDict( response=messaging.BatchResponse(responses), registration_ids_sent=registration_ids, deactivated_registration_ids=self. deactivate_devices_with_error_results(registration_ids, responses), )
def send_all(registration_token,title, body, data): # registration_token = 'YOUR_REGISTRATION_TOKEN' # [START send_all] # Create a list containing up to 500 messages. # notification=messaging.Notification(title, body,'https://drlinks.yte360.com/static/images/icon-thuoc.png'), messages = [ messaging.Message( notification=messaging.Notification(title, body,'https://drlinks.yte360.com/static/images/ic_launcher.png'), token=registration_token, data=data, android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification( title=title, body=body, sound='bell.mp3', icon='https://drlinks.yte360.com/static/images/ic_launcher.png', # color='#f45342' ), ), apns=messaging.APNSConfig( headers={'apns-priority': '10'}, payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( title=title, body=body, ), badge=42, sound='bell.mp3' ), ), ) ), # ... # messaging.Message( # notification=messaging.Notification(title, body), # topic='readers-club', # ), ] response = messaging.send_all(messages) # See the BatchResponse reference documentation # for the contents of response. print('{0} messages were sent successfully'.format(response.success_count))
def test_send_all_500(): messages = [] for msg_number in range(500): topic = 'foo-bar-{0}'.format(msg_number % 10) messages.append(messaging.Message(topic=topic)) batch_response = messaging.send_all(messages, dry_run=True) assert batch_response.success_count == 500 assert batch_response.failure_count == 0 assert len(batch_response.responses) == 500 for response in batch_response.responses: assert response.success is True assert response.exception is None assert re.match('^projects/.*/messages/.*$', response.message_id)
async def sendNotificatin(self): # See documentation on defining a message payload. message = messaging.Message( data={ 'title': '850', 'body': '2:45', }, token=self.registration_token, ) # Send a message to the device corresponding to the provided # registration token. response = messaging.send_all(message) # Response is a message ID string. print('Successfully sent message:', response)
def setNotification(self, timeStamp): messages = [ messaging.Message( notification=messaging.Notification('Smart App', 'Alert !!!!!'), token=self.__registrationToken, ) ] response = messaging.send_all(messages) # See the BatchResponse reference documentation # for the contents of response. print('{0} messages were sent successfully'.format( response.success_count)) doc_ref = self._firestoreDb.collection(self.__user).document( self.__uid).collection('notifications').document(timeStamp) doc_ref.set({"title": "Alert ! ", "body": timeStamp})
def pushNotification(historyLocation, keyApp, title): # The topic name can be optionally prefixed with "/topics/". topic = 'covidtracing' if historyLocation == "": historyLocation = "Test" if keyApp == "": keyApp = "Test Key" if title == "": title = "test title" # See documentation on defining a message payload. messages = [ # Gửi tin nhắn lịch trình đi lại tại đây, gửi kèm Key người bi F0 messaging.Message( data={ 'title': title, 'key': keyApp, 'historyLocation': historyLocation, }, topic=topic, ), # ... # Gửi thêm tin nhắn lịch trình đi lại tại đây luôn messaging.Message( notification=messaging.Notification('Thông báo ca nhiễm F0', historyLocation), topic=topic, ), ] # The topic name can be optionally prefixed with "/topics/". # See documentation on defining a message payload. # message = messaging.Message( # data={ # 'score': '850', # 'time': '2:45', # }, # topic=topic, # ) # Send a message to the devices subscribed to the provided topic. response = messaging.send_all(messages) # Response is a message ID string. print('Successfully sent message:', response)
async def sendAll(self): # [START send_all] # Create a list containing up to 100 messages. messages = [ messaging.Message( notification=messaging.Notification('Smart App', 'Alert !!!!!'), token=self.registration_token, ), # ... messaging.Message( notification=messaging.Notification('Price drop', '2% off all books'), topic='readers-club', ), ] response = messaging.send_all(messages) # See the BatchResponse reference documentation # for the contents of response. print('{0} messages were sent successfully'.format( response.success_count))
def send_all(): registration_token = 'YOUR_REGISTRATION_TOKEN' # [START send_all] # Create a list containing up to 500 messages. messages = [ messaging.Message( notification=messaging.Notification( 'Price drop', '5% off all electronics'), token=registration_token, ), # ... messaging.Message( notification=messaging.Notification( 'Price drop', '2% off all books'), topic='readers-club', ), ] response = messaging.send_all(messages) # See the BatchResponse reference documentation # for the contents of response. print('{0} messages were sent successfully'.format(response.success_count))
def send_all(): # TODO Custom token registration_token = 'deXMEcpHQzc:APA91bGH6_kXLK1OaiaHCimQrvadTNpVMiCm14i7PkT59rL7yC7dyVDedgSp2Mq5rHIA4AuajwYXd8FlaLPyoDbndBbPcp78T_yDgAJg2JlLefrGW5et4lEQMIdApAOcJ3G9xi2FC6ke' # [START send_all] # Create a list containing up to 100 messages. messages = [ messaging.Message( notification=messaging.Notification( 'Price drop', '5% off all electronics'), token=registration_token, ), # ... messaging.Message( notification=messaging.Notification( 'Price drop', '2% off all books'), topic='readers-club', ), ] response = messaging.send_all(messages) # See the BatchResponse reference documentation # for the contents of response. print('{0} messages were sent successfully'.format(response.success_count))
def send_batch(self, data, dry_run=False): response = messaging.send_all(data, dry_run=dry_run, app=self.app) if response.failure_count > 0: raise FCMTooManyRegIdsException("Many reg id is failed %s", ",".join(response.responses["failed_registration_ids"])) return response