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 recordJudgement(due, success, conn): gcm = GCM(options.gcm_key) print("Judge: " + str(success)) if success: prediction = lib.db.getTwitterPredictionByPredictionID(due["predictionID"], conn) wagers = lib.db.getTwitterPredictionWagersLocal(due["predictionID"], conn) message = { "message": "Your prediction have been judged", "link": r"https://" + options.hostname + r"/" + r"prediction/twitter/" + prediction["url"], } regids = [x["regid"] for x in wagers if x["regid"]] gcm.json_request(registration_ids=regids, data=message, priority="high") lib.db.passJudgement(due["predictionID"], success == "Yes", conn)
def sendNotice(self, reg_ids, message, url): gcm = GCM(self.api_key) data = { 'url': url, 'message': message } response = gcm.json_request(registration_ids=reg_ids, data=data) # Extra arguments res = gcm.json_request( registration_ids=reg_ids, data=data ) return res
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 android_push(uuids, message): if not uuids: raise Exception("Registration_id is required.") # GCM Configuration from gcm import GCM api_key = "AIzaSyAheYj04o3dgHhG8MrN5NGQKY4HT8NhzKc" gcm = GCM(api_key) if type(uuids) is list: gcm.json_request(registration_ids=uuids, data=message) else: gcm.plaintext_request(registration_id=uuids, data=message) return ""
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 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'})
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 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 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_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 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 push(self, message="test", reg_id=None): API_KEY = 'AIzaSyAEN09LeNCfS92A3_qgXrxIekiKDJC2ets' print(message) gcm = GCM(API_KEY) data = {'message': message} # Downstream message using JSON request reg_id = reg_id or 'cZwjGCf2elE:APA91bFXSN0b6vPH79JermZbCPUZGZvw_0odphwJK9VGdh2TPLsElehR0SHpxMYaKD06kknZ8uS5_oqkW0rP0yC8bdT8zrPDJSMWPxCIOj1Ksos9Q0qKkdb0rjczQRI9K_7UjMrPvGps' response = gcm.json_request(registration_ids=[reg_id], data=data) # Downstream message using JSON request with extra arguments res = gcm.json_request(registration_ids=[reg_id], data=data, collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600)
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 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 android_push(uuids, message): print str(uuids) if not uuids: return False from gcm import GCM g = GCM("AIzaSyAheYj04o3dgHhG8MrN5NGQKY4HT8NhzKc") try: if isinstance(uuids, list): g.json_request(registration_ids=uuids, data=message) elif isinstance(uuids, str): g.plaintext_request(registration_id=uuids, data=message) except Exception, e: print str(e) return False
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 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 send(self): from gcm import GCM gcm = GCM(settings.NOTIFICATIONS_GCM_KEY) try: response = gcm.json_request(registration_ids=self._to, data=self._data) except Exception as e: raise return response
class GCMPush(multiprocessing.Process): """ Class to syncronously http post to gcm server. Pass json data, a json string containing the data field, and the registration id of the phone you wish to post to. """ def __init__(self, json_data, reg_id): super(GCMPush, self).__init__() self.API_KEY = "AIzaSyBjUNo32k8XOOZVtlHuOEg4L3VwmTe-ziM" self.json_data = json_data self.gcm = GCM(self.API_KEY) if isinstance(reg_id, list): self.reg_id = reg_id else: self.reg_id = [ reg_id ] def run(self): self.gcm.json_request(registration_ids=self.reg_id, data=self.json_data)
def _send_message(self, reg_id_list, json_to_send): gcm = GCM(self.API_KEY) data = json_to_send #print "Sending this data:" #print "%s" % str(data) # Downstream message using JSON request #TODO fix "COULD NOT BE PARSED AS JSON" error... response = gcm.json_request(registration_ids=reg_id_list, data=data)
def send_single_notification(order): customer = order.user.userprofile app_id=[customer.app_id] gcm=GCM(constant.API_KEY) data = {'title':'MovinCart','Notification': "Has your order been delivered",'popup':"1",'page':"2",'NeedRefresh':"1",'order_id':str(order.id)} response = gcm.json_request(registration_ids=app_id, data=data) notification_sent=simplejson.dumps(data) OrderActivity(order=order,user=order.user,actions=12,comment=notification_sent).save() return response
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)
class Notifications(): def __init__(self, gcm_id=''): self.gcm_id = gcm_id.split(",") if gcm_id else 0 self.gcm = GCM(webapp.config['GCM_API_KEY']) self.is_enabled = webapp.config['NOTIFICATIONS_ENABLED'] def sendNotification(self, data): data['bottom_text'] = "Ostrich Books" if 'notification_id' in data: data['collapse_key'] = data['notification_id'] if self.is_enabled and self.gcm_id: notification_status = self.gcm.json_request( registration_ids=self.gcm_id, data=data) return notification_status @async def startDataUpdate(self): data = {'notification_id': 99, 'collapse_key': 99} if self.gcm_id: self.gcm.json_request(registration_ids=self.gcm_id, data=data) return self.sendMassNotification(data) @async def sendMassNotification(self, notification_data, admin=0): if 'notification_id' in notification_data: notification_data['collapse_key'] = notification_data[ 'notification_id'] if admin: admins = ",".join([str(_) for _ in Utils.getAdmins()]) query_condition = " WHERE user_id in (" + admins + ")" else: query_condition = " UNION SELECT gcm_id FROM users_unregistered" cursor = mysql.connect().cursor() cursor.execute("""SELECT gcm_id FROM users""" + query_condition) all_gcm = cursor.fetchall() all_gcm_ids = [] for gcm in all_gcm: all_gcm_ids.append(gcm[0]) self.gcm.json_request(registration_ids=all_gcm_ids, data=notification_data)
def command_insert(self, a_command): """ Sends a GCM message to the robot. """ # Use the command to send a GCM. gcm = GCM(API_KEY) response = gcm.json_request(registration_ids=REGISTRATION_IDS, data={'data': a_command}) a_command.gcm_response = response a_command.put() return a_command
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 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 main(): if len(sys.argv) is not 3: sys.exit(1) cloud = GCM('your-API-key-belongs-here') environ = Environ() title = sys.argv[1] text = sys.argv[2] words = text.split(" ") text = "" for word in words: text += environ.replace(word) + " " notification = {"title": title, "message": text} ids = get_registration_ids() cloud.json_request(registration_ids=ids, data=notification) sys.exit(0)
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 testGCM(request): API_KEY = 'AIzaSyBIoZYJ1mOKB8x32svoYCqCSeS4yEhxbQM' gcm = GCM(API_KEY) data = {'title': '타이틀', 'content': '내용', 'ticker': '티'} # Plaintext request reg_id = 'APA91bFFWd2KDbzx7I6amwY2GZBYF554kXqnd8VtApeqH7Iber0RuHY69VtEosUXvFENy6Oyr0T_SHT6mhbw4trrid_Jiti0wTDDP6jLKsWSejqjE0ytbrUTUu20rCK7nk9NoPLoA9yI' gcm.plaintext_request(registration_id=reg_id, data=data) # JSON request reg_ids = [ 'APA91bFFWd2KDbzx7I6amwY2GZBYF554kXqnd8VtApeqH7Iber0RuHY69VtEosUXvFENy6Oyr0T_SHT6mhbw4trrid_Jiti0wTDDP6jLKsWSejqjE0ytbrUTUu20rCK7nk9NoPLoA9yI' ] response = gcm.json_request(registration_ids=reg_ids, data=data) return HttpResponse(response.success) # Extra arguments res = gcm.json_request(registration_ids=reg_id, data=data, collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) return HttpResponse(res)
def msg_text(request): json_data = json.loads(request.body) msg = json_data.get("msg") group_id = json_data.get("group_id") group = Question.objects.get(id=group_id) if request.method == "POST": peers_involved = group.peers_involved.all() if peers_involved: gcm_ids = [peer.gcm_id for peer in peers_involved] gcm = GCM(settings.GCM_API_KEY) data = {"action": "chat", "msg": msg} gcm_status = gcm.json_request(registration_ids=gcm_ids, data=data) return Response({}, status=status.HTTP_200_OK)
def gcm_notification(registration_ids, title, message): API_KEY = "" # key for API server gcm = GCM(API_KEY) # registration_ids = [] # tokens from app installed on devices notification = { "title": title, # "Bazzzar notification" "message": message, # "message": "Amazing message!!! =)" "uri": "market://details?id=gcm.play.android.samples.com.gcmquickstart", "icon": "my icon", # can add "icon" } response = gcm.json_request( registration_ids=registration_ids, data=notification, # collapse_key='awesomeapp_update', # set param to update last unread notification # tag='ssfaefaf', # test # id='idssss', # test restricted_package_name="gcm.play.android.samples.com.gcmquickstart", priority='high', # maybe 'normal' delay_while_idle=False) # time_to_live from 0 to 2,419,200 seconds (4 weeks) # GCM allows a maximum of 4 different collapse keys to be used by the app server per device at any given time # Messages not be delivered until the device becomes active by using the delay_while_idle flag. # Note that there is limit of 100 multiple senders. # Successfully handled registration_ids log_list = list() if response and 'success' in response: for reg_id, success_id in response['success'].items(): log_list.append( 'Successfully sent notification for reg_id {0}'.format(reg_id)) # When an app server posts a message to GCM and receives a message ID back, # it does not mean that the message was already delivered to the device. # 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: log_list.append( "Removing reg_id: {0} from db".format(reg_id)) return log_list
def send_gcm(request): ''' save user gcm registration id :param request: :return: ''' if request.method == "GET": return Response({"detail": "get is not supported"}) elif request.method == "POST": secret = Secret.objects.all().order_by('-id')[0] API_KEY = secret.api_key gcm = GCM(API_KEY) ##data = {'param1': 'value1', 'param2': 'value2'} data = request.data # Downstream message using JSON request ##reg_ids = ['token1', 'token2', 'token3'] tokens = GcmRegister.objects.all() reg_ids = [] for token in tokens: reg_ids.append(token.gcmToken) response = gcm.json_request(registration_ids=reg_ids, data=data) # Downstream message using JSON request with extra arguments res = gcm.json_request(registration_ids=reg_ids, data=data, collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) # Topic Messaging topic = 'global' gcm.send_topic_message(topic=topic, data=data) return Response({'detail': res})
def chat(): if request.method == 'POST': data = request.json b = data['batch'] gcm = GCM(gcmKey) users = db.users.find({"batch": b}) print users reg_ids = [] for i in users: reg_ids.append(i['registration_id']) print len(reg_ids) response = gcm.json_request(registration_ids=reg_ids, data=data['data'], collapse_key=data['type']) print response
def location_request(): gcm = GCM(GCM_API_KEY) data = {"request": "positioning", "time": int(time())} if int(kv.get(app.secret_key + "_last_push") or 0) < time() - 60: res = gcm.json_request( registration_ids=[kv.get(app.secret_key + "_regid")], collapse_key="positioning", data=data, time_to_live=60, delay_while_idle=False, ) kv.set(app.secret_key + "_last_push", int(time())) return res else: return {'mark': 'too_frequent'}
def gcm_li(reg_id, reg_data): gcm = GCM(SERVER_API_KEY) reg_list = [] print "&@#&@&#@#&@#&@&#@#&@&#&#@" #print reg_id reg_list.append(reg_id) response_data = reg_data print response_data #response_data['message'] = "you got it" #test_reg_data = {'message': u'APA91bHZ8hH9xv20R-eqwuK9liLVN5cYAPFr9MDFvvCwOBpVv-ygV_NE7T9Dq73pqZiIQBlnyeaENM7Ym3m8Fql-S1VkylqQHzYxUsXEDapxCoDaoOo1mf4s_gBHvyMfrcoYTi0W9RY3', 'queue_num': '1', 'key': '1441338705248', 'doctor': 'adasdasd'} response = gcm.json_request(registration_ids=reg_list, data=response_data)
def add_comment(doc): """allow any logged user to post a comment""" record = json.loads(doc) if record['comment_doctype'] == 'Attendance Record': mail_notify_msg = """Dear User, \n '{0}' had commented '{1}' on the Attendance Record '{2}'. \n Please Check. \n \n Records, \n Love World Synergy""".format(record['comment_by'], record['comment'], record['comment_docname']) notify = frappe.db.sql( """select value from `tabSingles` where doctype='Notification Settings' and field = 'when_a_leader_makes_a_comment'""", as_list=1) hirerchy = frappe.db.sql( "select a.name,a.device_id from `tabDefaultValue` b, `tabUser` a where a.name=b.parent and b.defkey='Senior Cells' and b.defvalue=(select senior_cell from `tabAttendance Record` where name='%s')" % record['comment_docname'], as_list=1) user = frappe.db.sql( """select phone_1 from `tabMember` where email_id='%s'""" % (hirerchy[0][0]), as_list=1) if "Email" in notify[0][0]: frappe.sendmail(recipients=hirerchy[0][0], content=mail_notify_msg, subject='Attendance Record comment Notification') frappe.sendmail(recipients='*****@*****.**', content=mail_notify_msg, subject='Attendance Record comment Notification') if "SMS" in notify[0][0]: from erpnext.setup.doctype.sms_settings.sms_settings import send_sms if user: send_sms(user[0][0], mail_notify_msg) if "Push Notification" in notify[0][0]: data = {} data['Message'] = mail_notify_msg from gcm import GCM gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res = gcm.json_request(registration_ids=[x[1] for x in hirerchy], data=data, collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) doc = frappe.get_doc(record) doc.insert(ignore_permissions=True) return doc.as_dict()
class AndroidPushProvider(BaseProvider): def __init__(self): self.gcm = GCM(settings.GCM_KEY) def pushMessage(self, message, destToken, channel_name): send_count = len(destToken) if send_count > 0: # TODO: Gestire paginazione dei tokens a gruppi di 6/700 (il limite dovrebbe essere 1000 per call) # TODO: gestione del ttl # Nota: converto in un dict perché altrimenti il serializzatore non riesce a lavorare sul PushMessage dic_obj = { 'alert_msg': message.alert_msg, 'data_dic': message.data_dic, 'push_type': message.push_type } response = self.gcm.json_request(registration_ids=destToken, data=dic_obj, delay_while_idle=False) self.log_info(str(response)) # Handling errors if 'errors' in response: for error, reg_ids in response['errors'].items(): self.log_error("push error {0}".format(error)) # Check for errors and act accordingly if error is 'NotRegistered': pass # Remove reg_ids from database # for reg_id in reg_ids: # entity.filter(registration_id=reg_id).delete() if 'canonical' in response: for reg_id, canonical_id in response['canonical'].items(): self.log_error("canonical {0}".format(reg_id)) # # Repace reg_id with canonical_id in your database # entry = entity.filter(registration_id=reg_id) # entry.registration_id = canonical_id # entry.save() # Nota: al momento non viene gestito correttamente il conteggio dei push inviati, si da per scontato che tutti # lo siano else: self.log_info("Nothing to send for AndroidPushProvider") return send_count
def execute_push_msg(api_key, feed_id, push_msg, reg_id): registration_ids = [] registration_ids.append(reg_id) gcm = GCM(api_key) msg = {"price": str(feed_id) + ";" + push_msg} response = gcm.json_request(registration_ids=registration_ids, data=msg, collapse_key='awesomeapp_update', priority='high', delay_while_idle=False) if DEBUG: out_log.write("msg details: %s,%s\n" % (feed_id, push_msg))
def validate_duplicate(doc, method): if doc.get("__islocal"): res = frappe.db.sql( "select name from `tabChurches` where church_name='%s' and church_group='%s' and church_code='%s'" % (doc.church_name, doc.church_group, doc.church_code)) if res: frappe.throw( _("Another Church '{3}' With Church Name '{0}' and Church Code '{2}'' exist in Church Group '{1}'" ).format(doc.church_name, doc.church_group, doc.church_code, res[0][0])) notify_msg = """Dear User,\n\n Church is created with name '%s' for Group Church '%s'. \n\n Regards,\n\n Love World Synergy""" % ( doc.church_name, doc.church_group) 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.email_id: frappe.sendmail(recipients=doc.email_id, content=notify_msg, subject='Church Creation Notification') if "SMS" in notify[0][0]: if doc.phone_no: send_sms(doc.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.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_name ofc.office_code = doc.church_code ofc.insert()