def sendToUser(self, userId): ''' 返回实际发送的数量 ''' itemId = self.reward.get('itemId') desc = self.reward.get('desc') bottom = self.reward.get('bottom') avg = self.reward.get('avg') top = self.reward.get('top') lteprob= self.reward.get('lteprob') if random.random() <= lteprob: count = random.randrange(bottom, avg + 1) else: count = random.randrange(avg, top + 1) assets = {'itemId':itemId, 'count':count} ftlog.debug('RandomRewardHandler.sendToUser', 'userId=', userId, 'self.reward=', self.reward, 'assets=', assets) desc = strutil.replaceParams(desc, {'count':count}) mail = strutil.replaceParams(self.mail, {'assets_reward_desc':desc}) UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, assets, WishingWell.EVENT_ID, mail) return count
def recommendProductIfCan(self, gameId, userId): # 没有配置推荐商品,则不推荐 payOrder = Tool.dictGet(self._clientConf, 'config.server.payOrder') if not payOrder: return False clientId = sessiondata.getClientId(userId) product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder) ftlog.debug('FunAct.recommendProductIfCan:', 'userId=', userId, 'product=', product) # 没有在货架中找到商品 if not product: return False translateMap = { 'product.displayName': product.displayName, 'product.price': product.price, 'count': payOrder.get('contains', {}).get('count', 0) } desc = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipDesc') note = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipNote') desc = strutil.replaceParams(desc, translateMap) note = strutil.replaceParams(note, translateMap) todotask = TodoTaskLessBuyOrder(desc, None, note, product) TodoTaskHelper.sendTodoTask(gameId, userId, todotask) return True
def exchangeCouponItem(self, userId, couponId, **kwargs): couponItem = self.findCouponItem(couponId) if not couponItem: if ftlog.is_debug(): ftlog.debug('CouponService.exchangeCouponItem userId=', userId, 'couponId=', couponId, 'kwargs=', kwargs, 'gameId=', self.gameId, 'coupons=', self._couponItemMap.keys()) raise TYBizException(-1, 'Not found couponId %s' % (couponId)) if (couponItem.itemType == CouponItem.TYPE_PHONE_CARD and not kwargs.get('phone')): # 检查chargePhone参数 raise TYBizException(-1, 'Please input phone number') # 减奖券 trueDelta, final = pkuserchip.incrCoupon(userId, self.gameId, -couponItem.couponCount, pkdaoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE, 0, 0, 0) if -trueDelta < couponItem.couponCount: raise TYBizException(-1, 'Coupon not enough') if couponItem.itemType == CouponItem.TYPE_PHONE_CARD: phone = kwargs.get('phone') isCtyOk = sdkclient.couponCharge(self.gameId, userId, phone, '', '', couponItem.couponCount, couponItem.itemCount) if isCtyOk: mail = couponItem.mailOk else: mail = couponItem.mailFail if mail: mail = strutil.replaceParams(mail, { 'couponCount': str(couponItem.couponCount), 'itemCount': str(couponItem.itemCount), 'itemName': couponItem.itemName, 'phone': phone, 'qqGroup': self._qqGroup }) pkmessage.send(HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, userId, mail) datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, 'message') elif couponItem.itemType == CouponItem.TYPE_ID_CHIP: pkuserchip.incrChip(userId, self.gameId, couponItem.itemCount, pkdaoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE, 0, 0, 0) mail = couponItem.mailOk if mail: mail = strutil.replaceParams(mail, { 'couponCount': str(couponItem.couponCount), 'itemCount': str(couponItem.itemCount), 'itemName': couponItem.itemName, 'qqGroup': self._qqGroup }) pkmessage.send(HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, userId, mail) datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, 'message') return trueDelta, final
def buildQueryPrizeResponse(cls, gameId, userId, clientId): timestamp = pktimestamp.getCurrentTimestamp() conf = neituiguang.getConf() status = neituiguang.loadStatus(userId, timestamp) totalRewardCount = cls.calcTotalInvitationByState( status, Invitation.STATE_REWARD) availableRewardCount = cls.calcTotalInvitationByState( status, Invitation.STATE_ACCEPT) mo = MsgPack() mo.setCmd('promote_info') mo.setResult('action', 'query_prize') mo.setResult('detail', conf.prizeDetail) mo.setResult('imgUrl', conf.prizeImgUrl) mo.setResult('promoteCode', userId) shareId = hallshare.getShareId('neituiguang2', userId, gameId) share = hallshare.findShare(shareId) if share: mo.setResult('shareId', shareId) mo.setResult('shareLoc', conf.shareLoc) mo.setResult('weixinInviteDoc', share.getDesc(HALL_GAMEID, userId)) mo.setResult('weixinInviteUrl', share.getUrl(HALL_GAMEID, userId)) mo.setResult('smsInviteDoc', share.getSmsDesc(HALL_GAMEID, userId)) totalRewardContent = '' if conf.prizeRewardItem: totalRewardContent = hallitem.buildContent( conf.prizeRewardItem.assetKindId, conf.prizeRewardItem.count * totalRewardCount) prizeGetedInfo = conf.prizeGotTotalRewardDesc if conf.prizeRewardItem and totalRewardCount else conf.prizeNotGotRewardDesc prizeGetedInfo = strutil.replaceParams( prizeGetedInfo, {'totalRewardContent': totalRewardContent}) mo.setResult('prizeGetedInfo', prizeGetedInfo) availableRewardContent = '' if conf.prizeRewardItem: availableRewardContent = hallitem.buildContent( conf.prizeRewardItem.assetKindId, conf.prizeRewardItem.count * availableRewardCount) prizeAvailableInfo = conf.prizeAvailableRewardDesc if conf.prizeRewardItem else conf.prizeAvailableRewardDesc prizeAvailableInfo = strutil.replaceParams( prizeAvailableInfo, {'availableRewardContent': availableRewardContent}) mo.setResult('prizeAvailableInfo', prizeAvailableInfo) prizeList = [] invitationList = sorted(status.inviteeMap.values(), key=lambda i: i.index) for invitation in invitationList: prizeList.append(cls.encodeInvitation(invitation)) mo.setResult('prizeList', prizeList) mo.setResult('state', 1 if availableRewardCount > 0 else 0) return mo
def richtextFormatReplaceParams(cls, richtext, dictionary): ''' promptText中的变量替换 :param richtext: promptText富文本配置 :param dictionary: 变量字典 :return: 替换好的富文本 ''' if isinstance(richtext, basestring): return strutil.replaceParams(richtext, dictionary) for line in richtext: for lineitem in line: lineitem['text'] = strutil.replaceParams(lineitem['text'], dictionary) return richtext
def newTodoTask(self, gameId, userId, clientId, timestamp, **kwargs): subMemberStatus = kwargs.get( 'subMemberStatus') or hallsubmember.loadSubMemberStatus(userId) if subMemberStatus.isSub: todotask = TodoTaskMemberBuy(self.descForMember, self.pic) todotask.setParam('tip_bottom', self.tipForSubMember) return todotask memberInfo = kwargs.get('memberInfo') or hallitem.getMemberInfo( userId, timestamp) remainDays = memberInfo[0] todotask = None subActionText = None product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, self.payOrder) if not product: return None if remainDays > 0: todotask = TodoTaskMemberBuy(self.descForMember, self.pic) tipForMember = strutil.replaceParams(self.tipForMember, {'remainDays': str(remainDays)}) todotask.setParam('tip_bottom_left', tipForMember) todotask.setParam('sub_action_text', self.subActionTextForMember) else: price = product.price priceUnits = '元' if product.buyType == 'consume': price = product.priceDiamond priceUnits = '钻石' params = { 'product.price': str(price), 'product.priceUnits': priceUnits } if product.content and product.content.desc: params['product.content.desc'] = product.content.desc desc = strutil.replaceParams(self.desc, params) todotask = TodoTaskMemberBuy(desc, self.pic) todotask.setSubText(self.subActionText) todotask.setParam('sub_action_text', self.subActionText) todotask.setSubCmdWithText(TodoTaskPayOrder(product), subActionText) if remainDays <= 0 and self.closeAction: closeAction = decodeTodotaskFactoryByDict( self.closeAction).newTodoTask(gameId, userId, clientId, **kwargs) if closeAction: todotask.setParam('sub_action_close', closeAction) return todotask
def sendRewards(self, userId, timestamp): if ftlog.is_debug(): ftlog.debug('FTTableFinishRecorder.sendRewards', 'userId=', userId, 'rewardContent=', self.rewardContent) if not self.rewardContent: return userAssets = hallitem.itemSystem.loadUserAssets(userId) assetList = userAssets.sendContent(DIZHU_GAMEID, self.rewardContent, 1, True, timestamp, 'ACTIVITY_REWARD', self.intActId) changed = None if assetList: changed = TYAssetUtils.getChangeDataNames(assetList) if self.mail: mail = strutil.replaceParams( self.mail, {'rewardContent': TYAssetUtils.buildContentsString(assetList)}) pkmessage.sendPrivate(HALL_GAMEID, userId, 0, mail) if not changed: changed = set(['message']) if changed: datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, changed) ftlog.info('FTTableFinishRecorder.sendRewards', 'userId=', userId, 'rewards=', [(at[0].kindId, at[1]) for at in assetList])
def getInputParams(self, gameId, userBag, item, timestamp): ret = strutil.cloneData(self._inputParams) desc = ret.get('desc', '') status = loadSubMemberStatus(userBag.userId) unsubDesc = status.unsubDesc or '' ret['desc'] = strutil.replaceParams(desc, {'unsubDesc': unsubDesc}) return ret
def replacedDomain(urlString, replaceDict): ''' 获取宏定义对应的域名 如果没有对应的宏定义配置或者宏定义配置为空,会返回None ''' global _dominMap if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain _dominMap: ', _dominMap) for domain in _dominMap: domains = _dominMap[domain] if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain domains: ', domains, ' length:', len(domains)) if len(domains) == 0: continue # 按时间平均随机 nChoose = getIndexBySecondInDay(len(domains)) replaceDict[domain] = domains[nChoose] if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain replaceDict: ', replaceDict) if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain ', urlString, ' replaced params: ', replaceDict) return strutil.replaceParams(urlString, replaceDict)
def buildBetResponse(self, gameId, status, chip, target): ret = {'ec': 0} ret['chip'] = self.buildChipStr(chip) ret['target'] = target ret['totalBet'] = strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet(target)}) return ret
def sendLedText(self, activityGameId, userId, prize): ledsMap = Tool.dictGet(self._clientConf, 'config.server.ledsMap', {}) prizes = Tool.dictGet(self._clientConf, 'config.server.prizes', []) for item in prizes: # 根据奖励itemId找到奖励配置 if item['itemId'] != prize['itemId']: continue # 获取led发送的配置 ledItem = ledsMap.get(item.get('ledKey')) if not ledItem: continue # 查看是否满足LED发送条件 if ledItem.get('minCount', 0) > prize['count']: continue text = ledItem.get('text') if not text: continue prizeContent = hallitem.buildContent(prize['itemId'], prize['count'], True) ledtext = strutil.replaceParams( text, { 'nickname': UserInfo.getNickname(userId), 'prizeContent': prizeContent }) hallled.sendLed(activityGameId, ledtext, 0, scope='hall6') if ftlog.is_debug(): ftlog.debug('LuckyMoneyNew.sendLedText', 'activityGameId=', activityGameId, 'activityId=', self._clientConf['id'], 'userId=', userId, 'ledtext=', ledtext) break
def _sendRewards(self, status, task, timestamp): from hall.game import TGHall userAssets = hallitem.itemSystem.loadUserAssets(status.userId) assetList = userAssets.sendContent(self.gameId, task.taskKind.rewardContent, 1, True, timestamp, 'HALL_RP_TASK_REWARD', task.kindId) ftlog.info('RPTaskSystem._sendRewards', 'gameId=', self.gameId, 'userId=', status.userId, 'kindId=', task.kindId, 'assets=', [(atup[0].kindId, atup[1]) for atup in assetList]) changed = TYAssetUtils.getChangeDataNames(assetList) datachangenotify.sendDataChangeNotify(self.gameId, status.userId, changed) if task.taskKind.rewardMail: contents = TYAssetUtils.buildContentsString(assetList) mail = strutil.replaceParams(task.taskKind.rewardMail, {'rewardContent': contents}) pkmessage.sendPrivate(HALL_GAMEID, status.userId, 0, mail) TGHall.getEventBus().publishEvent( UserRedPacketTaskRewardEvent(status.userId, HALL_GAMEID, task.taskKind, assetList)) couponCount = TYAssetUtils.getAssetCount(assetList, hallitem.ASSET_COUPON_KIND_ID) if couponCount > 0: TGHall.getEventBus().publishEvent( UserReceivedCouponEvent( HALL_GAMEID, status.userId, couponCount, hall_red_packet_const.RP_SOURCE_RP_TASK))
def getVCode(cls, userId, mobile): ''' 获取验证码 ''' # 随机一个验证码,注意验证码位数 vcode = random.randint(1000, 9999) # 四位的验证码 # 格式化短信内容 vcode_expiryminute = cls.getConf('vcode_expiryminute', 10) vcode_content = cls.getConf('vcode_content') content = strutil.replaceParams( vcode_content, { 'vcode': vcode, 'vcode_expiryminute': vcode_expiryminute }) # 发送短信 resp = SDKInterface.sendSms(userId, mobile, content) resp_code = resp.get('code', ErrorEnum.ERR_OK) resp_info = resp.get('info') ftlog.debug('PlayerControl.getVCode:', 'userId=', userId, 'resp_code=', resp_code, 'resp_info=', resp_info) if resp_code != ErrorEnum.ERR_OK: return cls.makeResponse(userId, ErrorEnum.ERR_SEND_SMS) # 记录验证码信息 data = {'vcode': vcode, 'stamp': time.time()} PlayerData.setVCode(userId, data) # 给玩家返回信息 response = cls.makeResponse(userId) # response.setResult('vcode', vcode) return response
def getMatchShareInfo(userName, raceName, rank, reward, userId, condiction, clientId): DIZHU_GAMEID = 6 shareIds = getNewShareInfoByCondiction(DIZHU_GAMEID, clientId, condiction).get('shareIds', {}) rewardInfo = getNewShareInfoByCondiction(DIZHU_GAMEID, clientId, condiction).get('rewardInfo', {}) shareId = shareIds.get('weixin', 0) if shareIds else None if not shareId: return None share = hallshare.findShare(shareId) params = { 'userName': userName, 'raceName': raceName, 'rank': rank, 'reward': reward } todotask = share.buildTodotask(DIZHU_GAMEID, userId, 'diploma_share') desc = todotask.getParam('des', '') todotask.setParam('des', strutil.replaceParams(desc, params)) todotaskDict = todotask.toDict() todotaskDict['rewardInfo'] = rewardInfo if rewardInfo else None if ftlog.is_debug(): ftlog.debug('getMatchShareInfo userId=', userId, 'shareId=', shareId, 'userName='******'raceName=', raceName, 'rank=', rank, 'reward=', reward, 'condiction=', condiction) return todotaskDict
def doGetPrize(self, gameId, userId, clientId): try: timestamp = pktimestamp.getCurrentTimestamp() status = neituiguang.loadStatus(userId, timestamp) if not status.isBindMobile: conf = neituiguang.getConf() TodoTaskHelper.sendTodoTask( gameId, userId, TodoTaskBindPhone(conf.pleaseBindPhone, '')) return count, assetList = neituiguang.getAllReward(status) if count > 0: conf = neituiguang.getConf() prizeRewardTips = strutil.replaceParams( conf.prizeRewardTips, { 'rewardContent': TYAssetUtils.buildContentsString(assetList) }) TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskGoldRain(prizeRewardTips)) mo = self.buildQueryPrizeResponse(gameId, userId, clientId) router.sendToUser(mo, userId) else: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('奖励已经领取', True)) datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc']) except TYBizException, e: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(e.message, True))
def buildGotGiftDesc(self, gotVipGiftResult): desc = hallvip.vipSystem.getGotGiftDesc() if desc: contents = TYAssetUtils.buildContentsString( gotVipGiftResult.giftItemList) desc = strutil.replaceParams(desc, {'rewardContent': contents}) return desc
def buildVipLevelUpDesc(self, userId, oldVipLevel, userVip): vipLevelUpDesc = hallvip.vipSystem.getLevelUpDesc() return strutil.replaceParams( vipLevelUpDesc, { 'oldLevel': str(oldVipLevel.level), 'curLevel': str(userVip.vipLevel.level) })
def sendReward(userId, rewardConf, mailstr, eventId, eventParam): """ 通用发货 param: rewardConf 奖励配置 格式: { 'typeId': 'FixedContent', 'items': [{'itemId': 'user:chip', 'count': 100}] } param: mailstr 邮件内容文本字符串,其中包含子串\\${rewardContent} eventId: 哪个事件触发的 eventParam: 事件参数 return: list<(TYAssetKind, consumeCount, final)> """ rewardContent = TYContentRegister.decodeFromDict(rewardConf) userAssets = hallitem.itemSystem.loadUserAssets(userId) assetList = userAssets.sendContent(DIZHU_GAMEID, rewardContent, 1, True, pktimestamp.getCurrentTimestamp(), eventId, eventParam) changeNames = TYAssetUtils.getChangeDataNames(assetList) contents = TYAssetUtils.buildContentsString(assetList) if mailstr: mailstr = strutil.replaceParams(mailstr, {'rewardContent': contents}) message.send(DIZHU_GAMEID, message.MESSAGE_TYPE_SYSTEM, userId, mailstr) changeNames.add('message') datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, changeNames) return assetList
def sendRewardToUser(self, userId, mail, intActId, charged_rmb): ftlog.debug('GiftboxEntry.sendRewardToUser:begin', 'userId=', userId, 'mail=', mail, 'charged_rmb=', charged_rmb) # 将礼包道具消耗掉, ok = UserBag.consumeAssetsIfEnough(userId, self._itemId, 1, 'ACTIVITY_REWARD', DIZHU_GAMEID, intActId) if not ok: ftlog.debug('GiftboxEntry.sendRewardToUser:consumeitem', 'userId=', userId, 'ok=', ok) return False if mail and self._reward.get('desc'): desc = self._reward.get('desc') mail = strutil.replaceParams(mail, {'rewardContent':desc}) else: mail = None UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, self._reward, 'ACTIVITY_REWARD', mail, intActId) ftlog.info('GiftboxEntry:sendRewardToUser:'******'gameId=', DIZHU_GAMEID, 'userId=', userId, 'itemId=', self._itemId, 'charged_rmb=', charged_rmb, 'reward=', self._reward) return True
def buildLuckyDrawMessage(cls, itemconf): ''' 构建response中的结果说明信息 ''' message = itemconf.get('message', '') dictionary = {'assets_desc': itemconf.get('desc', '')} return strutil.replaceParams(message, dictionary)
def replacedDomain(urlString, replaceDict): ''' 获取宏定义对应的域名 如果没有对应的宏定义配置或者宏定义配置为空,会返回None ''' global _dominMap if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain _dominMap: ', _dominMap) for domain in _dominMap: domains = _dominMap[domain] if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain domains: ', domains, ' length:' , len(domains)) if len(domains) == 0: continue # 按时间平均随机 nChoose = getIndexBySecondInDay(len(domains)) replaceDict[domain] = domains[nChoose] if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain replaceDict: ', replaceDict) if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain ', urlString, ' replaced params: ', replaceDict) return strutil.replaceParams(urlString, replaceDict)
def processLoseOutRoom(gameId, userId, clientId, roomId): # 处理江湖救急流程 if ftlog.is_debug(): ftlog.debug('table_remote.processLoseOutRoom gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'roomId=', roomId) title = '' desc = '' tips = '' vipBenefits = 0 try: consumeCount, _finalCount, vipBenefits = hallvip.userVipSystem.gainAssistance( gameId, userId) if ftlog.is_debug(): ftlog.debug('table_remote.processLoseOutRoom gameId=', gameId, 'userId=', userId, 'roomId=', roomId, 'consumeCount=', consumeCount, 'vipBenefits=', vipBenefits) if consumeCount > 0: title = hallflipcardluck.getString('vipBenefits.title', 'VIP专属江湖救急') desc = hallflipcardluck.getString('vipBenefits.desc', '金币不够啦,送您一次翻奖机会,快来试试手气吧') tips = hallflipcardluck.getString('vipBenefits.title', '再送您${vipBenefits}江湖救急') tips = strutil.replaceParams(tips, {'vipBenefits': str(vipBenefits)}) except TYBizException: pass except: ftlog.error('table_remote.processLoseOutRoom gameId=', gameId, 'userId=', userId, 'roomId=', roomId) todotasks = [] if vipBenefits > 0: goldRainDesc = strutil.replaceParams( hallvip.vipSystem.getGotGiftDesc(), {'content': '%s金币' % (vipBenefits)}) todotasks.append(TodoTaskGoldRain(goldRainDesc)) datachangenotify.sendDataChangeNotify(gameId, userId, 'chip') else: desc = hallflipcardluck.getString('benefits.desc', '金币不够啦,送您一次翻奖机会,快来试试手气吧') if ftlog.is_debug(): ftlog.debug('table_remote.processLoseOutRoom gameId=', gameId, 'userId=', userId, 'roomId=', roomId, 'benefits=', desc) todotasks.append(TodotaskFlipCardNew(gameId, roomId, title, desc, tips)) return TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
def buildQueryPrizeResponse(cls, gameId, userId, clientId): timestamp = pktimestamp.getCurrentTimestamp() conf = neituiguang.getConf() status = neituiguang.loadStatus(userId, timestamp) totalRewardCount = cls.calcTotalInvitationByState(status, Invitation.STATE_REWARD) availableRewardCount = cls.calcTotalInvitationByState(status, Invitation.STATE_ACCEPT) mo = MsgPack() mo.setCmd('promote_info') mo.setResult('action', 'query_prize') mo.setResult('detail', conf.prizeDetail) mo.setResult('imgUrl', conf.prizeImgUrl) mo.setResult('promoteCode', userId) shareId = hallshare.getShareId('neituiguang2', userId, gameId) share = hallshare.findShare(shareId) if share: mo.setResult('shareId', shareId) mo.setResult('shareLoc', conf.shareLoc) mo.setResult('weixinInviteDoc', share.getDesc(HALL_GAMEID, userId)) mo.setResult('weixinInviteUrl', share.getUrl(HALL_GAMEID, userId)) mo.setResult('smsInviteDoc', share.getSmsDesc(HALL_GAMEID, userId)) totalRewardContent = '' if conf.prizeRewardItem: totalRewardContent = hallitem.buildContent(conf.prizeRewardItem.assetKindId, conf.prizeRewardItem.count * totalRewardCount) prizeGetedInfo = conf.prizeGotTotalRewardDesc if conf.prizeRewardItem and totalRewardCount else conf.prizeNotGotRewardDesc prizeGetedInfo = strutil.replaceParams(prizeGetedInfo, {'totalRewardContent': totalRewardContent}) mo.setResult('prizeGetedInfo', prizeGetedInfo) availableRewardContent = '' if conf.prizeRewardItem: availableRewardContent = hallitem.buildContent(conf.prizeRewardItem.assetKindId, conf.prizeRewardItem.count * availableRewardCount) prizeAvailableInfo = conf.prizeAvailableRewardDesc if conf.prizeRewardItem else conf.prizeAvailableRewardDesc prizeAvailableInfo = strutil.replaceParams(prizeAvailableInfo, {'availableRewardContent': availableRewardContent}) mo.setResult('prizeAvailableInfo', prizeAvailableInfo) prizeList = [] invitationList = sorted(status.inviteeMap.values(), key=lambda i: i.index) for invitation in invitationList: prizeList.append(cls.encodeInvitation(invitation)) mo.setResult('prizeList', prizeList) mo.setResult('state', 1 if availableRewardCount > 0 else 0) return mo
def getRealUserMail(cls, mailList, paramsDict): ''' 替换配置中的邮箱 ''' mailList = copy.deepcopy(mailList) for text in mailList: text['text'] = strutil.replaceParams(text['text'], paramsDict) return mailList
def doQuickBuyGetInfo(self, gameId, userId): clientId = sessiondata.getClientId(userId) toStoreTodotask = TodoTaskGotoShop('coin') if hallstore.storeSystem.isCloseLastBuy(clientId): TodoTaskHelper.sendTodoTask(gameId, userId, toStoreTodotask) return lastBuyProduct, _lastBuyClientId = hallstore.storeSystem.getLastBuyProduct( gameId, userId) if (not lastBuyProduct or not lastBuyProduct.recordLastBuy or not hallstore.storeSystem.canBuyProduct( gameId, userId, clientId, lastBuyProduct, 1)): if hallstore.storeSystem.lastBuyConf.payOrder: product, _ = hallstore.findProductByPayOrder( gameId, userId, clientId, hallstore.storeSystem.lastBuyConf.payOrder) if product: payOrderTodoTask = TodoTaskPayOrder(product) desc = strutil.replaceParams( hallstore.storeSystem.lastBuyConf.desc2, { 'product.displayName': product.displayName, 'product.price': product.price }) popInfoTodoTask = TodoTaskShowInfo(desc, True) popInfoTodoTask.setSubCmd(payOrderTodoTask) TodoTaskHelper.sendTodoTask(gameId, userId, popInfoTodoTask) return TodoTaskHelper.sendTodoTask(gameId, userId, toStoreTodotask) return payOrderTodoTask = TodoTaskPayOrder(lastBuyProduct) desc = strutil.replaceParams( hallstore.storeSystem.lastBuyConf.desc, { 'product.displayName': lastBuyProduct.displayName, 'product.price': lastBuyProduct.price }) popInfoTodoTask = TodoTaskShowInfo(desc, True) popInfoTodoTask.setSubCmd(payOrderTodoTask) popInfoTodoTask.setSubText(hallstore.storeSystem.lastBuyConf.subText) popInfoTodoTask.setSubCmdExt(toStoreTodotask) popInfoTodoTask.setSubTextExt( hallstore.storeSystem.lastBuyConf.subTextExt) TodoTaskHelper.sendTodoTask(gameId, userId, popInfoTodoTask)
def filterAssetDesc(cls, flippedCard): desc = flippedCard.flipableCard.desc assetDesc = flippedCard.assetKind.desc if not desc: return assetDesc return strutil.replaceParams(desc, { 'itemDesc': assetDesc, 'count': flippedCard.count })
def buildGotAssistanceDesc(self, finalCount, sendChip): desc = hallvip.vipSystem.getGotAssistanceDesc() or '' if desc: assetKind = hallitem.itemSystem.findAssetKind( hallitem.ASSET_CHIP_KIND_ID) return strutil.replaceParams( desc, {'rewardContent': '%s%s' % (sendChip, assetKind.displayName)}) return desc
def getDesc(self, gameId, userId, randChoise=False): if self.def_desc and not randChoise: return self.def_desc shareDesc = self.desc.getValue(userId, gameId) if ftlog.is_debug(): ftlog.debug('HallShare.getDesc desc: ', shareDesc) return strutil.replaceParams(shareDesc, {'promoteCode': userId, 'url': self.getUrl(gameId, userId)})
def filterProductDesc(self, flippedCard): desc = flippedCard.flipableCard.desc if not desc: return flippedCard.product.content.desc return strutil.replaceParams(desc, { 'contentDesc': flippedCard.product.content.desc, 'price': flippedCard.product.price, 'chipCount': flippedCard.product.getMinFixedAssetCount(hallitem.ASSET_CHIP_KIND_ID) })
def getMatchHistory(cls, userId, recordId, number=0, mixId=None): ''' 获取比赛历史 ''' # # 若请求的历史记录数量小于等于0,则返回记录的所有条数 if number <= 0: number = MatchHistoryDatabaseNew.getMaxHistoryNumber() # # 获得格式化字符串 conf = getMatchHistoryConfig() reward_case = conf.get('reward_format', '') noreward_case = conf.get('no_reaward_format', '') history_group_word = conf.get('history_group_word', '') response = [] histories = MatchHistoryDatabaseNew.getLeastHistory(userId, recordId, number, mixId) ftlog.debug('MatchHistoryHandler.onFetchMatchHistory:', 'userId=', userId, 'recordId=', recordId, 'number=', number, 'mixId=', mixId, 'histories=', histories) for i in xrange(0, len(histories)): historyrecord = histories[i] historytime = historyrecord.get('time', 0) historyrank = historyrecord.get('rank', 0) historyreward = historyrecord.get('reward') historyIsGroping = historyrecord.get('isGroping', False) historyExchangeCode = historyrecord.get('exchangeCode', 0) dictionary = { 'history_reward':historyreward, 'history_rank': historyrank, 'history_group': history_group_word if historyIsGroping else '' } if historyreward: # # 有奖励的情况下 resultdesc = strutil.replaceParams(reward_case, dictionary) else: # # 无奖励的情况 resultdesc = strutil.replaceParams(noreward_case, dictionary) response.insert(i, {'timestamp':historytime, 'desc': resultdesc, 'rank': historyrank, 'exchangeCode': historyExchangeCode}) response.reverse() return response
def buildLuckyDrawMailMessage(cls, itemconf, roomId): ''' 构建邮箱信息 ''' conf = getWarmupSystemConfig() mail = conf.get('mail', '') roomconf = gdata.getRoomConfigure(roomId) matchName = roomconf.get('name', '') dictionary = {'assets_desc': itemconf.get('desc', ''), 'match_name':matchName} return strutil.replaceParams(mail, dictionary)
def newTodoTask(self, gameId, userId, clientId, timestamp, **kwargs): subMemberStatus = kwargs.get('subMemberStatus') or hallsubmember.loadSubMemberStatus(userId) if subMemberStatus.isSub: todotask = TodoTaskMemberBuy(self.descForMember, self.pic) todotask.setParam('tip_bottom', self.tipForSubMember) return todotask memberInfo = kwargs.get('memberInfo') or hallitem.getMemberInfo(userId, timestamp) remainDays = memberInfo[0] todotask = None subActionText = None product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, self.payOrder) if not product: return None if remainDays > 0: todotask = TodoTaskMemberBuy(self.descForMember, self.pic) tipForMember = strutil.replaceParams(self.tipForMember, {'remainDays': str(remainDays)}) todotask.setParam('tip_bottom_left', tipForMember) todotask.setParam('sub_action_text', self.subActionTextForMember) else: price = product.price priceUnits = '元' if product.buyType == 'consume': price = product.priceDiamond priceUnits = '钻石' params = {'product.price': str(price), 'product.priceUnits': priceUnits} if product.content and product.content.desc: params['product.content.desc'] = product.content.desc desc = strutil.replaceParams(self.desc, params) todotask = TodoTaskMemberBuy(desc, self.pic) todotask.setSubText(self.subActionText) todotask.setParam('sub_action_text', self.subActionText) todotask.setSubCmdWithText(TodoTaskPayOrder(product), subActionText) if remainDays <= 0 and self.closeAction: closeAction = decodeTodotaskFactoryByDict(self.closeAction).newTodoTask(gameId, userId, clientId, **kwargs) if closeAction: todotask.setParam('sub_action_close', closeAction) return todotask
def getShareDownloadUrl(gameId, userId, source): clientId = sessiondata.getClientId(userId) ok, clientOs, cid, special, mc, sc = parseClientIdForDL(clientId) if not ok: ftlog.warn("getShareDownloadUrl|parseClientId|error", gameId, userId, source, cid, special, mc, sc) return channels = configure.getGameJson(HALL_GAMEID, "download").get("channels", {}) channel = clientOs + '.' + special + '.' + mc + '.' + sc downloadurl = channels['default'] if channel in channels: downloadurl = channels[channel] mix_domain = [ "dspkm.cc", "lkxjv.cc", "qkpwdfo.cc", "sijas.cc", "023i.cc", "lkjsdf.cc", "vdlskm.cc", "iojpdvs.cc", "sdvnkl.cc", "owirhj.cc", "lvsdp.cc", "msvdkn.cc", "dvslkm.cc", "odnsvk.cc", "p0joefipq.cc", "mvsdpok.cc", "02r389u.cc", "sdlknv.cc", "sdfioj.cc", "klsdvm.cc" ] domainList = configure.getGameJson(HALL_GAMEID, "misc").get("mix_domain", mix_domain) replaceDict = { 'mc': mc, 'sc': sc, 'cid': str(cid), 'uid': userId, 'mixDomain': genMixDomain(domainList) } downloadurl = strutil.replaceParams(downloadurl, replaceDict) parsedUrl = urlparse.urlparse(downloadurl) qparams = urlparse.parse_qs(parsedUrl.query) if parsedUrl.query else {} qparams = {k: v[0] for k, v in qparams.iteritems()} qparams.update({'source': source}) results = {} results['action'] = 'geturl' results['downloadurl'] = urlparse.urlunparse( (parsedUrl[0], parsedUrl[1], parsedUrl[2], parsedUrl[3], urllib.urlencode(qparams), parsedUrl[5])) from freetime.entity.msg import MsgPack from poker.protocol import router mp = MsgPack() mp.setCmd('share_hall') mp.setResult('gameId', gameId) mp.setResult('userId', userId) mp.updateResult(results) router.sendToUser(mp, userId) if ftlog.is_debug(): ftlog.debug("getShareDownloadUrl|", gameId, userId, results)
def flipCard(self, userId, index, timestamp=None): if timestamp is None: timestamp = pktimestamp.getCurrentTimestamp() status = self.loadStatus(userId, timestamp) remFlipCount = status.getRemFlipCount() if remFlipCount <= 0: ftlog.debug('DizhuFlipCard.flipCard userId=', userId, 'index=', index, 'nslogin='******'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'), 'remFlipCount=', remFlipCount) return False, status, None contentItem = status.findItemByIndex(index) if contentItem: ftlog.debug('DizhuFlipCard.flipCard userId=', userId, 'index=', index, 'nslogin='******'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'), 'alreadyFlipped=', '%s:%s' % (contentItem.assetKindId, contentItem.count)) return False, status, None regDays = self._calcRegDays(userId, timestamp) contentItem = self._flipCard(regDays) if not contentItem: ftlog.debug('DizhuFlipCard.flipCard userId=', userId, 'index=', index, 'nslogin='******'regDays=', regDays, 'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'), 'flipped=', None) return False, status, None status.addItem(index, contentItem) status.flipTime = timestamp remFlipCount = status.getRemFlipCount() if remFlipCount <= 0: status.paddings = self._makePaddings(userId) self._dao.saveStatus(userId, status) userAssets = hallitem.itemSystem.loadUserAssets(userId) assetItem = userAssets.addAsset(DIZHU_GAMEID, contentItem.assetKindId, contentItem.count, timestamp, 'NSLOGIN_REWARD', status.nslogin) contentString = TYAssetUtils.buildContent(assetItem) if self._rewardMail: mail = strutil.replaceParams(self._rewardMail, {'rewardContent':contentString}) pkmessage.sendPrivate(DIZHU_GAMEID, userId, 0, mail) datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, 'message') ftlog.debug('DizhuFlipCard.flipCard userId=', userId, 'index=', index, 'nslogin='******'regDays=', regDays, 'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'), 'reward=', contentString) return True, status, assetItem
def recommendProductIfNeed(self, gameId, userId, chip): # 当前金币足够则不用推荐商品 curchip = userchip.getChip(userId) ftlog.debug('BetGuess.recommendProductIfNeed:', 'userId=', userId, 'curchip=', curchip, 'chip=', chip) if curchip >= chip: return False # 没有配置推荐商品,则不推荐 payOrderMap = Tool.dictGet(self._clientConf, 'config.server.payOrderMap') if not payOrderMap: return False # 没有找到推荐商品配置,则不推荐 payOrder = payOrderMap.get(str(int(chip))) ftlog.debug('BetGuess.recommendProductIfNeed:', 'userId=', userId, 'payOrder=', payOrder) if not payOrder: return False clientId = sessiondata.getClientId(userId) product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder) ftlog.debug('BetGuess.recommendProductIfNeed:', 'userId=', userId, 'product=', product) # 没有在货架中找到商品 if not product: return False translateMap = { 'product.displayName': product.displayName, 'product.price': product.price, 'betchip': chip, } desc = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipDesc') note = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipNote') desc = strutil.replaceParams(desc, translateMap) note = strutil.replaceParams(note, translateMap) todotask = TodoTaskLessBuyOrder(desc, None, note, product) TodoTaskHelper.sendTodoTask(gameId, userId, todotask) return True
def doUpdateRecord(self, gameId, userId): mo = MsgPack() mo.setCmd('exchange') mo.setResult('action', 'update_record') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('record_list', ExchangeHelper.encodeRecordList(self._getCouponService().getExchangeRecords(userId))) mo.setResult('instruction', strutil.replaceParams(self._getCouponService().instruction, {'userId': str(userId)})) router.sendToUser(mo, userId)
def buildExpDesc(cls, userVip): expDesc = userVip.vipLevel.expDesc if not expDesc: return expDesc nextVipLevel = userVip.vipLevel.nextVipLevel or userVip.vipLevel return strutil.replaceParams(expDesc, { 'deltaExp': str(userVip.deltaExpToNextLevel()), 'deltaRmb': str(max(1, int(userVip.deltaExpToNextLevel() / 10))), 'nextVipLevel': str(nextVipLevel.level), 'nextVipLevelName': str(nextVipLevel.name), 'curVipLevel': str(userVip.vipLevel.level) })
def getConfigForClient(self, gameId, userId, clientId): status = self.loadUserQuizStatus(userId) userAssets = hallitem.itemSystem.loadUserAssets(userId) chip = userAssets.balance(gameId, self._serverConf['chipAssetId'], pktimestamp.getCurrentTimestamp()) or 0 stopBetTime = self.stopBetTime.strftime(self.TIMEFMT) if self.stopBetTime else '' config = { 'stopBetTime': stopBetTime, 'bgImg': self._serverConf['bgImg'], 'gameId': self._serverConf['gameId'], 'chip': self.buildChipStr(chip), 'leftImg': self._serverConf['leftImg'], 'leftTitle': self._serverConf['leftTitle'], 'leftBet': strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet('l')}), 'leftOdds': strutil.replaceParams(self._serverConf['oddsDesc'], {'odds': self._serverConf['leftOdds']}), 'middleBet': strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet('m')}), 'middleOdds': strutil.replaceParams(self._serverConf['oddsDesc'], {'odds': self._serverConf['middleOdds']}), 'rightImg': self._serverConf['rightImg'], 'rightTitle': self._serverConf['rightTitle'], 'rightBet': strutil.replaceParams(self._serverConf['totalBetDesc'], {'totalBet': status.getBet('r')}), 'rightOdds': strutil.replaceParams(self._serverConf['oddsDesc'], {'odds': self._serverConf['rightOdds']}), 'bet1': self._serverConf['bet1'], 'bet2': self._serverConf['bet2'], 'bet3': self._serverConf['bet3'] } self._clientConf['config'] = config return self._clientConf
def doQuickBuyGetInfo(self, gameId, userId): clientId = sessiondata.getClientId(userId) toStoreTodotask = TodoTaskGotoShop('coin') if hallstore.storeSystem.isCloseLastBuy(clientId): TodoTaskHelper.sendTodoTask(gameId, userId, toStoreTodotask) return lastBuyProduct, _lastBuyClientId = hallstore.storeSystem.getLastBuyProduct(gameId, userId) if (not lastBuyProduct or not lastBuyProduct.recordLastBuy or not hallstore.storeSystem.canBuyProduct(gameId, userId, clientId, lastBuyProduct, 1)): if hallstore.storeSystem.lastBuyConf.payOrder: product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, hallstore.storeSystem.lastBuyConf.payOrder) if product: payOrderTodoTask = TodoTaskPayOrder(product) desc = strutil.replaceParams(hallstore.storeSystem.lastBuyConf.desc2, {'product.displayName': product.displayName, 'product.price': product.price}) popInfoTodoTask = TodoTaskShowInfo(desc, True) popInfoTodoTask.setSubCmd(payOrderTodoTask) TodoTaskHelper.sendTodoTask(gameId, userId, popInfoTodoTask) return TodoTaskHelper.sendTodoTask(gameId, userId, toStoreTodotask) return payOrderTodoTask = TodoTaskPayOrder(lastBuyProduct) desc = strutil.replaceParams(hallstore.storeSystem.lastBuyConf.desc, {'product.displayName': lastBuyProduct.displayName, 'product.price': lastBuyProduct.price}) popInfoTodoTask = TodoTaskShowInfo(desc, True) popInfoTodoTask.setSubCmd(payOrderTodoTask) popInfoTodoTask.setSubText(hallstore.storeSystem.lastBuyConf.subText) popInfoTodoTask.setSubCmdExt(toStoreTodotask) popInfoTodoTask.setSubTextExt(hallstore.storeSystem.lastBuyConf.subTextExt) TodoTaskHelper.sendTodoTask(gameId, userId, popInfoTodoTask)
def buildProductDeliveryContent(cls, nt, succConf, orderDeliveryResult): try: sdkItem = None consume = '' chargeInfo = orderDeliveryResult.order.chargeInfo if chargeInfo and chargeInfo.chargeType: consume = str(chargeInfo.getCharge('rmb', 0)) + '元' dcount = chargeInfo.getCharge('diamond', 0) - chargeInfo.getConsume('coin', 0) if dcount > 0: sdkItem = {'name': '钻石', 'count': dcount, 'units': '个'} elif chargeInfo: consumes = [] for assetKindId, count in chargeInfo.consumeMap.iteritems(): if assetKindId == 'coin': consumes.append(str(chargeInfo.getConsume('coin', 0)) + '钻石') else: assetKind = hallitem.itemSystem.findAssetKind(assetKindId) if assetKind: consumes.append(assetKind.buildContent(count)) consume = ','.join(consumes) contentBase = succConf.get('content', u'您于${datetime}成功购买\n ${productName}\n本次消费:${consume}') contentList = [] if sdkItem: contentList.append(u'%s:%s%s' % (sdkItem['name'], sdkItem['count'], sdkItem['units'])) if orderDeliveryResult.assetItems: for assetKind, count, _final in orderDeliveryResult.assetItems: contentList.append(assetKind.buildContentForDelivery(count)) timestr = None try: timestr = nt.strftime(succConf.get('timefmt', '%Y-%m-%d %H:%M:%S')) except: ftlog.error() timestr = nt.strftime('%Y-%m-%d %H:%M:%S') return strutil.replaceParams(contentBase, { 'datetime': timestr, 'content': '\n'.join(contentList), 'productName': orderDeliveryResult.order.product.displayName, 'consume': consume, }) except: ftlog.error() return ''
def sendReward(self, rankingDefine, issueNumber, rankingUser, content): contentItemList = [] contentItems = content.getItems() for contentItem in contentItems: contentItemList.append({'itemId': contentItem.assetKindId, 'count': contentItem.count}) try: intRankingId = int(rankingDefine.rankingId) ret = user_remote.addAssets(HALL_GAMEID, rankingUser.userId, contentItemList, 'RANK_REWARD', intRankingId) if ret: mail = None if rankingDefine.rewardMail: rewardContent = hallitem.buildContentsString(contentItems) if rewardContent: params = { 'rankingName': rankingDefine.name, 'rank': rankingUser.rank + 1, 'rewardContent': hallitem.buildContentsString(contentItems) } mail = strutil.replaceParams(rankingDefine.rewardMail, params) if mail: gameId = rankingDefine.gameIds[0] if rankingDefine.gameIds else 0 if gameId == 0: gameId = 9999 pkmessage.sendPrivate(gameId, rankingUser.userId, 0, mail) ftlog.info('RankRewardSender.sendReward Succ userId=', rankingUser.userId, 'rankingId=', intRankingId, 'issueNumber=', issueNumber, 'rank=', rankingUser.rank + 1, 'rewards=', contentItemList, 'mail=', mail) else: ftlog.warn('RankRewardSender.sendReward Fail userId=', rankingUser.userId, 'rankingId=', intRankingId, 'issueNumber=', issueNumber, 'rank=', rankingUser.rank + 1, 'rewards=', contentItemList) except: ftlog.error('RankRewardSender.sendReward Exception userId=', rankingUser.userId, 'rankingId=', intRankingId, 'issueNumber=', issueNumber, 'rank=', rankingUser.rank + 1, 'rewards=', contentItemList)
def doGetPrize(self, gameId, userId, clientId): try: timestamp = pktimestamp.getCurrentTimestamp() status = neituiguang.loadStatus(userId, timestamp) if not status.isBindMobile: conf = neituiguang.getConf() TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskBindPhone(conf.pleaseBindPhone, '')) return count, assetList = neituiguang.getAllReward(status) if count > 0: conf = neituiguang.getConf() prizeRewardTips = strutil.replaceParams(conf.prizeRewardTips, {'rewardContent': TYAssetUtils.buildContentsString(assetList)}) TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskGoldRain(prizeRewardTips)) mo = self.buildQueryPrizeResponse(gameId, userId, clientId) router.sendToUser(mo, userId) else: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo('奖励已经领取', True)) datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc']) except TYBizException, e: TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(e.message, True))
def gainCheckinReward(self, gameId, userId, timestamp=None, actionType=0): if timestamp is None: timestamp = pktimestamp.getCurrentTimestamp() checkinOk, checkinDays = self.checkin(gameId, userId, timestamp) if ftlog.is_debug(): ftlog.debug('TYDailyCheckin.gainCheckinReward gameId=', gameId, 'userId=', userId, 'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'), 'checkinOk=', checkinOk, 'checkinDays=', checkinDays) if not checkinOk: return checkinOk, [], checkinDays # 发送奖励 rewardContent = self.getRewardContent(checkinDays) ebus = TGHall.getEventBus() ebus.publishEvent(TYDailyCheckinRewardEvent(gameId, userId, rewardContent, actionType)) if not rewardContent: return checkinOk, [], checkinDays userAssets = hallitem.itemSystem.loadUserAssets(userId) assetList = userAssets.sendContent(gameId, rewardContent, 1, True, timestamp, 'NSLOGIN_REWARD2', checkinDays) contents = TYAssetUtils.buildContentsString(assetList) if self._mail: mail = strutil.replaceParams(self._mail, {'rewardContent': contents}) pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, mail) datachangenotify.sendDataChangeNotify(gameId, userId, 'message') ftlog.debug('TYDailyCheckin.gainCheckinReward gameId=', gameId, 'userId=', userId, 'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'), 'reward=', contents) return checkinOk, assetList, checkinDays
def _onOrderDelivery(event): from hall.entity import hallitem nowDT = datetime.now() order = event.orderDeliveryResult.order if ((_conf.startDT and nowDT < _conf.startDT) or (_conf.endDT and nowDT >= _conf.endDT)): if ftlog.is_debug(): ftlog.debug('buy_send_gift._onOrderDelivery outofTime userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'nowDT=', nowDT.strftime('%Y-%m-%d %H:%M:%S'), 'startDT=', _conf.startDT.strftime('%Y-%m-%d %H:%M:%S'), 'endDT=', _conf.endDT.strftime('%Y-%m-%d %H:%M:%S')) return giftConf = _conf.findGiftConf(order.productId) if not giftConf: if ftlog.is_debug(): ftlog.debug('buy_send_gift._onOrderDelivery noGiftConf userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'orderClientId=', order.clientId) return hallGameId = strutil.getGameIdFromHallClientId(order.clientId) if hallGameId not in giftConf.gameIds: if ftlog.is_debug(): ftlog.debug('buy_send_gift._onOrderDelivery notInGameIds userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'giftConf=', giftConf.conf, 'orderClientId=', order.clientId, 'hallGameId=', hallGameId, 'gameIds=', giftConf.gameIds) return count = 0 if giftConf.maxCount >= 0: limitD = gamedata.getGameAttrJson(order.userId, hallGameId, 'act.buy_send_gift', {}) count = limitD.get(order.productId, 0) if count + 1 > giftConf.maxCount: ftlog.info('buy_send_gift._onOrderDelivery overLimit userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'giftConf=', giftConf.conf if giftConf else None, 'orderClientId=', order.clientId, 'count=', count, 'maxCount=', giftConf.maxCount) return count += 1 limitD[order.productId] = count gamedata.setGameAttr(order.userId, hallGameId, 'act.buy_send_gift', strutil.dumps(limitD)) assetList = None if giftConf.giftContent: userAssets = hallitem.itemSystem.loadUserAssets(order.userId) # def sendContent(self, gameId, content, count, ignoreUnknown, timestamp, eventId, intEventParam): assetList = userAssets.sendContent(hallGameId, giftConf.giftContent, 1, True, pktimestamp.getCurrentTimestamp(), 'ACTIVITY_REWARD', 10043) changedDataNames = TYAssetUtils.getChangeDataNames(assetList) if assetList else set() contentStr = TYAssetUtils.buildContentsString(assetList) if assetList else '' if giftConf.mail: mail = strutil.replaceParams(giftConf.mail, {'gotContent': contentStr, 'price': order.product.price}) message.send(hallGameId, message.MESSAGE_TYPE_SYSTEM, order.userId, mail) changedDataNames.add('message') if changedDataNames: datachangenotify.sendDataChangeNotify(HALL_GAMEID, order.userId, changedDataNames) ftlog.info('buy_send_gift._onOrderDelivery sendGift userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'giftConf=', giftConf.conf if giftConf else None, 'orderClientId=', order.clientId, 'count=', count, 'maxCount=', giftConf.maxCount, 'assetList=', [(a[0].kindId, a[1]) for a in assetList] if assetList else None)
def doQueryInviteInfo(self, gameId, userId, clientId): """ 查询邀请信息 上行: { "cmd": "game", "params": { "action": "query_invite_info", "gameId": 9999, "userId": 10323, "clientId": "IOS_3.9001_weixin.weixinPay,alipay.0-hall710.yitiao.ioshrbmj" } } 下行: { "cmd": "game", "result": { "action": "query_invite_info", "state": 1, "gameId": 9999, "bindUserId": 123456, "bindName": "123456", "bindPic": "", "rewardState": 0, "bindRewardCount": 12, "totalReward": 0, "inviteeList": [], "gotoInfo": { "title": "\\u4f53\\u9a8c\\u6e38\\u620f\\u9001\\u623f\\u5361\\u5566", "desc": "", "url": "http://www.shediao.com/youle/gamelist.html" }, "inviteShare": { "title": "\\u53ef\\u4ee5\\u548c\\u4eb2\\u53cb\\u4e00\\u8d77\\u6e38\\u620f\\u7684\\u9ebb\\u5c06", "desc": "\\u73a9\\u81ea\\u5efa\\u684c\\u672c\\u5730\\u9ebb\\u5c06\\uff0c\\u62a5\\u6211ID(10323)\\u5c31\\u9886\\u53d612\\u5f20\\u623f\\u5361", "url": "http://www.shediao.com/youle/gamelist.html" } } } """ timestamp = pktimestamp.getCurrentTimestamp() mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'query_invite_info') status = hall_simple_invite.loadStatus(userId, timestamp) # 是否已填写了邀请人 state = self.translateState(status) mo.setResult('state', state) mo.setResult('gameId', gameId) # 已绑定了邀请人 if state == 1 and status.inviter: bindUserId = status.inviter mo.setResult('bindUserId', bindUserId) name, pic = userdata.getAttrs(bindUserId, ['name', 'purl']) if not name or name == '': name = str(bindUserId) if not pic: pic = '' mo.setResult('bindName', name) mo.setResult('bindPic', pic) mo.setResult('rewardState', status.getRewardState(userId, gameId, clientId)) # 绑定奖励数 conf = hall_simple_invite.getSimpleInviteConf(userId, gameId, clientId) if not conf: ftlog.error('ClentId:', clientId, ' has no hall_simple_invite config, please check!!!') return if conf.inviteRewardItem: mo.setResult('bindRewardCount', conf.inviteRewardItem.count) userList, count = self.getInviteesRewardInfo(status, Invitation.STATE_REWARDED, clientId) # 自己绑定获取的 if status.rewardState == Invitation.STATE_REWARDED: count += 1 # 总奖励数 mo.setResult('totalReward', count * conf.inviteRewardItem.count) mo.setResult('inviteeList', userList) # 去邀请信息 goto = {} goto['title'] = conf.gotoTitle goto['desc'] = conf.gotoDesc goto['url'] = conf.gotoUrl mo.setResult('gotoInfo', goto) inviteShare = {} inviteShare['title'] = conf.inviteTitle inviteShare['desc'] = strutil.replaceParams(conf.inviteDesc, {'rewardContent': str(userId)}) inviteShare['url'] = conf.inviteUrl mo.setResult('inviteShare', inviteShare) router.sendToUser(mo, userId)
def filterAssetDesc(cls, flippedCard): desc = flippedCard.flipableCard.desc assetDesc = flippedCard.assetKind.desc if not desc: return assetDesc return strutil.replaceParams(desc, {'itemDesc': assetDesc, 'count': flippedCard.count})
def buildVipLevelUpDesc(self, userId, oldVipLevel, userVip): vipLevelUpDesc = hallvip.vipSystem.getLevelUpDesc() return strutil.replaceParams(vipLevelUpDesc, { 'oldLevel': str(oldVipLevel.level), 'curLevel': str(userVip.vipLevel.level) })
def getSmsDesc(self, gameId, userId): return strutil.replaceParams(self.smsDesc, {'promoteCode': userId, 'url': self.getUrl(gameId, userId)})
def exchangeProduct(gameId, userId, clientId, orderId, productId, count): product = storeSystem.findProduct(productId) if not product: raise TYBuyProductUnknownException(productId) if product.buyType != 'exchange': raise TYProductNotSupportExchangeException(productId) timestamp = pktimestamp.getCurrentTimestamp() # 限购系统锁定 periodId = hallstocklimit.productBuyLimitSystem.lockProduct(gameId, userId, productId, count, timestamp) # 创建订单 try: storeSystem.buyProduct(gameId, userId, clientId, orderId, productId, count) except: if periodId: hallstocklimit.productBuyLimitSystem.unlockProduct(gameId, userId, periodId, productId, count, 1, timestamp) raise # ftlog.info('hallstore.exchangeProduct gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'orderId=', orderId, 'productId=', productId, 'count=', count) try: # 消耗兑换的东西 userAssets = hallitem.itemSystem.loadUserAssets(userId) assetTuple = userAssets.consumeAsset(gameId, product.exchangeFeeContentItem.assetKindId, product.exchangeFeeContentItem.count * count, timestamp, 'BUY_PRODUCT', pokerconf.productIdToNumber(productId)) if assetTuple[1] < product.exchangeFeeContentItem.count * count: ftlog.warn('hallstore.exchangeProduct gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'orderId=', orderId, 'productId=', productId, 'count=', count, 'consumedCount=', assetTuple[1], 'needConsumeCount=', product.exchangeFeeContentItem.count * count, 'err=', 'ConsumeNotEnough') msg = strutil.replaceParams(product.exchangeFeeNotEnoughText, {'feeName': assetTuple[0].displayName}) raise TYProductExchangeNotEnoughException(productId, msg) datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames([assetTuple])) consumeMap = {assetTuple[0].kindId: assetTuple[1]} ret = storeSystem.deliveryOrder(userId, orderId, productId, TYChargeInfo('', {}, consumeMap)) # 分享提示 shareId = hallshare.getShareId('exchangeShare', userId, gameId) if ftlog.is_debug(): ftlog.debug('handleExchangeAuditResult shareId: ', shareId) share = hallshare.findShare(shareId) if share: desc = share.getDesc(gameId, userId, True) newDesc = strutil.replaceParams(desc, {'exchangeDesc': product.displayName}) share.setDesc(newDesc) task = share.buildTodotask(HALL_GAMEID, userId, 'exchange') TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, task) if periodId: hallstocklimit.productBuyLimitSystem.deliveryProduct(gameId, userId, periodId, productId, count, timestamp) return ret except: if periodId: hallstocklimit.productBuyLimitSystem.unlockProduct(gameId, userId, periodId, productId, count, 2, timestamp) raise
def filterAssetTips(cls, flippedCard): tips = flippedCard.flipableCard.tips return strutil.replaceParams(tips, {'count': flippedCard.count, 'units': flippedCard.item.units})
def buildGotGiftDesc(self, gotVipGiftResult): desc = hallvip.vipSystem.getGotGiftDesc() if desc: contents = TYAssetUtils.buildContentsString(gotVipGiftResult.giftItemList) desc = strutil.replaceParams(desc, {'rewardContent': contents}) return desc
def _onPlayerOver(event): conf = hallconf.getPublicConf('match_360kp', None) if not conf or not isinstance(conf, dict): if ftlog.is_debug(): ftlog.debug('match360kp.onPlayerOver NoConf userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf) return callbackUrl = conf.get('matchResultCallbackUrl') if not callbackUrl: if ftlog.is_debug(): ftlog.debug('match360kp.onPlayerOver NoCallbackUrl userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf) return timestamp = pktimestamp.getCurrentTimestamp() params = getParamsByPlayer(event.player, timestamp) if not params: if ftlog.is_debug(): ftlog.debug('match360kp.onPlayerOver NoParams userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf) return sign = signin('MATCH_RESULT', params) params['sign'] = sign matchResult = '' reward = '' if event.rankRewards: matchResult = conf.get('resultDescReward', '') reward = event.rankRewards.desc else: matchResult = conf.get('resultDescNoReward', '') matchResult = strutil.replaceParams(matchResult, { 'match.name': event.player.inst.match.conf.name, 'rank': event.player.rank, 'reward': reward }) params['result'] = matchResult result = webpage.webgetJson(callbackUrl, datas=params, appKey=None, timeout=conf.get('timeout', 3)) if ftlog.is_debug(): ftlog.debug('match360kp.onPlayerOver userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf, 'result=', result) if not result or 'errno' in result: ftlog.warn('match360kp.onPlayerOver userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf, 'result=', result)
def buildGotAssistanceDesc(self, finalCount, sendChip): desc = hallvip.vipSystem.getGotAssistanceDesc() or '' if desc: assetKind = hallitem.itemSystem.findAssetKind(hallitem.ASSET_CHIP_KIND_ID) return strutil.replaceParams(desc, {'rewardContent': '%s%s' % (sendChip, assetKind.displayName)}) return desc