def test_aps_alert(self): msg = messaging.Message( topic='topic', apns=messaging.APNSConfig( payload=messaging.APNSPayload(aps=messaging.Aps( alert=messaging.ApsAlert(title='t', body='b', title_loc_key='tlk', title_loc_args=['t1', 't2'], loc_key='lk', loc_args=['l1', 'l2'], action_loc_key='alk', launch_image='li')), ))) expected = { 'topic': 'topic', 'apns': { 'payload': { 'aps': { 'alert': { 'title': 't', 'body': 'b', 'title-loc-key': 'tlk', 'title-loc-args': ['t1', 't2'], 'loc-key': 'lk', 'loc-args': ['l1', 'l2'], 'action-loc-key': 'alk', 'launch-image': 'li', }, }, } }, } check_encoding(msg, expected)
def test_send(): msg = messaging.Message( topic='foo-bar', notification=messaging.Notification( 'test-title', 'test-body', 'https://images.unsplash.com/photo-1494438639946' '-1ebd1d20bf85?fit=crop&w=900&q=60'), android=messaging.AndroidConfig( restricted_package_name='com.google.firebase.demos', notification=messaging.AndroidNotification( title='android-title', body='android-body', image='https://images.unsplash.com/' 'photo-1494438639946-1ebd1d20bf85?fit=crop&w=900&q=60', event_timestamp=datetime.now(), priority='high', vibrate_timings_millis=[100, 200, 300, 400], visibility='public', sticky=True, local_only=False, default_vibrate_timings=False, default_sound=True, default_light_settings=False, light_settings=messaging.LightSettings( color='#aabbcc', light_off_duration_millis=200, light_on_duration_millis=300), notification_count=1)), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(alert=messaging.ApsAlert(title='apns-title', body='apns-body'))))) msg_id = messaging.send(msg, dry_run=True) assert re.match('^projects/.*/messages/.*$', msg_id)
def _build_apns_config(self, title_loc_key: str = ''): """ Data for the Apple Push Notification Service see https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging :param title_loc_key: :return: """ return messaging.APNSConfig( # headers={ # 'apns-priority': '10' # }, payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( # This is a localized key that iOS will search in # the safe iOS app to show as a default title title="New Activity", body="New Activity with your Safe", # title_loc_key=title_loc_key, ), # Means the content of the notification will be # modified by the safe app. # Depending on the 'type' custom field, # 'alert.title' and 'alert.body' above will be # different mutable_content=True, badge=1, sound='default', ), ), )
def test_invalid_loc_args(self, data): alert = messaging.ApsAlert(loc_key='foo', loc_args=data) excinfo = self._check_alert(alert) if isinstance(data, list): expected = 'ApsAlert.loc_args must not contain non-string values.' assert str(excinfo.value) == expected else: expected = 'ApsAlert.loc_args must be a list of strings.' assert str(excinfo.value) == expected
def set_alert(into: messaging.Message, title=None, subtitle=None, body=None, badge=0, sound="default"): message = into message.apns.payload.aps.alert = messaging.ApsAlert(title=title, subtitle=subtitle, body=body) message.apns.payload.aps.badge = badge message.apns.payload.aps.sound = sound
def test_send(): msg = messaging.Message( topic='foo-bar', notification=messaging.Notification('test-title', 'test-body'), android=messaging.AndroidConfig( restricted_package_name='com.google.firebase.demos', notification=messaging.AndroidNotification(title='android-title', body='android-body')), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(alert=messaging.ApsAlert(title='apns-title', body='apns-body'))))) msg_id = messaging.send(msg, dry_run=True) assert re.match('^projects/.*/messages/.*$', msg_id)
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 SendNotification(self, Topic, Title, Body): print("sending notif") NotifAmount = 1 message = messaging.Message( apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(alert=messaging.ApsAlert( title=Title, body=Body, ), sound="default", badge=NotifAmount + 1), ), ), topic=Topic, ) messaging.send(message)
def apns_message(): # [START apns_message] message = messaging.Message( apns=messaging.APNSConfig( headers={'apns-priority': '10'}, payload=messaging.APNSPayload(aps=messaging.Aps( alert=messaging.ApsAlert( title='$GOOG up 1.43% on the day', body= '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.', ), badge=42, ), ), ), topic='industry-tech', ) # [END apns_message] return message
def send_to_app(token, title, url): registration_token = token try: user = User.objects.get(token=token) if user.user_os == "ios": message = messaging.Message( # notification=messaging.Notification(title=title, body="페이지 변경 감지!"), apns=messaging.APNSConfig( payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert(title=title, body="페이지 변경 감지!",), badge=1, ), ), ), token=registration_token, ) else: message = messaging.Message( android=messaging.AndroidConfig( notification=messaging.AndroidNotification( title=title, body="페이지 변경 감지!", default_sound=True, visibility="public", priority="high", ) ), token=registration_token, ) except: return False try: response = messaging.send(message) print("Successfully sent message:", response) return True except Exception as e: print("Fail sent message", e) # delete_user(token) return False
def apns_message(registration_token, title, body, data): # [START apns_message] message = messaging.Message( token=registration_token, data=data, apns=messaging.APNSConfig( payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( title=title, body=body, ), badge=1, ), ), ) ) # [END apns_message] response = messaging.send(message) print("send notify IOS====",response)
def all_platforms_message(registration_token, title, body, data): # [START multi_platforms_message] message = 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' ), ), ) ) # [END multi_platforms_message] response = messaging.send(message) # See the BatchResponse reference documentation # for the contents of response. print(response)
def send_notify_ios_android(registration_token, title, body, data): # [START android_message] try: message = 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( payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( title=title, body=body, ), badge=1, ) ) ) ) # [END android_message] print("send_notify_ios_android.data===",data) response = messaging.send(message) print("send send_notify_ios_android====",response) except Exception as error: print(error) pass
import firebase_admin from firebase_admin import credentials from firebase_admin import messaging from firebase_admin import datetime cred = credentials.Certificate('ddyzd-firebase-adminsdk.json') default_app = firebase_admin.initialize_app(cred) # This registration token comes from the cli # ent FCM SDKs. #registration_token = 'ANDROID_CLIENT_TOKEN' token = 'fLfyEDFZAE4HuSRIIB7FuK:APA91bFdfN5CXf0Wsyjs8-vGeA0pBXo-7mGpC49BXu124s6ZIAluEC3i-pMZYEC_OtUzmZshfGyWRIEpzidHOXf5tPuIXJ-e59cvNbPdHHZ8oY4tKpEePkbarsIXgja5q1FLwVOyna85' # See documentation on defining a message payload. aps = messaging.Aps(messaging.ApsAlert(title="APs Alert Title", subtitle="APs Alert Subtitle", body="APs Alert Body")) aps = messaging.APNSPayload(aps, custom='data') message = messaging.Message( notification=messaging.Notification( title='넌', body='밤새 알림보낸다', ), # apns=messaging.APNSConfig(payload=aps), token=token ) for i in range(1): response = messaging.send(message) # Send a message to the device corresponding to the provided # registration token. # Response is a message ID string. print ('Successfully sent message:', response)
def send_notification(send_to_all=False, push_token=None, push_topic=None, title=None, body=None, url=None, action=None, card_id=None, device_id=None, silent=False): """ :param send_to_all: optional, if send to all, set to True :param push_token: optional this or push_topic :param push_topic: optional this or push_token :param title: notification title :param body: notification body message :param url: deeplink :param action: actions (1. open app, 2. deep link, 3. silent push) :param card_id: notification ID (if you want to override notification) e.g. afs:Card:001 :param device_id: device id of sender (so it wont silent push itself and start an infinity loop) :param silent: if push is silent or notification :return: firebase response """ _initialize_firebase() aps_alert = messaging.ApsAlert(title=title, body=body) content_available = False badge = 1 if silent: content_available = True badge = 0 aps_alert = messaging.ApsAlert() silent = str(silent) if action is PushActions.OPEN_APP: payload = { "title": title, "body": body, "action": action, "silent": silent, } elif action is PushActions.OPEN_DEEP_LINK: payload = { "title": title, "body": body, "action": action, "cardId": card_id, "silent": silent, } elif action is PushActions.SILENT_UPDATE_ACCOUNT: payload = {"action": action, "deviceId": device_id, "silent": silent} apns_config = messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(alert=aps_alert, content_available=content_available, badge=badge, custom_data=payload))) if send_to_all: message = messaging.Message( android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', data=payload), apns=apns_config, topic="environment-or-app-id", ) elif push_token: message = messaging.Message( android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', data=payload), apns=apns_config, token=push_token, ) elif push_topic: message = messaging.Message( android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', data=payload), apns=apns_config, condition="'%s' in topics && '%s' in topics" % (push_topic, "environment-or-app-id"), ) # Send a message to devices subscribed to the combination of topics # specified by the provided condition. response = messaging.send(message) return response
def test_no_loc_key(self): alert = messaging.ApsAlert(loc_args=['foo']) excinfo = self._check_alert(alert) expected = 'ApsAlert.loc_key is required when specifying loc_args.' assert str(excinfo.value) == expected
def test_invalid_launch_image(self, data): alert = messaging.ApsAlert(launch_image=data) excinfo = self._check_alert(alert) expected = 'ApsAlert.launch_image must be a string.' assert str(excinfo.value) == expected
def test_invalid_action_loc_key(self, data): alert = messaging.ApsAlert(action_loc_key=data) excinfo = self._check_alert(alert) expected = 'ApsAlert.action_loc_key must be a string.' assert str(excinfo.value) == expected
def test_invalid_title(self, data): alert = messaging.ApsAlert(title=data) excinfo = self._check_alert(alert) expected = 'ApsAlert.title must be a string.' assert str(excinfo.value) == expected
def fcm_send_message(registration_id, title=None, body=None, icon=None, data=None, sound=None, badge=None, low_priority=False, condition=None, time_to_live=None, click_action=None, collapse_key=None, delay_while_idle=False, restricted_package_name=None, dry_run=False, color=None, tag=None, body_loc_key=None, body_loc_args=None, title_loc_key=None, title_loc_args=None, content_available=None, extra_kwargs={}, api_key=None, json_encoder=None, extra_notification_kwargs=None, channel_id=None, critical=False, android_priority=None, **kwargs): apns_sound = sound if critical: sound_name = sound if sound else "default" apns_sound = messaging.CriticalSound(sound_name, critical=True) notification = None if title and body: notification = messaging.Notification( title=title, body=body, image=icon, ) message = messaging.Message( notification=notification, data=data, token=registration_id, android=messaging.AndroidConfig( priority=android_priority, collapse_key=collapse_key, ttl=time_to_live, restricted_package_name=restricted_package_name, notification=messaging.AndroidNotification( color=color, sound=sound, tag=tag, click_action=click_action, body_loc_key=body_loc_key, body_loc_args=body_loc_args, title_loc_key=title_loc_key, title_loc_args=title_loc_args, channel_id=channel_id, ), ), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( loc_key=body_loc_key, loc_args=body_loc_args, title_loc_key=title_loc_key, title_loc_args=title_loc_args, ), sound=apns_sound, content_available=content_available, badge=badge, ))), ) res = {} try: res["data"] = messaging.send(message, dry_run) except (exceptions.FirebaseError, ValueError) as error: res["error"] = error return {"results": [res]}
def construct_body(title: str, topic: str, category: str = None, data: dict = None, body_text: str = '', alert_sound: str = 'default', critical: bool = False, web_badge: str = '', web_icon: str = '', vibration_pattern: Sequence[int] = None, priority: str = 'normal'): if data is None: data = {} if vibration_pattern is None: vibration_pattern = DEFAULT_VIBRATION_PATTERN android_notification_additional_config = {} aps_additional_config = {} if category is not None: android_notification_additional_config['click_action'] = category aps_additional_config['category'] = category # https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html#//apple_ref/doc/uid/TP40008194-CH17-SW5 fcm_body = { 'data': data, 'android': messaging.AndroidConfig( priority=ANDROID_PRIORITIES[priority], # normal and high ttl=300, notification=messaging.AndroidNotification( title=title, body=body_text, **android_notification_additional_config, ), ), 'webpush': messaging.WebpushConfig( headers={ 'TTL': '300', 'Urgency': priority, # can be very-low, low, normal, or high 'Topic': topic, }, # Send everything in a dict instead so that we can handle the notifications ourselves. data=dict( notification=json.dumps(dict( title=title, body=body_text, # URL for badge icon badge=web_badge, icon=web_icon, # URL for icon # should the user be renotified if an old notification is replaced by a new one # renotify=True, # Should the notification remain active until the user clicks or dismisses it rather than closing automatically require_interaction=False, silent=False, # should the notification be comletely silent regardless of device settings # vibration pattern vibrate=vibration_pattern, )), **data ), # fcm_options=messaging.WebpushFcmOptions( # link='', # link to open when the user clicks on the notification # ), ), 'apns': messaging.APNSConfig( headers={ # The date at which the notification is no longer valid. This value # is a Unix epoch expressed in seconds (UTC). If the value is # nonzero, APNs stores the notification and tries to deliver it at # least once, repeating the attempt as needed until the specified # date. If the value is 0, APNs attempts to deliver the # notification only once and does not store the notification. 'apns-expiration': str(int(datetime.timestamp( datetime.utcnow() + FIVE_MINUTES))), # This should be the default, but we will specify it here manually. # 10 should be immediate, while 5 does it based off of power # considerations. 'apns-priority': IOS_PRIORITIES[priority], # Generally the app's bundle ID. # 'apns-topic': settings.FCM_NOTIFICATIONS['bundle_id'], # 64 bytes at most and is used to collapse notifications if the # notifications are the same. 'apns-collpase-id': topic, }, payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( title=title, # short string that descirbes purpose # subtitle='', body=body_text, # body text of message ), # badge=0, # badge counter sound=messaging.CriticalSound( alert_sound, critical=critical, volume=1), # sound to play content_available=True, # use 1 to indicate that the system has new data to handle # used for grouping along with a Notification Content app extension mutable_content=True, custom_data=data, **aps_additional_config, ), **data ), ), } return fcm_body
def test_invalid_body(self, data): alert = messaging.ApsAlert(body=data) excinfo = self._check_alert(alert) expected = 'ApsAlert.body must be a string.' assert str(excinfo.value) == expected
required=True) parser.add_argument('-c', '--config', help='Firebase private key file path', required=False) args = parser.parse_args() # Environment variables loading from config load_dotenv(dotenv_path=Path('.') / '.env.default') # Initialize firebase SDK firebase_private_key_file_path = args.config or os.getenv('FIREBASE_CONFIG') device_fcm_token = args.token app_credentials = credentials.Certificate(firebase_private_key_file_path) default_app = firebase_admin.initialize_app(app_credentials) message = messaging.Message( apns=messaging.APNSConfig( headers={'apns-priority': '10'}, # 10 - immediate send payload=messaging.APNSPayload( aps=messaging.Aps(alert=messaging.ApsAlert( title_loc_key='sign_transaction_request_title', ), mutable_content=True, badge=1, sound='default'))), data={'type': 'sendTransaction'}, token=device_fcm_token) message_id = messaging.send(message, app=default_app) print('Message id:', message_id)
android=messaging.AndroidConfig( notification=messaging.AndroidNotification( title="변경!", body="변화가 감지됬어요!", default_sound=True, # visibility="public", priority="high", ) ), # notification=messaging.Notification(title="변경!", body="변화가 감지됬어요!",), token=registration_token, ) """ message = messaging.Message( notification=messaging.Notification(title="test", body="페이지 변경 감지!"), apns=messaging.APNSConfig(payload=messaging.APNSPayload(aps=messaging.Aps( alert=messaging.ApsAlert( title="test", body="페이지 변경 감지!", ), badge=42, ), ), ), token=registration_token, ) # Send a message to the device corresponding to the provided # registration token. response = messaging.send(message) # Response is a message ID string. print("Successfully sent message:", response)