def send_notification(app_id): api_key = "AIzaSyBzAFQ19gB3BctG6VL8lO85VWf8I-vD_Gs" gcm = GCM(api_key) data = {'title': 'Notify', 'extra': "Welcome to Arduino"} print(data) response = gcm.json_request(registration_ids=[app_id], data=data) return response
def handle(self, *args, **options): gcm = GCM(settings.GOOGLE_API_KEY) for uuid in set(DeviceToken.objects.all().values_list('uuid', flat=True)): tok = DeviceToken.objects.filter(uuid=uuid).order_by('created_at')[0] payload = {} payload['title']="%s" % (get_district(tok.lat, tok.lng)) payload['message']= "%s " % (get_weathersummary(tok.lat, tok.lng)[1]) payload['timeStamp']=str(time.time()) payload['lat']=str(tok.lat) payload['lng']=str(tok.lng) payload['notId']="101" try: canonical_id = gcm.plaintext_request(registration_id=tok.token, data=payload) if canonical_id: token = DeviceToken.objects.filter(token=tok.token) token.token = canonical_id token.save() self.stdout.write('Sent to [%s].' % tok.token, ending='') except : token = DeviceToken.objects.filter(token=tok.token) token.delete() self.stdout.write('Deleted [%s].' % tok.token, ending='')
def __init__(self, config, log): Sender.__init__(self, config, log) self.access_key = config.get('Messenger', 'gcm_access_key') self.base_deeplink_url = config.get('Messenger', 'base_deeplink_url') self.gcm = GCM(self.access_key) self.canonical_ids = [] self.unregistered_devices = []
def checkDataAndNotify(): profiles = Profile.objects.all() data = {} currentTime = time.time() recentTime = currentTime - 24 * 3600 for profile in profiles: dbName = "User_" + str(profile.id) collection = connection[dbName]["funf"] newNotifications = False recentEntries = collection.find({ "time": {"$gte": recentTime }}) if (recentEntries.count() == 0): addNotification(profile, 1, "Stale behavioral data", "Analysis may not accurately reflect your behavior.", None) newNotifications = True #addNotification(profile, 2, "Survey", "Take this survey", "/survey/?survey=1"); #newNotifications = True if (newNotifications and Device.objects.filter(datastore_owner = profile).count() > 0): gcm = GCM(settings.GCM_API_KEY) #addNotification(profile, 2, "Push successful", "Push notifications are working properly.") for device in Device.objects.filter(datastore_owner = profile): #pdb.set_trace() gcm.plaintext_request(registration_id=device.gcm_reg_id,data= { "action":"notify" })
def processGCMRequest(): apiKey = "AIzaSyDTJukW0BARTSXHRiWPCt8y_e17A9PuYfg" gcm = GCM(apiKey) data = request.json notificationTitle = data['notificationTitle'] notificationBody = data['notificationBody'] tags = data['tags'] allSubscriptions = Subscriptions.objects.all() regIdList = [] for subscription in allSubscriptions: if (len(set(tags).intersection(set(subscription.subscriptionList))) and subscription.pushAllowed == "true"): regIdList.append(subscription.registrationId) if (len(regIdList) != 0): newNotification = Notifications() newNotification.notificationTitle = notificationTitle newNotification.notificationBody = notificationBody newNotification.registrationIds = regIdList newNotification.save() response = gcm.json_request(registration_ids=regIdList, data=data) return jsonify({ "notification_title": notificationTitle, "notification_text": notificationBody })
def makeDecision(request): logger.debug(request.body) json_data = json.loads(request.body) user_id = json_data["user_id"] options = json_data["options"] asked_to = json_data["asked_to"] asked_by_user = User.objects.get(id=user_id) question = Question(statement=json_data["question"], date_time_asked=datetime.datetime.now(), asked_by=asked_by_user) question.save() self_vote = Vote(user_id=asked_by_user, question=question) self_vote.save() for i in options: option = Option(name=i, quest_id=question.id) option.save() question.options.add(option) gcm_ids = [] for i in asked_to: user = User.objects.get(phone=i) vote = Vote(user_id=user, question=question) vote.save() gcm_ids.append(user.gcm_id) gcm = GCM(settings.GCM_API_KEY) data = {"action": "Requesting your Opinion"} gcm_status = gcm.json_request(registration_ids=gcm_ids, data=data) logger.debug(gcm_status) serializer = QuestionSerializer(question, context={'user_id': user_id}) return JSONResponse(serializer.data)
def sendGCMNotification(registrationTokenList, message): gcm = GCM(GCM_API_KEY) #print 'send message to gcm registration ids ' + ', '.join(registrationTokenList) retVal = gcm.json_request(registration_ids=registrationTokenList, data={"message": message}, delay_while_idle=False) return retVal
def make_request(self, api_key, message): gcm = GCM(api_key) response = gcm.json_request(**message.content) invalid_reg_ids = 0 # Handling errors if 'errors' in response: for error, reg_ids in response['errors'].items(): # Check for errors and act accordingly if error in ['NotRegistered', 'InvalidRegistration']: invalid_reg_ids += GCMDevice.objects.filter( registration_id__in=reg_ids).update(is_active=False) if 'canonical' in response: for reg_id, canonical_id in response['canonical'].items(): # Replace reg_id with canonical_id GCMDevice.objects.filter(registration_id=reg_id).update( registration_id=canonical_id) status = GCMMessage.STATUSES.DELIVERED if len(message.content['registration_ids']) == invalid_reg_ids: status = GCMMessage.STATUSES.ERROR elif invalid_reg_ids > 0: status = GCMMessage.STATUSES.PARTIALLY_DELIVERED return status, response
def checkDataAndNotify(): profiles = Profile.objects.all() data = {} currentTime = time.time() recentTime = currentTime - 24 * 3600 for profile in profiles: dbName = "User_" + str(profile.id) collection = connection[dbName]["funf"] newNotifications = False recentEntries = collection.find({"time": {"$gte": recentTime}}) if (recentEntries.count() == 0): addNotification( profile, 1, "Stale behavioral data", "Analysis may not accurately reflect your behavior.", None) newNotifications = True #addNotification(profile, 2, "Survey", "Take this survey", "/survey/?survey=1"); #newNotifications = True if (newNotifications and Device.objects.filter(datastore_owner=profile).count() > 0): gcm = GCM(settings.GCM_API_KEY) #addNotification(profile, 2, "Push successful", "Push notifications are working properly.") for device in Device.objects.filter(datastore_owner=profile): #pdb.set_trace() gcm.plaintext_request(registration_id=device.gcm_reg_id, data={"action": "notify"})
class PushThread(threading.Thread): def __init__(self): super(PushThread, self).__init__() self.gcm = GCM('AIzaSyC3CwECHoUqHKNQXbndpRWPjgauYhXTUEI') self.message_queue = Queue.Queue() self._break = False def stop_thread(self): self._break = True def run(self): print 'worker is running...' while not self._break: if not self.message_queue.empty(): message = self.message_queue.get() try: print 'worker does his job: ' + message.__str__() reg_id=Contacts.ids[str(message.receiver)] data = message.jsonify() self.gcm.plaintext_request(registration_id=reg_id, data=data) except: traceback.print_exc() else: time.sleep(5) print 'worker got off the work' def put_message(self, gcm_message): if isinstance(gcm_message, Message): self.message_queue.put(gcm_message) else: print 'put_message error'
def send_push(token, data): try: gcm = GCM(constants.GCM_PUSH_API_KEY) response = gcm.json_request(registration_ids=[token], data=data) except Exception, e: print e pass
def validate_duplicate(doc,method): if doc.get("__islocal"): res=frappe.db.sql("select name from `tabZones` where (zone_name='%s' or zone_code='%s') and region='%s'"%(doc.zone_name,doc.zone_code,doc.region)) frappe.errprint(res) if res: frappe.throw(_("Zone '{0}' already created with same Zone Name '{1}' or Zone Code '{2}' for Region '{3}'..!").format(res[0][0],doc.zone_name,doc.zone_code,doc.region)) notify_msg = """Dear User,\n Region is created with name '%s' for region '%s' \n \n Regards,\n Love World Synergy"""%(doc.zone_name,doc.region) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='on_creation_of_a_new_cell_pcf_church'""",as_list=1) if "Email" in notify[0][0]: if doc.contact_email_id: frappe.sendmail(recipients=doc.contact_email_id, content=notify_msg, subject='Region Creation Notification') if "SMS" in notify[0][0]: if doc.contact_phone_no: send_sms(doc.contact_phone_no, notify_msg) if "Push Notification" in notify[0][0]: data={} data['Message']=notify_msg gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res1=frappe.db.sql("select device_id from tabUser where name ='%s'" %(doc.contact_email_id),as_list=1) frappe.errprint(res1) if res1: res1 = gcm.json_request(registration_ids=res1, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600)
def notify_users(title, message, description=None, fragmentId=None, subFragmentId=None, dev_news=False, telegram_message=None): '''New Article #Victory in Berlin #Schwedt #2#0 New Competition #Schwedt vs. Berlin#1. Bundesliga - Staffel A#4#1 Developer Heading#Developer Message ''' if dev_news: msg = "#".join([title, message]) else: msg = "#".join([title, message, description, str(fragmentId), str(subFragmentId)]) gcm_token_objects = json.loads(send_get('/get_tokens'))['result'] gcm = GCM(GCM_KEY) data = {'update': msg} sent_requests = 0 receivers = [] for token in gcm_token_objects: if token not in receivers: gcm_push_response = gcm.json_request(registration_ids=[token], data=data) if bool(gcm_push_response): print token[:20] + " is invalid. Sending request to remove it." send_post({"token": token}, "/delete_token") else: print u"Sent {} to {}".format(msg.encode("ascii", "ignore"), token[:20]) receivers.append(token) sent_requests += 1 else: print token[:20] + " is already saved. Sending request to remove it." send_post({"token": token}, "/delete_token") print "Sent to " + str(sent_requests) + " receivers" send_to_slack("New notification: " + msg, important=False) if telegram_message: notify_telegram_channel(telegram_message)
def push_to_user(user, sender, type): data = { 'type': type, 'target_jid': user.key().name(), 'nudger': sender.first_name, 'toFn': user.first_name, 'toLn': user.last_name } gcm = GCM(API_KEY) response = gcm.json_request(registration_ids=user.gcm_registration_ids, data=data) # Handling errors if 'errors' in response: for error, reg_ids in response['errors'].items(): # Check for errors and act accordingly if error is 'NotRegistered': # Remove reg_ids from database for reg_id in reg_ids: user.gcm_registration_ids.remove(reg_id) user.put() if 'canonical' in response: for reg_id, canonical_id in response['canonical'].items(): # Repace reg_id with canonical_id in your database user.gcm_registration_ids.remove(reg_id) user.gcm_registration_ids.append(canonical_id) user.put()
def processGCMRequest(): apiKey="AIzaSyDTJukW0BARTSXHRiWPCt8y_e17A9PuYfg" gcm = GCM(apiKey) data = request.json notificationTitle = data['notificationTitle'] notificationBody = data['notificationBody'] tags = data['tags'] allSubscriptions = Subscriptions.objects.all() regIdList = [] for subscription in allSubscriptions: if( len(set(tags).intersection(set(subscription.subscriptionList))) and subscription.pushAllowed == "true"): regIdList.append(subscription.registrationId) if(len(regIdList) !=0): newNotification = Notifications() newNotification.notificationTitle = notificationTitle newNotification.notificationBody = notificationBody newNotification.registrationIds = regIdList newNotification.save() response = gcm.json_request(registration_ids=regIdList,data=data) return jsonify({"notification_title" : notificationTitle, "notification_text" : notificationBody})
def post(self): super(NewResourceHandler, self).post() kind = self.data['kind'] if kind == 'sms': key = self.account.send_message_to( phones=self.data['recipients'], content=self.data['content'] ) elif kind == 'link': key = self.account.send_link( url=self.data['url'] ) # Make a GCM call to phone with user's reg_id and # the entity key to retrieve from datastore if not DEBUG: gcm = GCM(API_KEY) gcm.plaintext_request( registration_id=self.account.registration_id, data={'key': key}, collapse_key=str(key) ) self.response.out.write("OK")
def send_to_gcm(device_list, data, collapse_key=None, ttl=43200): if len(device_list or []) == 0 or (data or {}) == {}: return ([], []) gcm = GCM(CONFIG['notifications']['gcm']['api_key']) kargs = { 'registration_ids': device_list, 'data': data, 'time_to_live': ttl } if collapse_key is not None: kargs['collapse_key'] = collapse_key response = gcm.json_request(**kargs) devices_ok = [] devices_to_remove = [] # Delete not registered or invalid devices if 'errors' in response: devices_to_remove = response['errors'].get('NotRegistered', []) devices_to_remove += response['errors'].get('InvalidRegistration', []) if 'canonical' in response: for old_id, canonical_id in response['canonical'].items(): devices_ok.append(canonical_id) devices_to_remove.append(old_id) return (devices_ok, devices_to_remove)
def send_notification(app_id): api_key="AIzaSyBzAFQ19gB3BctG6VL8lO85VWf8I-vD_Gs" gcm=GCM(api_key) data = {'title':'Notify','extra': "Welcome to Arduino"} print(data) response = gcm.json_request(registration_ids=[app_id], data=data) return response
def validate_duplicate(doc,method): if doc.get("__islocal"): res=frappe.db.sql("select name from `tabGroup Churches` where church_group='%s' and church_group_code='%s' and zone='%s'"%(doc.church_group,doc.church_group_code,doc.zone)) if res: frappe.throw(_("Another Group Church '{0}' With Group Church Name '{1}' and Church Group Code '{2}' exist in Zone '{3}'..!").format(res[0][0],doc.church_group,doc.church_group_code,doc.zone)) notify_msg = """Dear User,\n\n Group Church is created with name '%s' for zone '%s'. \n\nRegards,\n\n Love World Synergy"""%(doc.church_group,doc.zone) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='on_creation_of_a_new_cell_pcf_church'""",as_list=1) if notify: if "Email" in notify[0][0]: if doc.contact_email_id: frappe.sendmail(recipients=doc.contact_email_id, content=notify_msg, subject='Group Church Creation Notification') if "SMS" in notify[0][0]: if doc.contact_phone_no: send_sms(doc.contact_phone_no, notify_msg) if "Push Notification" in notify[0][0]: data={} data['Message']=notify_msg gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res1=frappe.db.sql("select device_id from tabUser where name ='%s'" %(doc.contact_email_id),as_list=1) frappe.errprint(res1) if res1: res1 = gcm.json_request(registration_ids=res1, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) ofc = frappe.new_doc("Offices") ofc.office_id = doc.name ofc.office_name = doc.church_group ofc.office_code = doc.church_group_code ofc.insert()
def send_message_device(reg_id, titre, message): gcm = GCM("AIzaSyDDA-TLkhjp-WWYPrVs0DznzQc0b77XGO0") data = {"data":[{'titre': titre, 'message': message}]} reg_ids = [reg_id] # JSON request gcm.json_request(registration_ids=reg_ids, data=data)
def send_message_device_invit(reg_id, titre, message, type_notif, moment_id): gcm = GCM("AIzaSyDDA-TLkhjp-WWYPrVs0DznzQc0b77XGO0") data = {"data":[{'titre': titre, 'message': message, "type_notif":type_notif, "moment_id": moment_id}]} reg_ids = [reg_id] # JSON request gcm.json_request(registration_ids=reg_ids, data=data)
def assignmember(memberid,ftv): frappe.db.sql("""update `tabFirst Timer` set ftv_owner='%s' where name='%s' """ % (memberid,ftv)) # recipients='*****@*****.**' member=frappe.db.sql("select member_name,email_id,phone_1 from `tabMember` where name='%s'"%(memberid)) member_ph = frappe.db.sql("select phone_1 from `tabMember` where name='%s'"%(memberid)) ftvdetails=frappe.db.sql("select ftv_name,email_id,task_description,due_date,phone_1 from `tabFirst Timer` where name='%s'"%(ftv)) ftv_ph = frappe.db.sql("select phone_1 from `tabMember` where name='%s'"%(ftv)) msg_member="""Hello %s,\n The First Timer '%s' name: '%s' Email ID: '%s' is assigned to you for follow up.\n Regards,\n Verve """%(member[0][0],ftv,ftvdetails[0][0],ftvdetails[0][1]) msg_ftv="""Hello %s,\n The Member '%s' name: '%s' Email ID: '%s' is assigned to you for follow up.\n Regards, \n Verve """%(ftvdetails[0][0],memberid,member[0][0],member[0][1]) desc="""Member '%s' is assigned to First Timer '%s' for followup."""%(memberid,ftv) task=frappe.get_doc({ "doctype": "Task", "subject": "Assign For followup", "expected_start_date":nowdate(), "expected_start_date":add_days(nowdate(),2), "status": "Open", "project": "", "description":desc }).insert(ignore_permissions=True) if frappe.db.exists("User", ftvdetails[0][1]): frappe.share.add("Task", task.name, ftvdetails[0][1], write=0) if frappe.db.exists("User", member[0][1]): frappe.share.add("Task", task.name, member[0][1], write=1) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='assign_for_followup'""",as_list=1) if "Email" in notify[0][0]: if member: frappe.sendmail(recipients=member[0][1], content=msg_member, subject='Assign For FollowUp Notification') if ftvdetails: frappe.sendmail(recipients=ftvdetails[0][1], content=msg_ftv, subject='Assign For FollowUp Notification') if "SMS" in notify[0][0]: if member_ph: send_sms(member_ph[0], msg_member) if ftv_ph: send_sms(ftv_ph[0], msg_ftv) if "Push Notification" in notify[0][0]: data={} data['Message']=msg_member gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res=frappe.db.sql("select device_id from tabUser where name ='%s'" %(member[0][1]),as_list=1) frappe.errprint(res) if res: res = gcm.json_request(registration_ids=res, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) # receiver_list=[] # receiver_list.append(member[0][2]) # frappe.errprint(['rev[0]',receiver_list[0]]) # if receiver_list[0] : # frappe.errprint(receiver_list[0]) # send_sms(receiver_list, cstr(msg_member)) # frappe.sendmail(recipients=member[0][1], sender='*****@*****.**', content=msg_member, subject='Assign for follow up') # frappe.sendmail(recipients=ftvdetails[0][1], sender='*****@*****.**', content=msg_ftv, subject='Assign for follow up') return "Done"
def message_braudcast_send(data): """ this will return recipents details """ dts=json.loads(data) from frappe.model.db_query import DatabaseQuery qry="select user from __Auth where user='******'username'])+"' and password=password('"+cstr(dts['userpass'])+"') " valid=frappe.db.sql(qry) msg='' if not valid: return { "status":"401", "message":"User name or Password is incorrect" } if dts['sms']: from erpnext.setup.doctype.sms_settings.sms_settings import send_sms rc_list=frappe.db.sql("select phone_1 from tabMember where phone_1 is not null and email_id in ('%s') limit 3" %(dts['recipents'].replace(",","','")),as_list=1) if rc_list: send_sms([ x[0] for x in rc_list ], cstr(dts['message'])) msg+= "SMS " rc_list=dts['recipents'].split(',') if dts['push']: data={} data['Message']=dts['message'] gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res=frappe.db.sql("select device_id from tabUser where name in ('%s')" % "','".join(map(str,rc_list)),as_list=1) if res: res = gcm.json_request(registration_ids=res, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) msg+= "Push notification" if dts['email']: frappe.sendmail(recipients=dts['recipents'], sender='*****@*****.**', content=dts['message'], subject='Broadcast Message') msg+=" Email" return msg +" sent Successfully"
def sendMessageGcmtest(registration_ids,message): '''url="https://android.googleapis.com/gcm/send" headers = {'Authorization': 'key='+gcm["GOOGLE_API_KEY"], 'Content-Type':'application/json'} payload = {'registration_ids': registration_ids, 'data': message} r = requests.post(url, data, headers=headers) print json.dumps(payload) print r''' results="" reg="" gcm = GCM(gcm_api["GOOGLE_API_KEY"]) data = {'warning': message} condition_gcm="SELECT gcm_regid FROM gcm_users" try: cursor.execute(condition_gcm) results = cursor.fetchall() #reg=results[0][0] for reg in results: reg=[reg[0]] response = gcm.json_request(registration_ids=reg, data=data) print response reg #print results except: print "error" reg=[reg] print reg
def _send_gcm_to_token(token_key, message): logging.info("Executing deferred task: _send_gcm_to_token, %s, %s" % (token_key, message)) token = dao.get_gcm_token_for_key(token_key) gcm = GCM(dao, sys.modules[__name__]) gcm.send_gcm([token], message)
def validate_duplicate(doc,method): if doc.get("__islocal"): res=frappe.db.sql("select name from `tabZones` where (zone_name='%s' or zone_code='%s') and region='%s'"%(doc.zone_name,doc.zone_code,doc.region)) if res: frappe.throw(_("Zone '{0}' already created with same Zone Name '{1}' or Zone Code '{2}' for Region '{3}'..!").format(res[0][0],doc.zone_name,doc.zone_code,doc.region)) notify_msg = """Dear User,\n\n Zone is created with name '%s' for region '%s'.\n\nRegards,\n\n Love World Synergy"""%(doc.zone_name,doc.region) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='on_creation_of_a_new_cell_pcf_church'""",as_list=1) if notify: if "Email" in notify[0][0]: if doc.contact_email_id: frappe.sendmail(recipients=doc.contact_email_id, content=notify_msg, subject='Zone Creation Notification') if "SMS" in notify[0][0]: if doc.contact_phone_no: send_sms(doc.contact_phone_no, notify_msg) if "Push Notification" in notify[0][0]: data={} data['Message']=notify_msg gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res1=frappe.db.sql("select device_id from tabUser where name ='%s'" %(doc.contact_email_id),as_list=1) if res1: res1 = gcm.json_request(registration_ids=res1, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) ofc = frappe.new_doc("Offices") ofc.office_id = doc.name ofc.office_name = doc.zone_name ofc.office_code = doc.zone_code ofc.insert()
def send_gcm(request,msg): def is_student(phone): try: s = Student.objects.get(phone=phone) except Student.DoesNotExist: return None return s phone = request.session['phone'] s = is_student(phone) if request.method == "GET": from gcm import GCM gcm = GCM("AIzaSyDxhSbm0PVsM9Y2eMk9Bpq3773Esazj9f0") data = {'message': msg} reg_ids = [] if s != None: reg_ids.append(s.cls.teacher.gcm_id) else: # If Teacher, than broad case t = Teacher.objects.get(phone=phone) for s in t.cls.members: reg_ids.append(s) response = gcm.json_request(registration_ids=reg_ids, data=data) if 'errors' in response: print response return HttpResponse(HTTP_500_INTERNAL_SERVER_ERROR) else: return HttpResponse(HTTP_200_OK) else: return HttpResponse(status=HTTP_400_BAD_REQUEST)
def send_GCM_notification(token, data): logger.debug("Sending GCM Notification to [%s]..." % token) try: gcm = GCM(settings.GCM_API_KEY) # Plaintext request #response = gcm.plaintext_request( registration_id=token, collapse_key='Updated Steps', data=data, time_to_live=86400 ) <-- currently broken in library response = gcm.plaintext_request(registration_id=token, data=data) logger.debug("Sent Push to: [%s] sent: %s" % (token, response)) return "Success" except GCMNotRegisteredException: logger.error("Token [%s] Not Registered!" % token) return "NotRegistered" except GCMMismatchSenderIdException: logger.error("Token [%s] Bad Sender error" % token) return "Mismatch" except GCMUnavailableException: logger.error("Failed for [%s]... try again" % token) return "Unavailable" except: LogTraceback() return "Error"
def send_gcm_push(request): r = request if 'api_token' not in r.POST: return render(request, 'gcm_sender/index.html', {'error_message': 'api token missing'}) if 'device_token' not in r.POST: return render(request, 'gcm_sender/index.html', {'error_message': 'device token missing'}) if 'push' not in r.POST: return render(request, 'gcm_sender/index.html', {'error_message': 'notification type missing'}) try: client = GCM(r.POST['api_token']) notification = create_notification(r.POST['push']) if notification is None: return render(request, 'gcm_sender/index.html', {'error_message': 'unable to sent the notification'}) response = client.json_request(registration_ids=[r.POST['device_token']], data=notification.as_dict()) if 'success' not in response: return render(request, 'gcm_sender/index.html', {'error_message': 'unable to sent the notification'}) return render(request, 'gcm_sender/index.html', {'success': True}) except Exception as err: return render(request, 'gcm_sender/index.html', {'error_message': 'unable to sent the notification'})
class GCMNotifications(Notifications): def __init__(self): self.gcm = GCM(config.google_api_key) # return super(GCMNotifications, self).__init__() def notify(self, reg_id, data): self.gcm.plaintext_request(registration_id=reg_id, data=data)
def send_push(type, description): gcm = GCM('AIzaSyCxXaknhqHcNAxxSKGseYQrpgHB5COLF00') data = {'type': type, 'message': description} try: gcm.plaintext_request(registration_id='APA91bGxJ3Y2n4pExPc8kX1PAyuARTuA9p8a3LxwTj9d6LbAQ3aE4TYeaJ13nxqDohOtBW0ief8VdQl_H4Zz31gm5Csa61eT68RyeudpJH7lwJrzy-5yl3VmvZzYU3uIOnYMTfSGMozmhkV6DfEGblz6xUGmLrYBxQ', data=data, retries=10 ) except: print 'fail'
def push_message(username, token, pk): print(token, pk) gcm = GCM(GCM_APIKEY) gcm.plaintext_request(registration_id=token, data={}, collapse_key='new', time_to_live=TIME_TO_LIVE)
def check_new_issue(): req = requests.get(url='http://www.themagpi.com/mps_api/mps-api-v1.php?mode=list_issues') json_issues = json.loads(req.text) last_issue = json_issues['data'][0] gcm = GCM(app_keys['gcm']) data = {} data['id'] = last_issue['title'] data['editorial'] = last_issue['editorial'].encode('utf8') data['title'] = last_issue['title'] data['link'] = last_issue['pdf'] data['image'] = last_issue['cover'] data['date'] = last_issue['date'] devices, next_curs, more = Device.query().fetch_page(10) while next_curs: for device in devices: try: gcm.plaintext_request(registration_id=device.id_gcm, data=data) except GCMNotRegisteredException: pass except GCMInvalidRegistrationException: pass except GCMUnavailableException: pass devices, next_curs, more = Device.query().fetch_page(10, start_cursor=next_curs) return jsonify( { 'status' : 'success' } ) , 200
def meetings_attendance(data): """ Need to add provision to send sms,push notification and emails on present and absent """ dts=json.loads(data) #print dts qry="select user from __Auth where user='******'username'])+"' and password=password('"+cstr(dts['userpass'])+"') " valid=frappe.db.sql(qry) if not valid: return { "status":"401", "message":"User name or Password is incorrect" } else: for record in dts['records']: if record['present']=='0' or record['present']=='1' : frappe.db.sql("update `tabInvitation Member Details` set present=%s where name=%s",(record['present'],record['name'])) res=frappe.db.sql("select device_id from tabUser where name=(select email_id from `tabInvitation Member Details` where name=%s) ",record['name'],as_list=True,debug=1) #print res if res and dts['push']=='1': from gcm import GCM gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') data = {'param1': 'new attendance updated sussessfully ....'} reg_ids=['APA91bGKibKhhg2RssK2eng8jXW7Gzhmq5_nDcxr8OiAxPSB62xlMdJdSPKCGO9mPF7uoLpT_8b-V0MdY33lc7fTNdh6U965YTQD3sIic_-sY3C45fF5dUEwVuVo8e2lmDduN4EUsHBH','APA91bHXuIe7c8JflytJnTdCOXlWzfJCM2yt5hGgwaqzIbNfGjANhqzLgrVCoSno70hKtygzg_W7WbE4lHeZD_LeQ6CSc_5AteGY1Gh6R7NXihVnE45K91DOPxgtnF5ncN4gSJYiX0_N'] #print reg_ids #print res[0] res = gcm.json_request(registration_ids=res[0], data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) return "Updated Attendance"
def validate_duplicate(doc,method): if doc.get("__islocal"): res=frappe.db.sql("select name from `tabCells` where cell_name='%s' and cell_code='%s' and senior_cell='%s'"%(doc.cell_name,doc.cell_code,doc.senior_cell)) if res: frappe.throw(_("Another Cell '{0}' With Cell Name '{1}' and Cell Code '{2}' exist in Senior Cell '{3}'..!").format(res[0][0],doc.cell_name,doc.cell_code,doc.senior_cell)) notify_msg = """Dear User,\n Region is created with name '%s' for Senior Cell '%s' \n \n Regards,\n Love World Synergy"""%(doc.cell_name,doc.senior_cell) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='on_creation_of_a_new_cell_pcf_church'""",as_list=1) if "Email" in notify[0][0]: if doc.contact_email_id: frappe.sendmail(recipients=doc.contact_email_id, content=notify_msg, subject='Region Creation Notification') if "SMS" in notify[0][0]: if doc.contact_phone_no: send_sms(doc.contact_phone_no, notify_msg) if "Push Notification" in notify[0][0]: data={} data['Message']=notify_msg gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res1=frappe.db.sql("select device_id from tabUser where name ='%s'" %(doc.contact_email_id),as_list=1) frappe.errprint(res1) if res1: res1 = gcm.json_request(registration_ids=res1, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600)
def handle(self, *args, **options): gcm = GCM(settings.GCM_API_KEY) registration_ids = [settings.TEST_REG_ID, ] notification = { "title": "Тестовый заголовок", "message": "Tестовый текст!", #"uri": "market://details?id=gcm.play.android.samples.com.gcmquickstart" } response = gcm.json_request(registration_ids=registration_ids, data=notification, priority='high', delay_while_idle=False) # Successfully handled registration_ids if response and 'success' in response: for reg_id, success_id in response['success'].items(): print('Successfully sent notification for reg_id {0}'.format(reg_id)) # Handling errors if 'errors' in response: for error, reg_ids in response['errors'].items(): # Check for errors and act accordingly if error in ['NotRegistered', 'InvalidRegistration']: # Remove reg_ids from database for reg_id in reg_ids: print("Removing reg_id: {0} from db".format(reg_id))
def trigger_gcm_request( API_KEY=None , REG_ID=None , data=None ) : global GLOBAL_GCM_API_KEY # importing the global variable into this method # mainly for test global GLOBAL_REG_ID , GLOBAL_DATA # if no API key is passed, then we shall use the global one. if not API_KEY : API_KEY = GLOBAL_GCM_API_KEY if not data : data = GLOBAL_DATA if not REG_ID : REG_ID = GLOBAL_REG_ID # doing the actual work of creating the request gcm = GCM( API_KEY ) print "API KEY : %s , DATA : %s , REG_ID %s "%( API_KEY , data , REG_ID ) response = gcm.json_request( REG_ID , data=data) return response
def sendNotification(gcm_id, data, type): gcm_obj = GCM(API_KEY) try: response = gcm_obj.plaintext_request(registration_id=gcm_id, data=data) return response except gcm.gcm.GCMInvalidRegistrationException: return {'error':'gcm.gcm.GCMInvalidRegistrationException'} except gcm.gcm.GCMNotRegisteredException: return {'error':'gcm.gcm.GCMNotRegisteredException'} except: return {'error':'oooops'}
def push_gcm_message(ids, title, message, notification_type=True): sender = GCM(SERVER_API_KEY) #reg_id = list() #reg_id.append(request.form['reg_id']) data = {'title': title, 'message': message, 'notification_type': notification_type} result = sender.json_request(registration_ids=ids, data=data) return result
def send(msg, summ, is_bullied, bully): gcm = GCM("AIzaSyDjXNoiS_0OzWwiajVsi1GIAJFvkN47qPk") data = {'message': msg, 'summ': summ, 'is_bullied' : is_bullied, 'bully' : bully} topic = 'global' gcm.send_topic_message(topic=topic, data=data) return
def notify_one_user(token, msg): gcm = GCM(GCM_KEY) data = {'update': msg} gcm_push_response = gcm.json_request(registration_ids=[token], data=data) if bool(gcm_push_response): print token[:20] + " is invalid or outdated" else: print "Sent " + msg + " to " + token[:20]
def __init__(self, _app): self.application = _app _config = BOOTSTRAP_DATA.get("gcm") _api_key = _config.get("api_key") self.gcm = None if _api_key != None: self.gcm = GCM(_api_key) return
def send_gcm_message(users, data): """ Sends a push notification consisting of the JSON object data to each user in users. """ API_KEY = "AIzaSyBdPfe8aggpF5PyiClufQt62gjjLbbVyeY" gcm = GCM(API_KEY) reg_ids = [user.gcm_registration_id for user in users] response = gcm.json_request(registration_ids=reg_ids, data=data)
def gcm_python_gcm(): from gcm import GCM api_key = "AIzaSyATYMS-F-gZRNvp7Md108k_vRfm-TZvueY" gcm = GCM(api_key, debug=True) data = {'param1': 'value1', 'param2': 'value2'} topic = "SomeTopic" response = gcm.send_topic_message(topic=topic, data=data) return response
def push_payload(payload): """ Pushes a payload through the proper broker to the current device instance. Payload should be structured like: { "metadata": { "received_at": <unix ts>, "pushed_at": <unix ts>, "from_id": "<device uuid>" }, "payload": "<aes256 salted, encrypted JSON payload>", "signature": "<salted HMAC-SHA1 payload>" } Supported brokers: - Google Cloud Messaging (through `python-gcm`) :param dict payload: Dictionary of push payload. :rtype: None :returns: None """ if not self.target_id: raise ValueError("No target id has been set") config = manager.get_instance().config gcm_conf = config.get_section('gcm') g = None try: g = GCM(gcm_conf.get_string('api_key', None)) except (Exception e): raise e resp = g.json_request( registration_ids=self.target_id, data=payload, delay_while_idle=True, time_to_live=3600 ) if resp and 'success' in resp: for devid, succid in resp['success'].items(): LOG.info('Pushed payload to device %s' % (devid)) if 'errors' in resp: for err, devids in resp['errors'].items(): if err in ['NotRegistered', 'InvalidRegistration']: for devid in devids: print('Invalid device id: %s' % (devid)) if 'canonical' in resp: for devid, canonical_id in resp['canonical'].items(): d = Device.get(target_id=devid) d.target_id = canonical_id d.save()
def notify_user(destination_user, message): gcm = GCM(GCM_API_KEY) reg_id = [destination_user.gcm_id] data = {'message': message} print('Notification sent to test account, destination=' + destination_user.email + ', message=' + message) if destination_user.gcm_id != 'TESTACCOUNT': response = gcm.json_request(registration_ids=reg_id, data=data)
def _Start(): assert options.options.id and options.options.data_key and options.options.data_value api_key = secrets.GetSecret(API_KEY_NAME) print 'API key: %s' % api_key g = GCM(api_key) data = {options.options.data_key: options.options.data_value} # Do not catch any of the exceptions for now, we'd like to see them. g.plaintext_request(registration_id=options.options.id, data=data)
def push(): global API_KEY gcm = GCM(API_KEY) data = {'param1': 'value1', 'param2': 'value2'} # Downstream message using JSON request global registrationIds reg_ids = registrationIds response = gcm.json_request(registration_ids=reg_ids, data=data) return "pushed :-)"
def push_send(push_id, push_type): # push_type = 0,1 # 0 : 즉시발송 # 1 : 푸쉬삭제 API_KEY = 'AIzaSyByl17d2XCjWqZy4Wa7RaWmlsbkB1bGfHs' reg_ids = [] # 푸시 보낼 사용자 선택. members = Member.objects.filter(push_acceptable=True) response = 'member is 0' if len(members) > 0: for member in members: reg_ids.append(member.push_id) # 푸시에 사용될 메시지 가져오기. push = Push.objects.filter(id=push_id) if len(push) > 0: push = Push.objects.get(id=push_id) # 푸시 메시지 생성. gcm = GCM(API_KEY) date = str(push.activated_date_time).replace(" ", "-").replace(":", "-") date = date[:date.find('.')] data = { 'subject': 'Funing', 'contents': push.contents, 'date': date, 'id': push_id, 'type': int(push_type) } # 푸시 보내기. response = gcm.json_request(registration_ids=reg_ids, data=data) # 푸시 에러 핸들링. if 'errors' in response: for error, reg_ids in response['errors'].items(): # Check for errors and act accordingly if error is 'NotRegistered': # Remove reg_ids from database for reg_id in reg_ids: # print reg_id Member.objects.get(push_id=reg_id).delete() if 'canonical' in response: for canonical_id, reg_id in response['canonical'].items(): # print 'canonical_id : %s' % canonical_id # print 'reg_id : %s' % reg_id # Repace reg_id with canonical_id in your database member = Member.objects.get(push_id=canonical_id) member.push_id = reg_id member.save() return response
def send_push_mesage(msg, the_time): logging.getLogger('BoilerLogger').debug('sending boiler sms message: %s' % msg) gcm = GCM(PUSH_NOTIFICATION_API_KEY) data = {'message': msg, 'time': str(the_time)} topic = 'global' try: gcm.send_topic_message(topic=topic, data=data) except: logging.getLogger('BoilerLogger').debug( 'can not send push message, ignore.')
def remove_key_data(gcm_iid): # Send request to phone to delete revoked private key gcm = GCM(cfg.config.gcm_api_key) data = {"action": "revoke"} # Check if there were errors and retry if needed response = gcm.json_request(registration_ids=[gcm_iid], data=data) if 'errors' in response: remove_key_data.retry( args=[gcm_iid], countdown=cfg.config.celery.remove_key_data.timeout )
def send_push_gcm(token, content): google_api_key = "AAAAgGY9xAc:APA91bFwKXq9w7sB6EKzNGvIKInrc8VF8TRu3SInUM1zbisRmSX9gnlMcWFam4uIMoeAv0CGhNlwrEHvEI7htSbg6-2YHQ2hIgD0agKF95GZ_tEduz4pTDSJiQj2tpZ10hGPPLapIEvm" gcm = GCM(google_api_key) data = {'message': content, 'title': 'Chibe'} try: gcm.plaintext_request(registration_id=token, data=data) except: PushNotification.objects.filter(token=token).delete() pass
def sendNotification(gcm_id, data, type): gcm_obj = GCM(API_KEY) try: response = gcm_obj.plaintext_request(registration_id=gcm_id, data=data) return response except gcm.gcm.GCMInvalidRegistrationException: return {'error': 'gcm.gcm.GCMInvalidRegistrationException'} except gcm.gcm.GCMNotRegisteredException: return {'error': 'gcm.gcm.GCMNotRegisteredException'} except: return {'error': 'oooops'}
def notifyAll(): for profile in Profile.objects.all(): if Device.objects.filter(datastore_owner=profile).count() > 0: gcm = GCM(settings.GCM_API_KEY) for device in Device.objects.filter(datastore_owner=profile): try: gcm.plaintext_request(registration_id=device.gcm_reg_id, data={"action": "notify"}) except Exception as e: print "Issue with sending notification to: %s, %s" % ( profile.id, profile.uuid) print e
def send(self): gcm = GCM(self.app.android_key) payload = dict(message=str(self.content.get('alert')), custom=self.content.get('extra')) log.msg(payload) try: gcm.plaintext_request(registration_id=self.token, data=payload) log.msg('Notification sent to %s...' % self.token[:10]) except: log.msg('Unable to sent to %s...' % self.token[:10]) pass
def addNotificationAndNotify(profile, notificationType, title, content, uri): addNotification(profile, notificationType, title, content, uri) if Device.objects.filter(datastore_owner=profile).count() > 0: gcm = GCM(settings.GCM_API_KEY) for device in Device.objects.filter(datastore_owner=profile): try: gcm.plaintext_request(registration_id=device.gcm_reg_id, data={"action": "notify"}) except Exception as e: print "Issue with sending notification to: %s, %s" % ( profile.id, profile.uuid) print e