def _push_msg(message, device_id): app_key = 'app_key' master_secret = 'master_key' _jpush = jpush.JPush(app_key, master_secret) push = _jpush.create_push() # push.audience = jpush.audience([{"registration_id":device_id}]) push.audience = {'registration_id': [device_id]} # push.audience = device_id android_msg = jpush.android( message, None, None, { "msg": message, # 强行套用app中notification的相关格式 "status": 0 } ) ios_msg = jpush.ios( message, None, None, { "msg": message, # 强行套用app中notification的相关格式 "status": 0 } ) push.notification = jpush.notification("hello jpush", ios_msg, android_msg, None) # push.options = {"time_to_live": 86400, "sendno": 12345, "apns_production":True} push.options = {"time_to_live": 86400, "apns_production": True} push.platform = jpush.platform("all") push.send()
def AsyncAddressAuditSubmit(apiKey, secretKey, alias, user_id, customContent, pushContent, pushTitle): from users.models import User uObectj = User.objects.get(user_id=long(user_id)) userCache = uObectj.user_handle_cache addrCache = uObectj.addr_handle_cache uObectj.addr_handle_cache = (int(addrCache) + 1) % 1000 uObectj.save() _jpush = jpush.JPush(apiKey, secretKey) pushExtra = {'pTitle': pushTitle} pushExtra.update(customContent) # pushExtra = customContent currentAlias = alias + str(user_id) push = _jpush.create_push() push.audience = jpush.all_ push.audience = jpush.audience(jpush.alias(currentAlias), ) push.notification = jpush.notification( ios=jpush.ios(alert=pushContent.encode('utf-8'), badge="+1", extras=pushExtra), android=jpush.android(pushContent, pushTitle, None, pushExtra)) push.options = { "time_to_live": 86400, "sendno": 9527, "apns_production": PUSH_STATUS } push.platform = jpush.all_ push.send()
def send(self, *args, **kwargs): try: content = NoticeTemplate.objects.get(category=self.category) except NoticeTemplate.DoesNotExist: print u"没有发现模板" return False print content.content template = Template(content.content) messages = template.render(dict(*args, **kwargs)) registration_id = kwargs.get('registration_id') opts = jpush.JPush(settings.JPUSH_APPKEY, settings.JPUSH_SECRET) push = opts.create_push() push.notification = jpush.notification(alert=messages) push.options = { "time_to_live": 86400, "apns_production": True, 'extras': kwargs.get('extras') } push.audience = jpush.audience(jpush.registration_id( registration_id)) if registration_id else jpush.all_ push.platform = jpush.all_ push.send()
def AsyncDelCommentPush(topicId, senderId, communityId, commentId, commentCount): config = readIni() tagSuffix = config.get('topic', "tagSuffix") pushContent = str(topicId).encode('utf-8') + ":" \ +str(senderId).encode('utf-8') + ":" \ +str(communityId).encode('utf-8') + ":" \ +str(commentId).encode('utf-8') + ":" \ +str(commentCount).encode('utf-8') tagSuffix = config.get('topic', "tagSuffix") tagNormalName = tagSuffix + str(communityId) tagSuffix = config.get('report', "tagSuffix") tagAdminName = tagSuffix + str(communityId) tagSuffix = config.get('property', "tagSuffix") tagPropertyName = tagSuffix + str(communityId) apiKey = config.get("SDK", "apiKey") secretKey = config.get("SDK", "secretKey") _jpush = jpush.JPush(apiKey, secretKey) push = _jpush.create_push() push.audience = jpush.all_ push.audience = jpush.audience( jpush.tag(tagNormalName, tagAdminName, tagPropertyName), ) push.message = jpush.message(pushContent, u"push_del_comm", None, None) push.options = { "time_to_live": 0, "sendno": 9527, "apns_production": PUSH_STATUS } push.platform = jpush.all_ push.send()
def pushAllIos(request): if request.method == 'POST': title = request.POST.get('title') content = request.POST.get('content') print(title, content) print(type(title), type(content)) ios_jpush = jpush.JPush(ios_app_key, ios_master_secret) push = ios_jpush.create_push() ios_jpush.set_logging("DEBUG") push.audience = jpush.all_ raw = {"body": content, "title": title} ios_msg = jpush.ios(alert=raw, badge="+1", sound="beep.wav") push.notification = jpush.notification(alert=content, ios=ios_msg) push.platform = jpush.all_ push.options = {"apns_production": False} try: response = push.send() print(response, type(response)) return render(request, 'success.html') except common.Unauthorized: return render(request, 'failed.html', {"err_msg": "验证失败!"}) # raise common.Unauthorized("Unauthorized") # AppKey,Master Secret 错误,验证失败必须改正。 except common.APIConnectionException: return render(request, 'failed.html', {"err_msg": "请求超时!"}) # raise common.APIConnectionException("conn error") # 包含错误的信息:比如超时,无网络等情况。 except common.JPushFailure: return render(request, 'failed.html', {"err_msg": "请求出错!"}) # print("JPushFailure") # 请求出错,参考业务返回码。 except: return render(request, 'failed.html', {"err_msg": "其他异常!"}) # print("Exception") return render(request, 'iospush.html')
def jpush_push(notify_info): # base on os to deal os_type = platform.system() if(os_type == "Windows"): pass elif(os_type == "Linux"): print "Start to deal jpush push API\n" _jpush = jpush.JPush(app_key, master_secret) _jpush.set_logging("DEBUG") push = _jpush.create_push() push.audience = jpush.all_ push.notification = jpush.notification(alert=notify_info) push.platform = jpush.all_ try: response = push.send() except common.Unauthorized as e: raise common.Unauthorized("Unauthorized") logging.error('Unauthorized exception received') except common.APIConnectionException as e: raise common.APIConnectionException("Connection") logging.error('Connection exception received') except common.JPushFailure as e: logging.error('JPush failure exception received') except: logging.error('Other unhandled exception received') return 0 # self test used #jpush_push(u'hello python jpush api')
def send_users_base_regid(reg_id, body, images='', extras=None): _jpush = jpush.JPush(setting.jpush_key, setting.jpush_secret) push = _jpush.create_push() alias1 = {"registration_id": [reg_id]} push.audience = jpush.audience(alias1) if extras: extras['images'] = images ios_msg = jpush.ios(alert=body, badge="+1", sound="a.caf", content_available=True, mutable_content=True, extras=extras) android_msg = jpush.android(alert=body, style=3, big_pic_path=images, extras=extras) else: ios_msg = jpush.ios(alert=body, badge="+1", sound="a.caf", content_available=True, mutable_content=True) android_msg = jpush.android(alert=body) push.notification = jpush.notification(alert=body, android=android_msg, ios=ios_msg) push.platform = jpush.all_ push.options = {"apns_production": True} result = push.send() # result = push.send_validate() print result.payload
def pushAllAndroid(request): if request.method == 'POST': title = request.POST.get('title') content = request.POST.get('content') print(title, content) print(type(title), type(content)) and_jpush = jpush.JPush(and_app_key, and_master_secret) push = and_jpush.create_push() and_jpush.set_logging("DEBUG") push.audience = jpush.all_ android_msg = jpush.android(alert=content, title=title) push.notification = jpush.notification(alert=content, android=android_msg) push.platform = jpush.all_ try: response = push.send() print(response, type(response)) return render(request, 'success.html') except common.Unauthorized: return render(request, 'failed.html', {"err_msg": "验证失败!"}) # raise common.Unauthorized("Unauthorized") # AppKey,Master Secret 错误,验证失败必须改正。 except common.APIConnectionException: return render(request, 'failed.html', {"err_msg": "请求超时!"}) # raise common.APIConnectionException("conn error") # 包含错误的信息:比如超时,无网络等情况。 except common.JPushFailure: return render(request, 'failed.html', {"err_msg": "请求出错!"}) # print("JPushFailure") # 请求出错,参考业务返回码。 except: return render(request, 'failed.html', {"err_msg": "其他异常!"}) # print("Exception") return render(request, 'androidpush.html')
def send_users_base_tags(tags, body, images='', extras={'link': ''}): _jpush = jpush.JPush(setting.jpush_key, setting.jpush_secret) push = _jpush.create_push() push.audience = jpush.audience() push.audience['tag'] = tags push.platform = jpush.all_ if extras: extras['images'] = images ios_msg = jpush.ios(alert=body, badge="+1", sound="a.caf", content_available=True, mutable_content=True, extras=extras) android_msg = jpush.android(alert=body, style=3, big_pic_path=images, extras=extras) else: ios_msg = jpush.ios(alert=body, badge="+1", sound="a.caf", content_available=True, mutable_content=True) android_msg = jpush.android(alert=body) push.notification = jpush.notification(alert=body, android=android_msg, ios=ios_msg) push.options = {"apns_production": True} result = push.send() print result.payload
def test_audience(self): _jpush = jpush.JPush(app_key, master_secret) push = _jpush.create_push() push.audience = jpush.audience( jpush.tag("tag1", "tag2"), jpush.alias("alias1", "alias2") ) push.notification = jpush.notification(alert="Hello world with audience!") push.platform = jpush.all_ try: response = push.send() self.assertEqual(response.status_code, 200) except common.Unauthorized as e: self.assertFalse(isinstance(e, common.Unauthorized)) raise common.Unauthorized("Unauthorized") except common.APIConnectionException as e: self.assertFalse(isinstance(e, common.APIConnectionException)) raise common.APIConnectionException("conn") except common.JPushFailure as e: self.assertFalse(isinstance(e, common.JPushFailure)) print ("JPushFailure") except: self.assertFalse(1) print ("Exception")
def AsyncSetProprtyRepair(apiKey, secretKey, currentCommunityId, custom_content, message, customTitle, tagSuffix): # import sys # default_encoding = 'utf-8' # if sys.getdefaultencoding() != default_encoding: # reload(sys) # sys.setdefaultencoding(default_encoding) tagName = tagSuffix + str(currentCommunityId) _jpush = jpush.JPush(apiKey, secretKey) pushExtra = {'pTitle': customTitle} pushExtra.update(custom_content) # pushExtra = custom_content push = _jpush.create_push() push.audience = jpush.all_ push.audience = jpush.audience(jpush.tag(tagName), ) push.notification = jpush.notification( ios=jpush.ios(alert=message.encode('utf-8'), badge="+1", extras=pushExtra), android=jpush.android(message, customTitle, None, pushExtra)) push.options = { "time_to_live": 86400, "sendno": 9527, "apns_production": PUSH_STATUS } push.platform = jpush.all_ push.send()
def pushsinglemsg(apptype, body, receiver): key = 'bb9fc37f914d94589c6d7c4d' secret = '0b058bd331eae435fa38f20e' if apptype == 2: key = '382c5d880cae31ec81df46ff' secret = 'ac37c4c44a0b83539d469464' elif apptype == 3: key = '28e20ce5dcfd49511309806a' secret = 'b05bdc47c2cb686850a6c766' elif apptype == 4: key = '3c7971b2e03ef0f0df5c70b2' secret = 'ff57774954b9ed1f0771cef4' _jpush = jpush.JPush(key, secret) push = _jpush.create_push() push.audience = jpush.audience(jpush.alias(receiver)) ios_msg = jpush.ios(alert=body, badge="+1", sound="a.caf", extras={'k1': 'v1'}) android_msg = jpush.android(alert=body) push.notification = jpush.notification(alert=body, android=android_msg, ios=ios_msg) push.platform = jpush.all_ push.options = {"apns_production": False} re = push.send() print re
def jpushios(obj): _jpush = jpush.JPush(app_key, master_secret) push = _jpush.create_push() push.audience = jpush.all_ name = Name(obj) project = Project(obj) content = obj.content version = Version(obj) urgency = Urgency(obj) module = Module(obj) distribter = Distribter(obj) msgdict = [ name, u'在', project, version, u'版本', module, u'中', u'发现一个', urgency, u'问题', u':', content ] msg = ''.join(msgdict) push.audience = jpush.audience(jpush.alias(distribter)) ios_msg = jpush.ios(alert=msg, badge="+1", sound="a.caf", extras={'k': 'v'}) push.options = { "time_to_live": 86400, "sendno": 12345, "apns_production": False } push.notification = jpush.notification(alert="", ios=ios_msg) push.platform = jpush.platform("ios") push.send()
def _reload_jp(self, instance): # type: (JPushSecret) -> None if instance is not None: self._jpush = jpush.JPush(instance.app_key, instance.master_secret) self._production = instance.production else: self._jpush = None self._production = False
def push(self, data, *targets): ''' jpush通知 :param targets: 列表, 推送目标 [] :param data: 字典, 推送数据 ''' try: try: _jpush = jpush.JPush(*setting.JPUSH['auth']) self._push(_jpush, targets, data) except: # 调用auth_new来发送(google版) _jpush = jpush.JPush(*setting.JPUSH['auth_google']) self._push(_jpush, targets, data) except: self._processor.tracker.trace_error()
def __init__(self, msg='金指投', extras={}): self.msg = msg self.ios_msg = jpush.ios(alert=msg, badge="+1", sound="a.caf", extras=extras) self.android_msg = jpush.android(alert=msg, extras=extras) self.push = jpush.JPush(settings.JAK, settings.JMS).create_push()
def init_notifier(self): from vnpy.trader.setting import get_settings push_settings = get_settings('notification.') if push_settings: krPush = jpush.JPush(push_settings['app_key'], push_settings['master_secret']) self.notifier = krPush.create_push() self.notifier.audience = jpush.all_ self.notifier.platform = jpush.all_
def __new__(cls, *args, **kwargs): app_key = args[0] master_secret = args[1] if not hasattr(SendPush, '_instance'): obj = super(SendPush, cls).__new__(cls, *args, **kwargs) obj.jpush = jpush.JPush(app_key, master_secret) obj.jpush.set_logging('DEBUG') cls._instance = obj return cls._instance
def __init__(self, sender, instance, created, **kwargs): self._instance = instance self._sender = sender self._created = created self._kwargs = kwargs self._jpush = jpush.JPush(app_key, app_secret) try : self.send_message(self.create_message()) except PushException as e: log.error('push message exeption for instance %s' %instance)
def send_friend_notification(regid, data): _jpush = jpush.JPush(settings.JPUSH_APP_KEY, settings.JPUSH_APP_MASTER) push = _jpush.create_push() push.audience = jpush.registration_id(regid) push.notification = jpush.notification(ios=jpush.ios(alert='sb has make friend with you!', extras={"d": data, "action": "friend"})) push.options = dict(apns_production=False) push.platform = jpush.platform('ios') return push.send()
def send_new_photo_notification(regids, data): _jpush = jpush.JPush(settings.JPUSH_APP_KEY, settings.JPUSH_APP_MASTER) push = _jpush.create_push() push.audience = jpush.registration_id(*regids) push.notification = jpush.notification(ios=jpush.ios(alert='', content_available=True, extras={"d": data, "action": "photo"})) push.options = dict(apns_production=False) push.platform = jpush.platform('ios') return push.send()
def set_device_info(regist_id, tags=[], alias=None): _jpush = jpush.JPush(setting.jpush_key, setting.jpush_secret) device = _jpush.create_device() reg_id = regist_id entity = jpush.device_tag({'add': tags}) if alias: entity['alias'] = alias print entity, regist_id result = device.set_deviceinfo(reg_id, entity) print result.payload
def sendinfo(username, parkingmame): _jpush = jpush.JPush(app_key, master_secret) _jpush.set_logging("DEBUG") push = _jpush.create_push() push.audience = jpush.audience(jpush.alias(str(username))) info = "Dear " + username + ",you car has parked at " + parkingmame + "!" push.notification = jpush.notification(alert=str(info)) push.platform = jpush.all_ print(push.payload) push.send()
def __init__(self, call_remote=True): self.call_remote = call_remote if not call_remote: dir = os.path.dirname(__file__) fid = open(os.path.join(dir, 'jpush.config'), 'r') data = fid.read() config = json.loads(data) self.app_key = config['app_key'] self.master_secret = config['master_secret'] logging.info("jpush app_key{%s}, master_key{%s...}" % (self.app_key, self.master_secret[:6])) self._jpush = jpush.JPush(self.app_key, self.master_secret)
def AsyncForcedReturn(): config = readIni() ListApkInfo = [] from core.settings import NEW_VERSION_URL from web.models import APK QuerySet = APK.objects.filter().order_by('-v_id')[:1] apkObj = QuerySet[0] valCode = apkObj.v_name valSize = str(apkObj.v_size) + 'MB' valURL = NEW_VERSION_URL valForce = apkObj.v_force function = apkObj.v_function bug = apkObj.v_bug dicts = {} dicts.setdefault('fun',function) dicts.setdefault('bug',bug) ListApkInfo.append(dicts) response_data = {} response_data['flag'] = 'ok' response_data['vcode'] = valCode response_data['size'] = valSize response_data['url'] = valURL response_data['srv_url'] = 'none' response_data['force'] = valForce response_data['detail'] = ListApkInfo pushContent = response_data apiKey = config.get("SDK", "apiKey") secretKey = config.get("SDK", "secretKey") tagSuffixWithTopic = config.get('topic', "tagSuffix") tagSuffixWithReport = config.get('report', "tagSuffix") tagSuffixWithProperty = config.get('property', "tagSuffix") _jpush = jpush.JPush(apiKey,secretKey) from addrinfo.models import Community commQuerySet = Community.objects.all() for i in range(0,commQuerySet.count(),1): commId = commQuerySet[i].getCommunityId() tagNormalName = tagSuffixWithTopic + str(commId) tagAdminName = tagSuffixWithReport+str(commId) tagPropertyName = tagSuffixWithProperty+str(commId) push = _jpush.create_push() push.audience = jpush.all_ push.audience = jpush.audience( jpush.tag(tagNormalName,tagAdminName,tagPropertyName), ) push.message = jpush.message( pushContent, u"push_force_return", None, None ) push.options = {"time_to_live":0, "sendno":9527, "apns_production":PUSH_STATUS} push.platform = jpush.all_ push.send()
def pushAll(): print 'pushAll' app_key = os.environ.get('JPUSH_APP_KEY', "09bc724caa75be2669ca7411") master_secret = os.environ.get('JPUSH_SECRET', "fe3dea5c60401e23c708cb5a") _jpush = jpush.JPush(app_key, master_secret) print '_push', _jpush push = _jpush.create_push() push.audience = jpush.all_ push.notification = jpush.notification(alert="Hello, world!") push.platform = jpush.all_ ret = push.send() print 'ret=', ret
def send_like_notification(regid, like_num): if not regid or len(regid) <> 11: return 'invalid reg_id' _jpush = jpush.JPush(settings.JPUSH_APP_KEY, settings.JPUSH_APP_MASTER) push = _jpush.create_push() push.audience = jpush.registration_id(regid) push.notification = jpush.notification(ios=jpush.ios(alert='', content_available=True, extras={"like_num": like_num, "action": "like"})) push.options = dict(apns_production=False) push.platform = jpush.platform('ios') return push.send()
def post(self, *args, **kwargs): import jpush # __jpush = jpush.JPush('ba5645ed9b17309f7abb116b', '02947521a9540e832c8d0a6d') __jpush = jpush.JPush('ba930456252a3ac98c746dc7', 'b5ae4b7a4ff60e5c9045b278') useridList = self.get_body_argument("userid") msg = self.get_body_argument("msg") print(useridList) print(msg) '''
def AsyncDelBlackList(user_id,black_user_id): from users.models import User userObj = User.objects.get(user_id = long(user_id)) try: from users.models import Remarks remObj = Remarks.objects.get(target_id=long(black_user_id),remuser_id=long(user_id)) user_name = remObj.user_remarks except: user_name = userObj.user_nick user_type = userObj.user_type user_portrait = userObj.user_portrait user_public_status = userObj.user_public_status user_profession = userObj.user_profession user_signature = userObj.user_signature user_level = userObj.user_level user_phone_number = userObj.user_phone_number familyId = userObj.user_family_id try: from users.models import FamilyRecord frObj = FamilyRecord.objects.get(family_id=familyId) building_num = frObj.family_building_num aptnum = frObj.family_apt_num except: building_num = None aptnum = None from users.views import genNeighborDict userInfo = genNeighborDict(user_id,user_name,user_portrait,building_num,aptnum,familyId,user_type,\ user_phone_number,user_profession,user_signature,user_level,user_public_status) config = readIni() pushContent = userInfo alias = config.get("SDK", "youlin") apiKey = config.get("SDK", "apiKey") secretKey = config.get("SDK", "secretKey") currentAlias = alias + str(black_user_id) _jpush = jpush.JPush(apiKey,secretKey) push = _jpush.create_push() push.audience = jpush.all_ push.audience = jpush.audience( jpush.alias(currentAlias), ) push.message = jpush.message( pushContent, u"push_del_black", None, None ) push.options = {"time_to_live":3600, "sendno":9527, "apns_production":PUSH_STATUS} push.platform = jpush.all_ push.send()
def jpush_foundpage(channel_no, version, id, title, city): if JPUSH.SWITCH and channel_no == JPUSH.DEFAULT_CHANNELNO and version >= JPUSH.DEFAULT_VERSION: import jpush oCmsChannelJpush = CmsChannelJpush.objects.get(channel_no=channel_no) cities = city.split(",") new_cities = [] for city in cities: if len(city) > 2 and city[-1] in ["市", "县"]: city = city[:-1] new_cities.append(city) cities = new_cities version = "Putao_" + version.replace(".", "_") app_key = oCmsChannelJpush.app_key master_secret = oCmsChannelJpush.master_secret _jpush = jpush.JPush(app_key, master_secret) push = _jpush.create_push() push.platform = jpush.all_ for i in range(0, len(cities), 20): city = cities[i:i + 20] msg_time = int(time.time()) city_list = [] # push.audience = jpush.all_ if "*" in city: push.audience = jpush.audience(jpush.tag(channel_no, version)) else: push.audience = jpush.audience( jpush.tag(*city), jpush.tag_and(channel_no, version)) city_list = city # push.notification = jpush.notification(alert="new found page") messages = { "version": 1, "data": [{ "msg_digest": title, "msg_type": 10, "msg_subject": title, "msg_id": id, "is_notify": 0, "msg_expand_param": { "tab_index": 1, "city_list": city_list }, "msg_time": msg_time, "msg_product_type": "0" }] } push.message = {"msg_content": json.dumps(messages)} push.send()