def fcm_push_notify(token, full_name, blood_type): push_service = FCMNotification(api_key=FCM_API_KEY) registration_id = token message_title = "Blood Donation Required" message_body = ("%s is requesting blood donation of blood type %s")%(full_name, blood_type) push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) return True
def send_alarm(src): config = { "apiKey": "AAAAXDKjDeY:APA91bHLONjob43L-tynyMAicqee38C9yuAo6rZFdlc25zmCmmnqyrcyG7NIugNLECKIU2q4QpyNPTzN0NsJHTm8SyiuzJOxzL5JPmHwIoJO7LrYDboUJU0-115EXKWpK8vLVJor1-Pi", "authDomain": "homeattender.firebaseapp.com", "databaseURL": "https://homeattender.firebaseio.com/", "storageBucket": "homeattender.appspot.com" } #base firebase setup firebase = firebase.FirebaseApplication('https://homeattender.firebaseio.com/', None) push_service = FCMNotification(api_key=config["apiKey"]) registration_id = "cp5OKaH4C_Y:APA91bEtcHMcJINecS8SpGYMckeO_Jj9HYwyrQXs4jGBObxgrT8yGCYmdh0JHVE4VP0Q0MmlGxH-OOC6ixT9pFNkqfivOke-nTXanJnhbyVkVBK28bT7KMhSH_Mun3SuWRj14xH58e0V3ZAJLpsFFds8BwFjbyXbnQ" #picture pyrebase setup to send from rasp to phone pyrebase = pyrebase.initialize_app(config) storage = pyrebase.storage() #PUSH file_sorce = sprintf(image_name, "/home/pi/lip/LeotonModule/fire_%.4d.jpg", src); picture_name = "fire{}.png".format(time.strftime("%Y%m%d-%H%M%S")) storage.child(picture_name).put(src) time="" msg = "Fire detected!".time firebase.patch('/FireAlarm', {'Info': msg, 'PicName': picture_name}) #NOTIFICATION message_title = "FIRE" message_body = "FIRE HAS BEEN DETECTED" firebase.patch('/', {'Alert': 'off'}) push_service.notify_single_device(registration_id=self.registration_id, message_title=message_title, message_body=message_body) return '0'
def send_message(row): push_service = FCMNotification(api_key=api_key) if row[4] == "NRM": title = "Oei, je hebt een " + row[4] elif float(row[4]) >= 5: title = "Nice, je hebt een " + row[4] + " voor \"" + row[0] + "\"" else: title = "Oei, je hebt een " + row[4] + " voor \"" + row[0] + "\"" if row[3] == "": row[3] = "100" if row[2] == "": row[2] = "undefined" body = "Deze telt " + row[3] + "% mee, voor: \"" + row[1] + "\"" message_title = title message_body = body print('hoi') push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) time.sleep(0.5)
def _send_via_fcm(self, message_title, message_body, channel_id, data): push_service = FCMNotification( api_key=self.external_config['fcm_api_key']) if (message_title and message_body): if channel_id == 'wazo-notification-call': notification = push_service.notify_single_device( registration_id=self.token, data_message=data, extra_notification_kwargs=dict(priority='high')) else: notification = push_service.notify_single_device( registration_id=self.token, message_title=message_title, message_body=message_body, badge=1, extra_notification_kwargs=dict( android_channel_id=channel_id), data_message=data) if notification.get('failure') != 0: logger.error('Error to send push notification: %s', notification) return notification
def send_fcm_notification(message, endpoint): token = endpoint.device_token if settings.FCM_API_KEY: global fcm_client if not fcm_client: fcm_client = FCMNotification(api_key=settings.FCM_API_KEY) fcm_client.notify_single_device(registration_id=token, message_title=settings.FCM_TITLE, message_body=message)
def push_message(message_title, message_body): push_service = FCMNotification( api_key= "AAAAbvxqako:APA91bEfQcwyCtjwvDgkxS6w5ilhij2qJFm0QW-fGpu6eWXyx-li5ENgtIw4ULS2w9Z55jwEU_P6cBhFQRvaH6Hs-6Lw5bV6Fa8_VETZPNx17RbC9OvFWsBZOxcjw6Ftda9QDSHGLTmU" ) registration_ids = 'eTl6bv-xGhM:APA91bHePBBMw8-iCTuIFYPwrDPlunr3dL6Kd825imU7KhgVxBPIF0P-sziHkIVN6A2I4YiW0mNPCZHS3JIaEXZ2gqDq8RMPFd6AR_dmthsvzj68_FnbQkefzWVHsJvy0aACquDWDBHN' push_service.notify_single_device(registration_id=registration_ids, message_title=message_title, message_body=message_body)
def push_to_fcm(device_token, gcm_key, title=None, message=None, data=None, sound=None, badge=None): fcm_push_service = FCMNotification(api_key=gcm_key) fcm_push_service.notify_single_device( registration_id=device_token, message_title=title, message_body=message, data_message=data, sound=sound, badge=badge )
def notify_user_commented(user, pid, sid): from flask import current_app as app content = locales[SupportedLanguage.query.get(user.lang).code]['commented'] push_service = FCMNotification(api_key=app.config['FCM_API_KEY']) push_service.notify_single_device( registration_id=user.fcm_token, message_title=content['title'], message_body=content['body'], data_message={"url": InterviewSession.session_url(pid, sid)})
def send_notification(): push_service = FCMNotification( api_key= "AAAAYZeGLRQ:APA91bFxUFSa1jjVBdx3u6O3hnG5FOX1vb4-AdHtVWmFw5Uz_Z2YqhJbn09YCl05WJn-2b3LNU2Oas5N_pdvfbGdIYOL79t7ogj_SOJ_X86RsBlKJZ3kjEfAg3kodWUr5_Vt1QiIhT-2vAKC1tGGSI7glojgXA1raQ" ) registration_id = "dqKCetGoaNw:APA91bFbr8khPvPk83Np2boHlWXxDDGD7hDj1gvma7mahM41CFMJUuoHMv4Bi5NlfDuhk0lxXBc67RuXJu2RpVAzPkNnxrp89xPpYWI7IAcn9qBX7-0k6C1V0LH0lo0yzP4hQHu4L9IhpVzA3gJF0ii0DhLJdkDfSw" message_title = "Sensor Status" push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body, sound="Default")
def get(self): senderFirstName = self.request.get('firstName') toBucket = self.request.get('toBucket') notification_type = self.request.get('notificationType') registration_id = '' print toBucket """Query that user""" r = User.query(User.user_bucket == toBucket) """Grab their current registration token""" for j in r.fetch(): registration_id = j.registration_token """Initializing the notification service""" push_service = FCMNotification( api_key="AIzaSyC6vzkRMzlOzDjnJwB5TDpcPY7BUQL54Xg") # Sending a notification with data message payload data_message = { "Nick": "Mario", "body": "great match!", "Room": "PortugalVSDenmark" } # To a single device result = push_service.notify_single_device( registration_id=registration_id, data_message=data_message) print result if notification_type == 'like': message_title = 'Tru' message_body = senderFirstName + ' has liked you!' print message_body result = push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body) elif notification_type == 'match': message_title = 'Tru' message_body = 'Congratulations! You have just matched with someone! Introduce yourself!' result = push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body) else: message_title = 'Tru' message_body = senderFirstName + ' has sent you a message!' result = push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body) print result
def send_push_notification(fcm_registration_id, message): logger.info('Starting to build push notification') try: push_service = FCMNotification( api_key=os.environ.get('FIREBASE_API_KEY')) data_message = {"message": message} push_service.notify_single_device( registration_id=fcm_registration_id, data_message=data_message) logger.info('Push notification sent') except Exception as error: logging.error('An exception occurred: {}'.format(error))
def messaging(message_body, category, order, registration_id): data_message = {'category': category, 'order': order} message_title = "completed" api_key = "AIzaSyD85T_x9TX2shewTUJyk6l_LrQboiLM7KU" push_service = FCMNotification(api_key=api_key) push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body, data_message=data_message )
def handle(self, *args, **options): # Initiate connection push_service = FCMNotification(api_key=settings.FCM_SERVER_KEY) # Maintain a count count = 0 # Iterate all upcoming events for event in Event.objects.filter( start_time__range=(timezone.now(), timezone.now() + timedelta(minutes=30)), starting_notified=False): # Stop the spam! event.starting_notified = True event.notify = False event.save() # Event About to Start print('EATS -', event.name) # Construct object data_message = { "type": "event", "id": str(event.id), "title": event.name, "verb": "Event is about to start", "large_icon": event.bodies.first().image_url, "image_url": event.image_url } # Notify all followers for profile in event.followers.prefetch_related('user').all(): # Check bad users if not profile or not profile.user: continue try: # Send rich notification registration_id = profile.fcm_id push_service.notify_single_device( registration_id=registration_id, data_message=data_message) count += 1 except Exception as ex: print(profile.name, ex) print('Sent', count, 'rich notifications') self.stdout.write( self.style.SUCCESS('Event starting chore completed successfully'))
def send_notification(token, name): push_service = FCMNotification( api_key= "AAAAVb5JwQI:APA91bHd-4Rwk92cEDP7vew-iCmKwx5V92KKLsNOaPkya8pF4AhzmmIi29JC3xrqBj3mNHHUO4Y7zVaYqyurtEP1m-PH_eUUcZcMsH2o7ZugxNvTnKImmVReNKXJ4dh-YNL5d_DcXjCG" ) registration_id = token message_title = "Hello " + name message_body = "This is a notification from Flask Backend" data_message = {"notification": "true"} push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body, data_message=data_message)
def send_single_notification(device_id, device_type, data): # send on single device push_service = FCMNotification(api_key=fcm_server_key) registration_id = device_id if device_type == "1": result = push_service.notify_single_device( registration_id=registration_id, data_message=data) else: result = push_service.notify_single_device( registration_id=registration_id, message_body="this is your message", data_message=data) return result
def messaging(message_body, post_pk, registration_id): data_message = { "post_pk": post_pk, } message_title = "패롯의 알림" api_key = "AAAAH9L9RaI:APA91bGPaj0u1ETZd42p7FDUac4Yz2Y8h02TmxvVKIx0hxPfnE4ZGI72-7c7SkkjT84ItTo1VHDiEfo9s-GW5uQ2d6SLmJhhztnuppM0mssxXKJNVRnv-anwum_UyCPpMV1r0aFaOJfmOg93mN1SJrepGKFPruk1hw" push_service = FCMNotification(api_key=api_key) push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body, data_message=data_message, )
def send_fcm_notification(title="", body="", data=None, users=None): """ sends fcm notification to a single or multiple user device :param title: title of the notification message :param body: body of the notification :param data: any data to be sent :param users: list of user ids :return: True/False """ if users: push_service = FCMNotification(api_key=settings.FCM_API_KEY) try: if data: if isinstance(users, list): registration_ids = [ devices.registration_id for devices in UserDevice.objects.filter( used_id__in=users) ] push_service.multiple_devices_data_message( registration_ids=registration_ids, data_message=data) else: registration_id = UserDevice.objects.get( user_id=users).registration_id push_service.single_device_data_message( registration_id=registration_id, data_message=data) else: if isinstance(users, list): registration_ids = [ devices.registration_id for devices in UserDevice.objects.filter( user_id__in=users) ] push_service.notify_multiple_devices( registration_ids=registration_ids, message_title=title, message_body=body) else: registration_id = UserDevice.objects.get( user_id=users).registration_id push_service.notify_single_device( registration_id=registration_id, message_title=title, message_body=body) return True except: return False else: return False
def trigger_notification(attendant_app_id, table_name): """ Triggers a Firebase Cloud message to the particular app ID, alerting the waitstaff. :param attendant_app_id: :param table_name: :return: """ push_service = FCMNotification(api_key=api_key) message_title = "Resty Update" message_body = "{} is requesting your service!".format(table_name) message = { 'message_title': message_title, 'message_body': message_body } result = push_service.notify_single_device( registration_id=attendant_app_id, data_message=message) if result['success'] == 1: return True else: print "Notification error: {}".format(result) return False
class PushNotifyService(object): def __init__(self, api_key): self.push_service = FCMNotification(api_key=API_KEY) @classmethod def from_config(cls): return cls(**NOTIFICATION_CONFIG) def send_push_notification(self, push_id, message_title, message_body): try: self.push_service.notify_single_device(registration_id=push_id, message_title=message_title, message_body=message_body) except: raise PushNotifyError('Error sending notification')
def notifyFire(): # send push alarm push_service = FCMNotification(api_key=PUSH_API_KEY, proxy_dict={}) r = requests.get(SERVER_URL + 'api/tokenLists/' + SERIAL_NUMBER) token_list = r.json()['token_list'] r = requests.get(SERVER_URL + 'api/users/by_serial_number/' + SERIAL_NUMBER) user_data = r.json() for token in token_list: r = requests.get(SERVER_URL + 'api/user_push_data/' + token) user_push_data = r.json()['push_data'] nickname = '' for push_data in user_push_data: if push_data['serial_number'] == SERIAL_NUMBER: nickname = push_data['nickname'] break data = { "title": "Fire!", "message": u"%s(%s) 에서 화재 발생!" % (user_data['address'], nickname) } result = push_service.notify_single_device(registration_id=token, data_message=data)
def fcm_send_message(registration_id, title=None, body=None, icon=None, data=None, sound=None, badge=None, low_priority=None, condition=None, time_to_live=None, click_action=None, collapse_key=None, **kwargs): api_key = SETTINGS.get("FCM_SERVER_KEY") push_service = FCMNotification(api_key=api_key) result = push_service.notify_single_device(registration_id=registration_id, message_title=title, message_body=body, message_icon=icon, data_message=data, sound=sound, badge=badge, collapse_key=collapse_key, low_priority=low_priority, condition=condition, time_to_live=time_to_live, click_action=click_action, **kwargs) # do not raise errors, pyfcm will raise exceptions if response status will # be anything but 200 return result
def send_images(cust_id): # checks if customer folder exists if not os.path.exists(os.path.join(path, cust_id)): os.makedirs(os.path.join(path, cust_id)) # get the current number of images on customer folder number = 1 images = request.files.getlist("images") data_message = {} for img in images: img.save(os.path.join(path, cust_id, f"{number}.jpg")) data_message[ f"image_{number}"] = f"http://134.119.194.237:7000/static/highstone/{number}.jpg/47f6da8f-4409-48c4-86d2-3b926f3cbf54/" number += 1 #send notification cur = mysql.connection.cursor() cur.execute("SELECT token FROM user WHERE username='******'".format(cust_id)) token = cur.fetchone() push_service = FCMNotification(api_key=fb_api_key) registration_id = str(f"{token['token']}") message_title = "Danger Detected!" message_body = "A Danger situation happened on oven. Due to this danger situation Nuriel turned off the oven. Please verify this stiuation!" result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body, data_message=data_message) # 1123123/static/1.jpg return jsonify(message='image received.', status=200)
def senf_by_pyfcm(self): push_service=FCMNotification(api_key=VALID_API_KEY) result=push_service.notify_single_device( registration_id=get_devies_tokens, message_title=self.title, message_body=self.content) return result
def xsss(): req_data = request.get_json() targetUrl = req_data['url'] device_token = req_data['reg_token'] try: testIp = socket.gethostbyname(targetUrl) except: return jsonify(result=False) ##f=open("xssReport.txt","w") hashToken = hashlib.md5(device_token).hexdigest() fileName = req_data['filename'] fileName = hashToken + '_' + fileName #fileName=fileName+".txt" #with open(fileName,'w') as f: #subprocess.call(["python","xsssnipertest.py","-u",targetUrl],stdout=f) #convert.convert_txt_pdf(fileName) xss_inter(targetUrl, fileName) push_service = FCMNotification( api_key="AIzaSyB4BBdlKyxQaB9ZBL1U4ynZz3nDNW9vsmo") registration_id = device_token data = { "title": "XSS Report", "message": "Your report " + req_data['filename'] + " for XSS has been generated" } #message_title = "XSS Report" #message_body = "Your report has been generated" result = push_service.notify_single_device(registration_id=registration_id, data_message=data) return jsonify(reportGenerated=True)
def test_nessus(): req_data = request.get_json() testUrl = req_data['url'] scanName = req_data['name'] device_token = req_data['reg_token'] hashToken = hashlib.md5(device_token).hexdigest() testIp = gethostbyname(testUrl) reportName = scanName + ".pdf" reportName = hashToken + '_' + reportName path_report = "/home/tejas/Desktop/website/" + reportName client = TenableIOClient( access_key= '135b739644f7f56f6e39fa6f45d00ccdc199fb15793ddf324a7ad0e4526e1b95', secret_key= 'ff6d61f566c11479154f68dc8f0a6ebf35aa961d65329a01a41349638face336') scan = client.scan_helper.create(name=scanName, text_targets=testIp, template='basic') scan.launch().download(path_report, scan.histories()[0].history_id) #path_from_pdf="/home/ubuntu/website/"+reportName path_to_pdf = "/home/tejas/Desktop/website/static/reports/nessus/" + reportName subprocess.call(["mv", path_report, path_to_pdf]) push_service = FCMNotification( api_key="AIzaSyB4BBdlKyxQaB9ZBL1U4ynZz3nDNW9vsmo") data = { "title": "Nessus Report", "message": "Your report " + req_data['name'] + " for Nessus has been generated" } #message_title = "Nessus Report" #message_body = "Your report has been generated" result = push_service.notify_single_device(registration_id=device_token, data_message=data) return jsonify(reportGenerated=True)
class FCMSender: def __init__(self, server_key): self.push_service = FCMNotification(api_key=server_key) def send(self, title, message, registration_id=None): message_title = title message_body = message if registration_id is None: result = self.push_service.notify_topic_subscribers(topic_name='all', message_title=message_title, message_body=message_body) else: result = self.push_service.notify_single_device(registration_id=registration_id, message_body=message_body, message_title=message_title) print(result) return result @staticmethod def get_clients_to_push(): rows = database.Database().execute(query_formats.get_registration_id_format) clients_to_push = list() for row in rows: clients_to_push.append(row['registration_key']) return clients_to_push
def send_dyanamic_test(): from pyfcm import FCMNotification # from functions.sqlquery import sql_query import schedule import time push_service = FCMNotification( api_key= "AAAAYNJto2I:APA91bEHdYbm2mhUfGfBIWseFzintaOJgJDifgSyzJdfcZrCyUdLD9XPwSKlX6IMaOeXNMkdTSs52mGKVequsJ_JtdZcq-6e15L9UzjHhs2JaMhcHmpDPgBu0D0bmPyXO2pqHa2Q0q0d" ) #registration_id = "e-nFqTWX25w:APA91bE2X84_I30e2XZE4assg0qWea0VZjRr_liIREzYMWviaxg67Fh13iIp44-Wwi4XynZnMveC98hOEaWf3BTy1mEvF3FpEY8LXLfrY8ipZO2JGGwyw4_UAmr0yNv2matfY20UJ9Ow" registration_id = "f8bLCD9kaoI:APA91bGN7uLHIZyefhLFBLa_HvHedRH7sq-o-LFKelIEkV9NS_ZGCrFVUePsySHjaeZZoWREfRkwF6LEcF-Z1vYpzfybfGJb7hMIwfdknVQzPcneWMsBpFsLDIlw4A7QAzFSS9vO9lVL" message_title = [ "We think you will love", "Indipendance Day Sale", "Sunday Special", "Happy Birthday" ] message_body = [ "Boat bassheadz earphones (Frosty White)", "Celebrate independance day with Rs.100 off", "Enjoy your holiday with Rs. 1000 off", "Celebrate your Birthday with Rs. 50 off" ] result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title[1], message_body=message_body[1]) return jsonify(result)
def send_product_notification(): from functions.sqlquery import sql_query2 from pyfcm import FCMNotification user_id = request.form['user_id'] prod_id = sql_query2( ''' SELECT * from user_side_notifications where user_id = ?''', (user_id, )) prod_id = prod_id[-1][1] #time = prod_id[0][1] # return jsonify(time) best_product = sql_query2( ''' SELECT name from product_table where product_id =?''', (prod_id, )) best_product = best_product[-1][0] time_id = get_time() # return "hora hai" push_service = FCMNotification( api_key= "AAAAYNJto2I:APA91bEHdYbm2mhUfGfBIWseFzintaOJgJDifgSyzJdfcZrCyUdLD9XPwSKlX6IMaOeXNMkdTSs52mGKVequsJ_JtdZcq-6e15L9UzjHhs2JaMhcHmpDPgBu0D0bmPyXO2pqHa2Q0q0d" ) registration_id = "f8bLCD9kaoI:APA91bGN7uLHIZyefhLFBLa_HvHedRH7sq-o-LFKelIEkV9NS_ZGCrFVUePsySHjaeZZoWREfRkwF6LEcF-Z1vYpzfybfGJb7hMIwfdknVQzPcneWMsBpFsLDIlw4A7QAzFSS9vO9lVL" message_title = "We think you will love" message_body = best_product # + time_id result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) return jsonify(result)
def post(self): try: args = parser.parse_args() watch_id = args['watch_id'] fall_result = args['fall_result'] db = pymysql.connect(host=HOST, user=USER, password=PASSWORD,charset='utf8', db=DB) cusor = db.cursor(pymysql.cursors.DictCursor) wear_sql = "SELECT * FROM watch_wear WHERE watch_id=%s" cusor.execute(wear_sql, (watch_id)) wear_result = cusor.fetchone() if wear_result["wear"] == 1: search_sql = "SELECT * FROM watch_user WHERE watch_id=%s" cusor.execute(search_sql, (watch_id)) res = cusor.fetchone() name = res["name"] print(watch_id, fall_result) push_service = FCMNotification(api_key="AAAAFWjNWao:APA91bGA4SV9-2Uy0OuaHE0rtHDKG9ld_CSlygKrl1kyDn-1pn78yTVB_0fxx2Pjg3vthMkBbetI0qI-ZInMYPhTsGTDCVA72ElIZq35BZ68rFtrDskmY1Pc-CP5I3miuOu0411wVajK") registration_id = "fIqUj9dG7zk:APA91bEBS5WJLjaPd3wjFeD4Wrb8xaGotpFpZUkqWyw2Bc6TU7PlKEFDsPcoIQpqqYBTL1B9_sxQEsZ07gunQlqL4Jm_dD1BKs8pdevJDOoSI6mjGbwPQ8bqexT-x_-MJ9EYefjn1wmw" message_title = "실버워치 낙상 알림" message_body = f"{name} 낙상 감지됨." result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) cusor.close() db.close() return {"status" : 1, "fall_result": fall_result} except Exception as e: print(e) return {"status": 0}
def testSsl(): req_data = request.get_json() testUrl = req_data['url'] device_token = req_data['reg_token'] '''try: testIp=socket.gethostbyname(targetUrl) except: return jsonify( result=False )''' hashToken = hashlib.md5(device_token).hexdigest() fileName = req_data['filename'] fileName = hashToken + '_' + fileName ssl_inter(testUrl, fileName) '''fileName=fileName+".txt" with open(fileName,'w') as f: subprocess.call(["./testssl.sh","-U",testUrl],stdout=f) convert.convert_txt_pdf(fileName)''' push_service = FCMNotification( api_key="AIzaSyB4BBdlKyxQaB9ZBL1U4ynZz3nDNW9vsmo") registration_id = device_token data = { "title": "SSL Report", "message": "Your report " + req_data['filename'] + " for SSL has been generated" } #message_title = "SSL Report" #message_body = "Your report has been generated" result = push_service.notify_single_device(registration_id=registration_id, data_message=data) return jsonify(reportGenerated=True)
def MOTION (PIR_PIN): print ("Motion detected by PIR. E-mail notification sent") addTimeToNotification() print (notificationTime) camera() push_service = FCMNotification(api_key="AIzaSyBxUGqEvrIxL0-5-wzfhr2EjmHXdQe3vcA") message_title = "Varsel" message_body = "Bevegelse oppdaget av bevegelsessensor" result = push_service.notify_single_device(registration_id=registration, message_title=message_title, message_body=message_body) print result #print registration #writelog() sleep(5)
def push_test_ios(request): push_service = FCMNotification(api_key="AAAAwJiGQL0:APA91bH0yzNqpkRvB8hgnz64g-OKSjjGJADjtr8njfmY_EuucOAXFciONvfn9ooxqkkPHb3Mt9wZ2LLEEfQn4KFVkKfS8A_7sMQh9mjHUXsGLBseO31m_zOy9c39k3wwim8x0ojvw6ia") title_ios = str("구독중인 "+ "헿" + " 이/가 변경되었습니다!") message_ios = str("민섭이혀엉~") try: toke_ = ["ec575CPxhj8:APA91bEd64mo-Qw_a6mKYmEIgJ3ui4_qOv_6Cd96XRoHiDeR_IX_zbliwvdNDyNAbASmut9tuPPgY00MzUlVRP33x11I6YxfRY2T-Syli8U0FeJ1L2AuClaIa5PhbzR0uLvouDmOwfXQ"] result = push_service.notify_single_device(registration_id=toke_[0], message_title=title_ios, message_body=message_ios) # result = push_service.notify_multiple_devices(message_title=title_ios, message_body=message_ios, registration_ids=toke_, data_message={}) except Exception as e: print(e) return render(request, 'refresh/push_server_page.html')
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, **kwargs): """ Copied from https://github.com/olucurious/PyFCM/blob/master/pyfcm/fcm.py: Send push notification to a single device Args: registration_id (str): FCM device registration IDs. body (str): Message string to display in the notification tray data (dict): Data message payload to send alone or with the notification message sound (str): The sound file name to play. Specify "Default" for device default sound. Keyword Args: collapse_key (str, optional): Identifier for a group of messages that can be collapsed so that only the last message gets sent when delivery can be resumed. Defaults to ``None``. delay_while_idle (bool, optional): If ``True`` indicates that the message should not be sent until the device becomes active. time_to_live (int, optional): How long (in seconds) the message should be kept in FCM storage if the device is offline. The maximum time to live supported is 4 weeks. Defaults to ``None`` which uses the FCM default of 4 weeks. low_priority (boolean, optional): Whether to send notification with the low priority flag. Defaults to ``False``. restricted_package_name (str, optional): Package name of the application where the registration IDs must match in order to receive the message. Defaults to ``None``. dry_run (bool, optional): If ``True`` no message will be sent but request will be tested. Returns: :tuple:`multicast_id(long), success(int), failure(int), canonical_ids(int), results(list)`: Response from FCM server. Raises: AuthenticationError: If :attr:`api_key` is not set or provided or there is an error authenticating the sender. FCMServerError: Internal server error or timeout error on Firebase cloud messaging server InvalidDataError: Invalid data provided InternalPackageError: JSON parsing error, mostly from changes in the response of FCM, create a new github issue to resolve it. """ if api_key is None: api_key = SETTINGS.get("FCM_SERVER_KEY") push_service = FCMNotification(api_key=api_key, json_encoder=json_encoder) result = push_service.notify_single_device( registration_id=registration_id, message_title=title, message_body=body, message_icon=icon, data_message=data, sound=sound, badge=badge, collapse_key=collapse_key, low_priority=low_priority, condition=condition, time_to_live=time_to_live, click_action=click_action, delay_while_idle=delay_while_idle, restricted_package_name=restricted_package_name, dry_run=dry_run, color=color, tag=tag, body_loc_key=body_loc_key, body_loc_args=body_loc_args, title_loc_key=title_loc_key, title_loc_args=title_loc_args, content_available=content_available, extra_kwargs=extra_kwargs, **kwargs ) # do not raise errors, pyfcm will raise exceptions if response status will # be anything but 200 return result
"address_line_two" : "MAIN AREA OF SERVICE", "area" : 1000, "date" : "20 July 2016", "location" : "Some Restaurant", "time" : "12:30 PM" }, { "address_line_one" : "Some location, some other sub location, Location", "address_line_two" : "MAIN AREA OF SERVICE", "area" : 1000, "date" : "20 July 2016", "location" : "Some Restaurant", "time" : "12:30 PM" }, { "address_line_one" : "Some location, some other sub location, Location", "address_line_two" : "MAIN AREA OF SERVICE", "area" : 1000, "date" : "20 July 2016", "location" : "Some Restaurant", "time" : "12:30 PM" } ] } # push_service.notify_single_device is actuall fuction which send notification result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body, data_message=data_message) # print notification reached data print result
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'olucurious' from pyfcm import FCMNotification push_service = FCMNotification(api_key="<api-key>") registration_id="<device registration_id>" message = "Hi john, your Uber driver is around" result = push_service.notify_single_device(registration_id=registration_id, message_body=message) print result