本文整理汇总了Python中gcm.GCM类的典型用法代码示例。如果您正苦于以下问题:Python GCM类的具体用法?Python GCM怎么用?Python GCM使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GCM类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle
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))
示例2: makeDecision
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)
示例3: notify_users
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)
示例4: trigger_gcm_request
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
示例5: send_to_gcm
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)
示例6: validate_duplicate
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)
示例7: handle
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='')
示例8: validate_duplicate
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()
示例9: processGCMRequest
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})
示例10: send_message_device_invit
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)
示例11: send_notification
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
示例12: send_message_device
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)
示例13: assignmember
def assignmember(memberid,ftv):
frappe.db.sql("""update `tabFirst Timer` set ftv_owner='%s' where name='%s' """ % (memberid,ftv))
# recipients='[email protected]'
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='[email protected]', content=msg_member, subject='Assign for follow up')
# frappe.sendmail(recipients=ftvdetails[0][1], sender='[email protected]', content=msg_ftv, subject='Assign for follow up')
return "Done"
示例14: sendMessageGcmtest
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
示例15: send_gcm_push
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'})