Esempio n. 1
0
    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))
Esempio n. 2
0
    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])
Esempio n. 3
0
    def sendAssetsToUser(cls,
                         gameId,
                         userId,
                         assets,
                         eventId,
                         mail=None,
                         intEventParam=0):
        '''
        :param gameId 统计用途,地主就写6
        :param assets 要发送的资产, 格式必须是:{itemId:'item:0011', count:1}
        :param eventId 事件ID,要在config/poker/map.bieventid.json中注册
        :param mail(optional) 给用户邮箱发送信息,默认不发送
        '''
        timestamp = pktimestamp.getCurrentTimestamp()
        contentitem = TYContentItem.decodeFromDict(assets)
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetKind, consumecount, finalcount = userAssets.addAsset(
            gameId, contentitem.assetKindId, contentitem.count, timestamp,
            eventId, intEventParam)
        # 通知用户道具和消息存在改变
        if assetKind.keyForChangeNotify:
            datachangenotify.sendDataChangeNotify(
                gameId, userId, [assetKind.keyForChangeNotify, 'message'])

        # 发送邮箱信息
        if mail and len(mail) > 0:
            pkmessage.sendPrivate(9999, userId, 0, mail)

        return (assetKind, consumecount, finalcount)
Esempio n. 4
0
    def sendAssetsListToUser(cls,
                             gameId,
                             userId,
                             assetList,
                             eventId,
                             mail=None,
                             intEventParam=0):
        '''
        :param gameId 统计用途,地主就写6
        :param assetList 要发送的资产, 格式必须是:[{itemId:'item:0011', count:1}, ...]
        :param eventId 事件ID,要在config/poker/map.bieventid.json中注册
        :param mail(optional) 给用户邮箱发送信息,默认不发送
        '''
        timestamp = pktimestamp.getCurrentTimestamp()
        itemList = []
        for i in xrange(0, len(assetList)):
            itemList.insert(i, TYContentItem.decodeFromDict(assetList[i]))
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetList = userAssets.sendContentItemList(gameId, itemList, 1, True,
                                                   timestamp, eventId,
                                                   intEventParam)

        # 通知用户道具和消息存在改变
        if assetList:
            datachangenotify.sendDataChangeNotify(
                gameId, userId, TYAssetUtils.getChangeDataNames(assetList))

        # 发送邮箱信息
        if mail and len(mail) > 0:
            pkmessage.sendPrivate(9999, userId, 0, mail)
Esempio n. 5
0
 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
Esempio n. 6
0
    def handleEvent(cls, event):
        try:
            gameId = 6
            userId = event.userId
            conf = dizhuconf.getActivityConf("vip_send")

            if not cls.dateCheck(gameId, userId, conf):
                cls.removeVipItems(gameId, userId, conf)
                return

            if not cls.gameCheck(userId, gameId):
                return

            vipLevel = int(
                hallvip.userVipSystem.getUserVip(userId).vipLevel.level)
            vipLevelLimit = conf.get("vip_level", 1)

            ftlog.debug('VipSend.handleEvent vipLevel=', vipLevel,
                        'vipLevelLimit=', vipLevelLimit, 'userId=', userId)

            if vipLevel >= vipLevelLimit:
                attrname = cls.getFlagAttr(conf.get('start_date',
                                                    '2015-01-01'))
                is_send = gamedata.getGameAttr(userId, gameId, attrname)

                if is_send:
                    return

                items = conf.get("item_send", [])
                timestamp = pktimestamp.getCurrentTimestamp()
                for item in items:
                    contentItem = TYContentItem.decodeFromDict(item)
                    userAssets = hallitem.itemSystem.loadUserAssets(userId)
                    assetKind, _, _ = userAssets.addAsset(
                        gameId, contentItem.assetKindId, contentItem.count,
                        timestamp, 'DIZHU_VIP_SEND', 0)
                mail = conf.get("mail", "")
                if mail:
                    pkmessage.sendPrivate(9999, userId, 0, mail)

                if assetKind.keyForChangeNotify:
                    datachangenotify.sendDataChangeNotify(
                        gameId, userId,
                        [assetKind.keyForChangeNotify, 'message'])

                gamedata.setGameAttr(userId, gameId, attrname, 1)

                ftlog.debug('vipsend vipLevel=', vipLevel, 'vipLevelLimit=',
                            vipLevelLimit, 'userId=', userId, "attrname=",
                            attrname)
        except:
            ftlog.exception()
Esempio n. 7
0
 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)
Esempio n. 8
0
    def handleEvent(cls, event):
        try:
            gameId = 6
            userId = event.userId
            if not cls.dateCheck(gameId, userId):
                return
            conf = dizhuconf.getTeHuiLiBaoConf()
            diamonds = conf.get('diamonds', 1000)
            itemId = conf.get('itemId', -1)
            if event.diamonds >= diamonds:
                itemKind = hallitem.itemSystem.findItemKind(itemId)
                if not itemKind:
                    ftlog.error('tehuilibao itemId not found itemId=', itemId)
                    return

                userBag = hallitem.itemSystem.loadUserAssets(
                    userId).getUserBag()
                count = userBag.calcTotalUnitsCount(itemKind)
                ftlog.info('tehuilibao gameId=', gameId, 'userId=', userId,
                           'itemId=', itemId, 'diamonds=', event.diamonds,
                           'itemcount=', count)
                if count > 0:
                    oldchip = userchip.getChip(userId)

                    count = userBag.consumeUnitsCountByKind(
                        gameId, itemKind, 1, pktimestamp.getCurrentTimestamp(),
                        'TE_HUI_LI_BAO', 0)
                    chip = conf.get('chip', 0)

                    userchip.incrChip(
                        userId, gameId, chip,
                        daoconst.CHIP_NOT_ENOUGH_OP_MODE_CLEAR_ZERO,
                        'TE_HUI_LI_BAO', 0, sessiondata.getClientId(userId))
                    datachangenotify.sendDataChangeNotify(
                        gameId, userId, 'chip')

                    newchip = userchip.getChip(userId)
                    pkmessage.sendPrivate(9999, userId, 0,
                                          "恭喜您获得%s金币特惠礼包奖励!" % chip)
                    datachangenotify.sendDataChangeNotify(
                        gameId, userId, 'message')
                    ftlog.info('tehuilibao gameId=', gameId, 'userId=', userId,
                               'itemId=', itemId, 'diamonds=', event.diamonds,
                               'oldchip=', oldchip, 'newchip=', newchip)
        except:
            ftlog.exception()
            ftlog.info('tehuilibao handleEvent error gameId=', event.gameId,
                       'userId=', event.userId)
Esempio n. 9
0
    def exchange(self, userId, gameId, clientId, userBag):
        if ftlog.is_debug():
            ftlog.debug('HallItemAutoExchange.exchange src:', self.itemSrc,
                        ' dst:', self.itemDst, ' ratio:', self.ratio)

        timestamp = pktimestamp.getCurrentTimestamp()
        for cond in self.conditions:
            if not cond.check(gameId, userId, clientId, timestamp):
                return

        from hall.entity import hallitem
        srcItemKind = hallitem.itemSystem.findItemKind(self.itemSrc)
        dstItemKind = hallitem.itemSystem.findItemKind(self.itemDst)

        if not srcItemKind:
            ftlog.info('HallItemAutoExchange.exchange srcItemKind not found ',
                       self.itemSrc)
            return
        if not dstItemKind:
            ftlog.info('HallItemAutoExchange.exchange dstItemKind not found ',
                       self.itemDst)
            return

        count = userBag.calcTotalUnitsCount(srcItemKind)
        if ftlog.is_debug():
            ftlog.debug('HallItemAutoExchange.exchange delItemKind:',
                        srcItemKind, ' count:', count)

        delCount = 0
        newCount = 0
        while count >= self.ratio:
            count -= self.ratio
            delCount += self.ratio
            newCount += 1

        if delCount > 0:
            ftlog.info('HallItemAutoExchange.exchange delItemKind:',
                       srcItemKind, 'delCount:', delCount, 'addItemKind:',
                       dstItemKind, 'addCount:', newCount)
            userBag.forceConsumeUnitsCountByKind(gameId, srcItemKind, delCount,
                                                 timestamp,
                                                 'ITEM_AUTO_EXCHANGE', 0)
            userBag.addItemUnitsByKind(gameId, dstItemKind, newCount,
                                       timestamp, 0, 'ITEM_AUTO_EXCHANGE', 0)
            msg = self.message.replace('{delCount}', str(delCount))
            msg = msg.replace('{newCount}', str(newCount))
            from poker.entity.biz.message import message
            message.sendPrivate(gameId, userId, 0, msg, None)
Esempio n. 10
0
    def doPutMessage(self, gameId, fromUid, toUid, mtype, msg, ismgr, scope,
                     clientIds):
        button = runhttp.getParamStr('button', None)
        button = strutil.loads(button, ignoreException=True)
        data = None
        mo = MsgPack()

        if mtype == 0 and len(msg) > 0 and toUid > 0 and gameId >= 0:
            # 发送私人消息
            # 必须参数
            # 1)msg - 消息
            # 2)toUid - 接收消息的userId
            # 3)gameId
            data = pkmessage.sendPrivate(gameId, toUid, fromUid, msg, button)
        elif mtype == 1 and len(msg) > 0 and gameId >= 0:
            # 发送站内消息到全体用户
            # 必选参数
            # msg - 消息
            # gameId
            data = pkmessage.sendGlobal(gameId, msg, button)
        elif mtype == 2 and gameId > 0 and len(msg) > 0:
            # 发送LED
            # TODO 当前Game服务为4,5,6号 , 每个服务都发送
            mo.setCmd('send_led')
            mo.setParam('msg', msg)
            mo.setParam('gameId', gameId)
            mo.setParam('ismgr', 1)
            router.sendToAll(mo, gdata.SRV_TYPE_UTIL)
            data = True
        elif mtype == 3 and gameId > 0 and toUid > 0 and len(msg) > 0:
            # 封装popwnd
            # 必选参数
            # gameId
            # toUid 接收弹窗的userId
            # msg 弹窗消息内容
            task = TodoTaskShowInfo(msg, True)
            mo = TodoTaskHelper.makeTodoTaskMsg(gameId, toUid, task)
            # 将消息发送给此人
            router.sendToUser(mo, toUid)
            data = True
        elif mtype == 4 and gameId > 0 and len(msg) > 0 and len(scope) > 0:
            mo.setCmd('send_led')
            mo.setParam('msg', msg)
            ftlog.info('send_led new msg=', msg)
            mo.setParam('gameId', gameId)
            ftlog.info('send_led new gameId=', gameId)
            mo.setParam('ismgr', ismgr)
            ftlog.info('send_led new ismgr=', ismgr)
            mo.setParam('scope', scope)
            ftlog.info('send_led new scope=', scope)
            mo.setParam('clientIds', clientIds)
            ftlog.info('send_led new clientIds=', clientIds)
            router.sendToAll(mo, gdata.SRV_TYPE_UTIL)
            data = True

        if data == None:
            mo.setError(1, 'params error')
        else:
            mo.setResult('ok', 'true')
        return mo
Esempio n. 11
0
 def sendRewards(self, player, group, rankRewards):
     '''给用户发送奖励'''
     try:
         matchlog('MatchRewardsDizhu.sendRewards', self._room.roomId,
                  group.groupId, player.userId, player.rank,
                  rankRewards.rewards)
         user_remote.addAssets(self._room.gameId, player.userId,
                               rankRewards.rewards, 'MATCH_REWARD',
                               self._room.roomId)
         if rankRewards.message:
             pkmessage.sendPrivate(self._room.gameId, player.userId, 0,
                                   rankRewards.message)
             datachangenotify.sendDataChangeNotify(self._room.gameId,
                                                   player.userId, 'message')
     except:
         ftlog.error()
Esempio n. 12
0
    def doPutMessage(self, gameId, fromUid, toUid, mtype, msg, ismgr, scope, clientIds):
        button = runhttp.getParamStr('button', None)
        button = strutil.loads(button, ignoreException=True)
        data = None
        mo = MsgPack()

        if mtype == 0 and len(msg) > 0 and toUid > 0 and gameId >= 0:
            # 发送私人消息
            # 必须参数 
            # 1)msg - 消息
            # 2)toUid - 接收消息的userId
            # 3)gameId
            data = pkmessage.sendPrivate(gameId, toUid, fromUid, msg, button)
        elif mtype == 1 and len(msg) > 0 and gameId >= 0:
            # 发送站内消息到全体用户
            # 必选参数
            # msg - 消息
            # gameId
            data = pkmessage.sendGlobal(gameId, msg, button)
        elif mtype == 2 and gameId > 0 and len(msg) > 0:
            # 发送LED
            # TODO 当前Game服务为4,5,6号 , 每个服务都发送
            mo.setCmd('send_led')
            mo.setParam('msg', msg)
            mo.setParam('gameId', gameId)
            mo.setParam('ismgr', 1)
            router.sendToAll(mo, gdata.SRV_TYPE_UTIL)
            data = True
        elif mtype == 3 and gameId > 0 and toUid > 0 and len(msg) > 0:
            # 封装popwnd
            # 必选参数
            # gameId
            # toUid 接收弹窗的userId
            # msg 弹窗消息内容
            task = TodoTaskShowInfo(msg, True)
            mo = TodoTaskHelper.makeTodoTaskMsg(gameId, toUid, task)
            # 将消息发送给此人
            router.sendToUser(mo, toUid)
            data = True
        elif mtype == 4 and gameId > 0 and len(msg) > 0 and len(scope) > 0:
            mo.setCmd('send_led')
            mo.setParam('msg', msg)
            ftlog.info('send_led new msg=', msg)
            mo.setParam('gameId', gameId)
            ftlog.info('send_led new gameId=', gameId)
            mo.setParam('ismgr', ismgr)
            ftlog.info('send_led new ismgr=', ismgr)
            mo.setParam('scope', scope)
            ftlog.info('send_led new scope=', scope)
            mo.setParam('clientIds', clientIds)
            ftlog.info('send_led new clientIds=', clientIds)
            router.sendToAll(mo, gdata.SRV_TYPE_UTIL)
            data = True

        if data == None:
            mo.setError(1, 'params error')
        else:
            mo.setResult('ok', 'true')
        return mo
Esempio n. 13
0
    def _sendRewards(self, status, task, timestamp):
        userAssets = hallitem.itemSystem.loadUserAssets(status.userId)
        assetList = userAssets.sendContent(self.gameId,
                                           task.taskKind.rewardContent, 1,
                                           True, timestamp, 'ACTIVITY_REWARD',
                                           self.intActId)
        ftlog.debug('QuweiTaskActivity._sendRewards', 'gameId=', self.gameId,
                    'actId=', self.actId, 'userId=', status.userId, '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)
Esempio n. 14
0
    def sendRewardToUser(self, gameId, userId, reward, mail):
        ftlog.debug("TYActivityFund.sendRewardToUser: userId=", userId, "reward=", reward, "mail=", mail)

        timestamp = pktimestamp.getCurrentTimestamp()
        contentItem = TYContentItem.decodeFromDict(reward)
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetKind, _, _ = userAssets.addAsset(gameId, contentItem.assetKindId,
                                                      contentItem.count, timestamp,
                                                      'DIZHU_ACT_FUND_SEND', 0)
        # 通知用户道具和消息存在改变
        if assetKind.keyForChangeNotify:
            datachangenotify.sendDataChangeNotify(gameId, userId, [assetKind.keyForChangeNotify, 'message'])

        # 发送邮箱信息
        if mail==None or len(mail) <= 0:
            return
        mail_message = strutil.replaceParams(mail, {"assets":str(reward.get('desc', ''))})
        if mail_message:
            pkmessage.sendPrivate(9999, userId, 0, mail_message)
Esempio n. 15
0
 def sendRankRewards(self, player, rankRewards):
     '''
     给用户发奖
     '''
     try:
         ftlog.info('MatchRankRewardsSenderDizhu.sendRankRewards matchId=',
                    player.matchInst.matchId, 'instId=',
                    player.matchInst.instId, 'userId=', player.userId,
                    'rank=', player.rank, 'rewards=', rankRewards.rewards)
         user_remote.addAssets(self._room.gameId, player.userId,
                               rankRewards.rewards, 'MATCH_REWARD',
                               player.matchInst.matchId)
         if rankRewards.message:
             pkmessage.sendPrivate(self._room.gameId, player.userId, 0,
                                   rankRewards.message)
             datachangenotify.sendDataChangeNotify(self._room.gameId,
                                                   player.userId, 'message')
     except:
         ftlog.error()
Esempio n. 16
0
 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)
Esempio n. 17
0
 def sendRewards(self, player, rankRewards):
     '''给用户发送奖励'''
     try:
         self._logger.info('MatchRewardsDizhu.sendRewards', 'groupId=',
                           player.group.groupId if player.group else None,
                           'score=', player.score, 'rank=', player.rank,
                           'rankRewards=', rankRewards.rewards)
         user_remote.addAssets(self._room.gameId, player.userId,
                               rankRewards.rewards, 'MATCH_REWARD',
                               self._room.roomId)
         if rankRewards.message:
             pkmessage.sendPrivate(self._room.gameId, player.userId, 0,
                                   rankRewards.message)
             datachangenotify.sendDataChangeNotify(self._room.gameId,
                                                   player.userId, 'message')
     except:
         self._logger.error('MatchRewardsDizhu.sendRewards', 'groupId=',
                            player.group.groupId if player.group else None,
                            'score=', player.score, 'rank=', player.rank,
                            'rankRewards=', rankRewards.rewards)
Esempio n. 18
0
def sendUserAssets(gameId, userId, contentItems, rankNumber):
    if ftlog.is_debug():
        ftlog.debug('replay_ranking_prize_sender.sendUserAssets',
                    'gameId=', gameId,
                    'userId=', userId,
                    'contentItems=', contentItems,
                    'rankNumber=', rankNumber)
    dictContentItems = [{'itemId': item.assetKindId, 'count': item.count} for item in contentItems]
    ok = user_remote.addAssets(gameId, userId, dictContentItems, 'REPLAY_RANK_PRIZE', 0)
    if ok:
        prizeContent = hallitem.buildContentsString(contentItems, True)
        mail = strutil.replaceParams(getReplayRankingPrizeSentMail(), {'prizeContent':prizeContent, 'rankNumber': rankNumber})
        if mail:
            pkmessage.sendPrivate(9999, userId, 0, mail)
    else:
        ftlog.warn('replay_ranking_prize_sender.sendUserAssets: send error',
                    'gameId=', gameId,
                    'userId=', userId,
                    'contentItems=', contentItems)
    return ok
Esempio n. 19
0
    def sendReward(self, userId, reward, mail):
        # 给幸运玩家发彩蛋
        # TODO: 需不需要发邮件?
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetKind, count, _ = userAssets.addAsset(
            DIZHU_GAMEID, reward.get('itemId'), reward.get('count'),
            pktimestamp.getCurrentTimestamp(), 'ACTIVITY_REWARD',
            self.intActId)
        item = {}
        item['name'] = assetKind.displayName
        item['pic'] = assetKind.pic
        item['count'] = count
        from hall.entity.todotask import TodoTaskHelper, TodoTaskShowRewards
        rewardTodotask = TodoTaskShowRewards([item])
        if ftlog.is_debug():
            ftlog.debug('SkyEggActivity send user ', userId, ' "todotask:"',
                        rewardTodotask)

        TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, rewardTodotask)

        pkmessage.sendPrivate(HALL_GAMEID, userId, 0, mail)
Esempio n. 20
0
    def _send_rewards(cls, uid, task_id, task_kind, multi_award):
        reward_content = task_kind.reward_content
        if multi_award:
            reward_content = task_kind.multi_reward_content
        userAssets = hallitem.itemSystem.loadUserAssets(uid)
        assetList = userAssets.sendContent(DIZHU_GAMEID,
                                           reward_content, 1, True,
                                           int(time.time()), 'TASK_REWARD',
                                           int(task_id))
        ftlog.debug('UserTaskData._send_rewards', 'task_id=', task_id,
                    'userId=', uid, 'assets=',
                    [(atup[0].kindId, atup[1]) for atup in assetList])
        changed = TYAssetUtils.getChangeDataNames(assetList)
        datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, uid, changed)

        if task_kind.reward_mail:
            contents = TYAssetUtils.buildContentsString(assetList)
            mail = strutil.replaceParams(task_kind.reward_mail,
                                         {'rewardContent': contents})
            pkmessage.sendPrivate(HALL_GAMEID, uid, 0, mail)

        return reward_content
Esempio n. 21
0
    def _sendPrizeIfNeed(self, gameId, userId, clientId, product, prizeContent,
                         timestamp):
        # 加载活动数据
        status = self.loadStatus(userId, timestamp)
        if self._isOverLimit(status, timestamp, 1):
            if ftlog.is_debug():
                ftlog.debug('BuySendPrize._sendPrizeIfNeed OverLimit gameId=',
                            gameId, 'userId=', userId, 'clientId=', clientId,
                            'productId=', product.productId, 'count=',
                            status.limitRecord.count, 'limitCount=',
                            self._limitCount)
            return

        status.limitRecord.count += 1
        status.limitRecord.lastSendTimestamp = timestamp
        self.saveStatus(status)

        # 检查是否已经发过奖励
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetList = userAssets.sendContent(gameId, prizeContent, 1, True,
                                           timestamp, 'ACTIVITY_REWARD',
                                           self.intActId)

        changed = TYAssetUtils.getChangeDataNames(assetList)
        changed.add('promotion_loc')
        datachangenotify.sendDataChangeNotify(gameId, userId, changed)

        if self._mail:
            contents = TYAssetUtils.buildContentsString(assetList)
            mail = strutil.replaceParams(self._mail,
                                         {'rewardContent': contents})
            pkmessage.sendPrivate(HALL_GAMEID, userId, 0, mail)

        ftlog.info('BuySendPrize._sendPrizeIfNeed gameId=', gameId, 'userId=',
                   userId, 'clientId=', clientId, 'productId=',
                   product.productId, 'buyType=', product.buyType, 'actId=',
                   self.actId, 'intActId=', self.intActId, 'sendAssets=',
                   [(at[0].kindId, at[1]) for at in assetList], 'timestamp=',
                   timestamp, 'count=', status.limitRecord.count)
Esempio n. 22
0
 def _sendAuthReawrd(cls, userId):
     """发送认证奖励"""
     assets = cls.getConf('auth_reward')
     if ftlog.is_debug():
         ftlog.debug('PlayerControl._sendAuthReawrd', 'userId=', userId,
                     'assets=', assets)
     if assets:
         contentItems = [{
             'itemId': assets.get('itemId'),
             'count': assets.get('count')
         }]
         if user_remote.addAssets(DIZHU_GAMEID, userId, contentItems,
                                  'ERDAYI_AUTH_REWARD', 0):
             ftlog.info('PlayerControl._sendAuthReawrd Succ', 'userId=',
                        userId, 'assets=', assets)
             rewardDesc = hallitem.buildContent(assets.get('itemId'),
                                                assets.get('count'), False)
             mail = strutil.replaceParams(cls.getConf('auth_reward_mail'),
                                          {'reward_desc': rewardDesc})
             pkmessage.sendPrivate(9999, userId, 0, mail)
             cls.sendPopTip(userId, mail)
         else:
             ftlog.warn('PlayerControl._sendAuthReawrd Fail', 'userId=',
                        userId, 'assets=', assets)
Esempio n. 23
0
def complementByVip(userId, gameId, clientId):
    if not checkChargeDate(userId):
        ftlog.info("complementByVip|charge|surpass|30days", userId)
        return
    vip_complement = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement")
    vip_complement_max = configure.getGameJson(HALL_GAMEID, "misc").get("vip_complement_max")
    vipL = getVipLevel(userId)
    vipKey = "vip_" + str(vipL)
    ftlog.info("complementByVip|enter", userId, gameId, vipL, vipKey, vip_complement, clientId)
    if vipKey in vip_complement:
        once = vip_complement[vipKey]
        max = vip_complement_max[vipKey]
        coin = userdata.getAttr(userId, 'chip')
        vipcominfo = gamedata.getGameAttr(userId, HALL_GAMEID, 'vip_complement')
        if not vipcominfo:
            vipcom = 0
        else:
            vipcominfo = json.loads(vipcominfo)
            vipLevel = vipcominfo['vipLevel']
            if vipL != vipLevel:
                vipcom = 0
                ftlog.info("complementByVip|vip|up", userId, vipL, vipLevel)
            else:
                vipcom = vipcominfo['vipcom']

        mostchip = max - vipcom
        ftlog.info("complementByVip|go", userId, gameId, clientId, once, max, coin, vipcom, mostchip, vipcominfo)
        if vipcom >= max:
            vip_complement_msg = gamedata.getGameAttr(userId, HALL_GAMEID, 'vip_complement_msg')
            if not vip_complement_msg:
                vip_complement_msg = 0
            else:
                if int(vip_complement_msg) >= 3:
                    return
            gamedata.setGameAttr(userId, HALL_GAMEID, 'vip_complement_msg', int(vip_complement_msg) + 1)
            ftlog.info("complementByVip|reach|max", userId ,gameId, clientId, vipcom, max)
            msg = u"今日您的VIP金币补足权益已停止,充值可恢复权益,充值越多,额度越高。客服电话:4008-098-000"
            infoTodoTask = TodoTaskShowInfo(msg, True)
            TodoTaskHelper.sendTodoTask(gameId, userId, infoTodoTask)

            return

        if coin >= once:
            ftlog.info("complementByVip|once|is|ok", userId, coin, once)
            return
        else:
            delta = once - coin
            if delta > mostchip:
                delta = mostchip
            final = addChip(userId, gameId, clientId, delta)
            if final:
                gamedata.setGameAttr(userId, HALL_GAMEID, 'vip_complement',
                                     json.dumps({'vipLevel': vipL, 'vipcom': vipcom + delta}))
                mail = "您当前是VIP%d,今日首次登录为您补足到%d金币"%(vipL, final)
                pkmessage.sendPrivate(9999, userId, 0, mail)

                bireport.reportGameEvent('HALL_VIPCOMPLEMENT', userId, gameId, 0, 0, 0, 0, 0, 0,
                                         [vipL, delta, -delta, max - vipcom - delta, final],
                                         clientId,
                                         0, 0)
                ftlog.info("complementByVip|", userId, vipL, delta, final)
Esempio n. 24
0
 def sendMailToUser(cls, userId, mail):
     '''
     给用户发送邮箱信息
     '''
     pkmessage.sendPrivate(9999, userId, 0, mail)
def _sendReward(gameId, activityId, quizResult):
    if not quizResult in ('l', 'm', 'r'):
        ftlog.warn('hotfix_match_quiz._sendReward BadQuizResult gameId=', gameId,
                   'activityId=', activityId, 'quizResult=', quizResult)
        return

    actConf = _getActivityConf(activityId)
    if not actConf:
        ftlog.warn('hotfix_match_quiz._sendReward NotActConf gameId=', gameId,
                   'activityId=', activityId, 'quizResult=', quizResult)
        return

    serverConf = actConf.get('server_config')
    if not serverConf:
        ftlog.warn('hotfix_match_quiz._sendReward NotActServerConf gameId=', gameId,
                   'activityId=', activityId, 'quizResult=', quizResult)
        return

    oddsMap = {
        'l': serverConf['leftOdds'],
        'm': serverConf['middleOdds'],
        'r': serverConf['rightOdds'],
    }

    odds = oddsMap.get(quizResult)
    gameId = int(serverConf['gameId'])
    intActId = int(serverConf['intActId'])
    chipAssetId = 'user:chip'  # serverConf['chipAssetId']

    ftlog.info('hotfix_match_quiz._sendReward sending... gameId=', gameId,
               'activityId=', activityId,
               'quizResult=', quizResult,
               'intActId=', intActId,
               'chipAssetId=', chipAssetId,
               'odds=', odds,
               'oddsMap=', oddsMap)

    totalBets = {'l': 0, 'm': 0, 'r': 0}
    totalReward = 0
    needTotalReward = 0
    userIds = _getActUsers(gameId, activityId)

    for userId in userIds:
        #         class UserQuizStatus(object):
        #     def __init__(self, userId):
        #         self._userId = userId
        #         self._betMap = {}
        #         self._totalBet = 0
        status = activity_match_quiz.loadUserQuizStatus(gameId, userId, activityId)
        if not status:
            ftlog.error('hotfix_match_quiz._sendReward NotUserStatus gameId=', gameId,
                        'activityId=', activityId,
                        'quizResult=', quizResult,
                        'intActId=', intActId,
                        'chipAssetId=', chipAssetId,
                        'odds=', odds,
                        'oddsMap=', oddsMap,
                        'userId=', userId,
                        'status=', None)
            status = UserQuizStatus(userId)

        betAmount = status.getBet(quizResult, 0)

        totalBets['l'] += status.getBet('l', 0)
        totalBets['m'] += status.getBet('m', 0)
        totalBets['r'] += status.getBet('r', 0)

        quizResultTitleMap = {'l': serverConf['leftTitle'] + '获胜', 'm': '平局', 'r': serverConf['rightTitle'] + '获胜'}

        if betAmount > 0:
            rewardCount = int(betAmount * odds * 1000)
            needTotalReward += rewardCount
            addState = 2
            if _setAlreadySentReward(gameId, activityId, userId):
                try:
                    # 给用户发奖
                    addOk = user_remote.addAssets(gameId, userId, [{'itemId': chipAssetId, 'count': rewardCount}],
                                                  'ACTIVITY_CONSUME', intActId)

                    msg = '恭喜您在欧洲杯竞猜活动%sVS%s场次押注%s钻石猜中%s,赔率为%s,获得%s金币奖励。' % (serverConf['leftTitle'],
                                                                             serverConf['rightTitle'],
                                                                             int(betAmount),
                                                                             quizResultTitleMap[quizResult],
                                                                             odds,
                                                                             rewardCount)
                    pkmessage.sendPrivate(HALL_GAMEID, userId, 0, msg)
                except:
                    ftlog.error('hotfix_match_quiz._sendReward RewardUser gameId=', gameId,
                                'activityId=', activityId,
                                'quizResult=', quizResult,
                                'intActId=', intActId,
                                'chipAssetId=', chipAssetId,
                                'odds=', odds,
                                'oddsMap=', oddsMap,
                                'userId=', userId,
                                'rewardCount=', rewardCount,
                                'status=', status.toDict())
                    addOk = False
                addState = 1 if addOk else 0
                if addOk:
                    totalReward += rewardCount

            ftlog.info('hotfix_match_quiz._sendReward RewardUser gameId=', gameId,
                       'activityId=', activityId,
                       'quizResult=', quizResult,
                       'intActId=', intActId,
                       'chipAssetId=', chipAssetId,
                       'odds=', odds,
                       'oddsMap=', oddsMap,
                       'userId=', userId,
                       'rewardCount=', rewardCount,
                       'addState=', addState,
                       'status=', status.toDict())
        else:
            ftlog.info('hotfix_match_quiz._sendReward NotRewardUser gameId=', gameId,
                       'activityId=', activityId,
                       'quizResult=', quizResult,
                       'intActId=', intActId,
                       'chipAssetId=', chipAssetId,
                       'odds=', odds,
                       'oddsMap=', oddsMap,
                       'userId=', userId,
                       'status=', status.toDict())

    ftlog.info('hotfix_match_quiz._sendReward sent gameId=', gameId,
               'activityId=', activityId,
               'quizResult=', quizResult,
               'intActId=', intActId,
               'chipAssetId=', chipAssetId,
               'odds=', odds,
               'oddsMap=', oddsMap,
               'totalBets=', totalBets,
               'totalReward=', totalReward,
               'needTotalReward=', needTotalReward)
    return {'actId': activityId, 'intActId': intActId,
            'chipAssetId': chipAssetId, 'quizResult': quizResult,
            'totalBets': totalBets,
            'totalReward': totalReward,
            'odds': odds,
            'oddsMap': oddsMap,
            'needTotalReward': needTotalReward,
            }
Esempio n. 26
0
def sendPrivateMessage(userId, msg):
    """ 发送个人消息
    """
    if not isinstance(msg, unicode):
        msg = unicode(msg)
    message.sendPrivate(9999, userId, 0, msg)
Esempio n. 27
0
def sendMessage(gameId, userId, fromUid, msg):
    pkmessage.sendPrivate(HALL_GAMEID, userId, fromUid, msg)
    datachangenotify.sendDataChangeNotify(gameId, userId, 'message')
Esempio n. 28
0
def sendMessage(gameId, userId, fromUid, msg):
    pkmessage.sendPrivate(HALL_GAMEID, userId, fromUid, msg)
    datachangenotify.sendDataChangeNotify(gameId, userId, 'message')
Esempio n. 29
0
    def handleEvent(cls, event):
        conf = dizhuconf.getActivityConf('month_checkin_gift')
        monthDayCount = calendar.monthrange(event.checkinDate.year,
                                            event.checkinDate.month)[1]
        giftDayCount = conf.get('giftDayCount', -1)
        if giftDayCount <= 0:
            giftDayCount = monthDayCount
        giftDayCount = min(giftDayCount, monthDayCount)

        clientId = sessiondata.getClientId(event.userId)
        hallGameId = strutil.getGameIdFromHallClientId(clientId)

        if hallGameId != DIZHU_GAMEID:
            return

        if ftlog.is_debug():
            ftlog.debug('MonthCheckinGift.handleEvent userId=',
                        event.userId, 'gameId=', event.gameId, 'eventType=',
                        type(event), 'checkinDate=', event.checkinDate,
                        'allCheckinCount=', event.status.allCheckinCount,
                        'giftDayCount=', giftDayCount, 'monthDayCount=',
                        monthDayCount)

        giftContent = None
        try:
            if not Tool.checkNow(conf.get('datetime_start'),
                                 conf.get('datetime_end')):
                ftlog.debug('MonthCheckinGift.handleEvent outOfDate userId=',
                            event.userId, 'gameId=', event.gameId,
                            'eventType=', type(event), 'checkinDate=',
                            event.checkinDate, 'allCheckinCount=',
                            event.status.allCheckinCount, 'giftDayCount=',
                            giftDayCount, 'monthDayCount=', monthDayCount)
                return

            giftContent = TYContentRegister.decodeFromDict(
                conf.get('giftContent'))
        except:
            ftlog.error('MonthCheckinGift.handleEvent userId=',
                        event.userId, 'gameId=', event.gameId, 'eventType=',
                        type(event), 'checkinDate=', event.checkinDate,
                        'allCheckinCount=', event.status.allCheckinCount,
                        'giftDayCount=', giftDayCount, 'monthDayCount=',
                        monthDayCount)
            return

        if event.status.allCheckinCount >= giftDayCount:
            assetList = None
            if giftContent:
                userAssets = hallitem.itemSystem.loadUserAssets(event.userId)
                assetList = userAssets.sendContent(
                    DIZHU_GAMEID, giftContent, 1, True,
                    pktimestamp.getCurrentTimestamp(), 'ACTIVITY_REWARD',
                    cls.ACTIVITY_ID)
                changed = TYAssetUtils.getChangeDataNames(assetList)
                mail = conf.get('mail', '')
                if mail:
                    gotContent = giftContent.desc if giftContent.desc else TYAssetUtils.buildContentsString(
                        assetList)
                    mail = strutil.replaceParams(mail,
                                                 {'gotContent': gotContent})
                    message.sendPrivate(HALL_GAMEID, event.userId, 0, mail)
                    changed.add('message')
                datachangenotify.sendDataChangeNotify(HALL_GAMEID,
                                                      event.userId, changed)

            ftlog.info('MonthCheckinGift.statics sendGift userId=',
                       event.userId, 'gameId=', event.gameId, 'eventType=',
                       type(event), 'checkinDate=', event.checkinDate,
                       'allCheckinCount=', event.status.allCheckinCount,
                       'giftDayCount=', giftDayCount, 'monthDayCount=',
                       monthDayCount, 'rewards=',
                       [(a[0].kindId, a[1])
                        for a in assetList] if assetList else None)
Esempio n. 30
0
    def _do_complain(self, userId, gameId, clientId, roomId0, tableId0,
                     gameNum, otherPlayerId1, otherPlayerId2):
        mo = MsgPack()
        mo.setCmd('complain')
        roomId = roomId0
        roomId0 = gdata.getBigRoomId(roomId0)
        complainConf, tips = dizhuconf.getComplainInfo(roomId0)
        if not complainConf:
            mo.setError(1, '本房间不支持投诉')
            router.sendToUser(mo, userId)
            return mo

        comMoney = complainConf['fee']
        currentUserChip = userchip.getChip(userId)
        if complainConf['fee'] <= (currentUserChip):
            trueDelta, _chip = userchip.incrChip(
                userId, gameId, -complainConf['fee'],
                daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                'GAME_COMPLAIN_INSURANCE', roomId0, clientId)
            # 金币不足支付举报的,返回错误。现改为'金币不足扔可继续举报'所以注释掉
            if trueDelta != -complainConf['fee']:
                comMoney = trueDelta
                # mo.setError(2, tips.get("error", ""))
                # router.sendToUser(mo, userId)
                # return mo
        else:
            comMoney = 0
        if ftlog.is_debug():
            ftlog.debug('AccountTcpHandler.doComplain userId=', userId,
                        'userchip=', currentUserChip, 'fee=',
                        complainConf['fee'], 'comMoney=', comMoney)

        complain_time = pktimestamp.getCurrentTimestamp()
        params = {
            'act': 'api.getComplaintDetailInfo',
            'gameid': gameId,
            'playerId': userId,
            'comtTime': complain_time,
            'roomId': roomId0,
            'PlayerOneId': otherPlayerId1,
            'PlayerTwoId': otherPlayerId2,
            'tableId': tableId0,
            'gameSign': gameNum,
            'comMoney': complainConf['fee']
        }
        try:
            roundNum = int(gameNum.split('_')[-1])
        except Exception:
            roundNum = 0

        try:
            ret, complainCodec = normal_table_room_remote.getComplainContent(
                gameId, userId, roomId, tableId0, gameNum)
            if ret != 0:
                mo.setError(3, complainCodec)
                router.sendToUser(mo, userId)
                if comMoney > 0:
                    userchip.incrChip(userId, gameId, comMoney,
                                      daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                                      'GAME_COMPLAIN_INSURANCE', roomId0,
                                      clientId)
                    datachangenotify.sendDataChangeNotify(
                        gameId, userId, 'chip')
                ftlog.error('doComplain userId=', userId, 'gameId=', gameId,
                            'clientId=', clientId, 'err=', complainCodec)
            else:
                mo.setResult('success', {
                    "code": 1,
                    'info': tips.get("succ", "")
                })
                pkmessage.sendPrivate(9999, userId, 0, tips.get("succ", ""))
                router.sendToUser(mo, userId)
                datachangenotify.sendDataChangeNotify(gameId, userId,
                                                      ['chip', 'message'])
                bireport.reportGameEvent(
                    'GAME_COMPLAIN_INSURANCE', userId, DIZHU_GAMEID,
                    params['roomId'], params['tableId'], roundNum,
                    params['comMoney'], 0, 0, [
                        params['PlayerOneId'], params['PlayerTwoId'],
                        params['comtTime'],
                        strutil.dumps(complainCodec)
                    ], clientId, 0, 0)
                ftlog.info('report_bi_game_event',
                           'eventId=GAME_COMPLAIN_INSURANCE', 'userId=',
                           userId, 'gameId=', DIZHU_GAMEID, 'params=', params)
        except Exception, e:
            mo.setError(4, '操作失败')
            router.sendToUser(mo, userId)
            if comMoney > 0:
                userchip.incrChip(userId, gameId, comMoney,
                                  daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                                  'GAME_COMPLAIN_INSURANCE', roomId0, clientId)
                datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
            ftlog.error('doComplain userId=', userId, 'gameId=', gameId,
                        'clientId=', clientId, 'err=', e.message)
Esempio n. 31
0
    def withdraw(cls, userId):
        '''
        玩家提现
        * 必须玩家认证->绑定银行卡,之后才能提现
        '''
        ftlog.info('PlayerControl.withdraw:params', 'userId=', userId)

        # 1.获取玩家认证信息,获取身份证号码
        realinfo = PlayerData.getRealInfo(userId)
        if not realinfo:
            info = cls.getConf('withdraw_need_realinfo_errinfo')
            cls.sendPopTip(userId, info)
            return cls.makeResponse(userId, ErrorEnum.ERR_NO_REALINFO, info,
                                    True)
        idNo = realinfo.get('idNo')
        if not idNo:
            info = cls.getConf('withdraw_need_realinfo_errinfo')
            ftlog.info('PlayerControl.withdraw:Erdayi3rdInterface userId=',
                       userId, 'errInfo=', info,
                       'err= withdraw_need_realinfo_errinfo')
            return cls.makeResponse(userId, ErrorEnum.ERR_NO_BIND_IDNUMBER,
                                    info)

        # 2.查看玩家是否绑定银行卡
        bankinfo = PlayerData.getBankInfo(userId)
        if not bankinfo:
            info = cls.getConf('withdraw_need_bankinfo_errinfo')
            cls.sendPopTip(userId, info)
            ftlog.info('PlayerControl.withdraw:Erdayi3rdInterface userId=',
                       userId, 'errInfo=', info,
                       'err= withdraw_need_bankinfo_errinfo')
            return cls.makeResponse(userId, ErrorEnum.ERR_NO_REALINFO, info,
                                    True)

        # 2.先查看玩家余额是否足够
        wallet_resp = cls.getWalletInfo(userId)
        wallet_resp_code = wallet_resp.getResult('code')
        withdraw_money_lowat = cls.getConf('withdraw_money_lowat')
        if wallet_resp_code != ErrorEnum.ERR_OK:
            ftlog.info('PlayerControl.withdraw:Erdayi3rdInterface userId=',
                       userId, 'wallet_resp_code=', wallet_resp_code,
                       'withdraw_money_lowat=', withdraw_money_lowat, 'err=',
                       'withdraw_money_lowat')
            return cls.makeResponse(userId, wallet_resp_code,
                                    wallet_resp.getResult('info'))

        walletinfo = wallet_resp.getResult('wallet', {})
        if withdraw_money_lowat > float(walletinfo.get('money', 0)):
            ftlog.info('PlayerControl.withdraw:Erdayi3rdInterface userId=',
                       userId, 'walletinfo=', walletinfo,
                       'withdraw_money_lowat=', withdraw_money_lowat, 'err=',
                       'withdraw_money_lowat')
            return cls.makeResponse(userId,
                                    ErrorEnum.ERR_WITHDRAW_BALANCE_NOT_ENOUGH)

        # 3.查看上次领取时间,领取存在24小时的冷却时间
        waittime = cls.getConf('withdraw_wait', 24 * 60 * 60)
        withdrawinfo = PlayerData.getWithdraw(userId)
        if withdrawinfo:
            laststamp = withdrawinfo.get('laststamp', 0)
            if time.time() - laststamp < waittime:
                ftlog.info('PlayerControl.withdraw:Erdayi3rdInterface userId=',
                           userId, 'withdrawinfo=', withdrawinfo, 'laststamp=',
                           laststamp, 'waitTime=', waittime, 'err=',
                           'withdraw must cooling 24hours')
                return cls.makeResponse(userId,
                                        ErrorEnum.ERR_WITHDRAW_PROCESSING)

        # 3.第三方接口
        response3rd = Erdayi3rdInterface.playerBonousWithdraw(userId, idNo)
        resp_code = response3rd.get('resp_code')
        resp_msg = response3rd.get('resp_msg')
        act_money = response3rd.get('act_money', '0.0')
        ftlog.info('PlayerControl.withdraw:Erdayi3rdInterface', 'userId=',
                   userId, 'resp_code=', resp_code, 'resp_msg=', resp_msg,
                   'act_money=', act_money, 'response3rd=', response3rd)

        # 4.提现成功受理
        if resp_code == ErrorEnum.ERR_OK:
            # 记录提现成功受理的时间
            withdrawinfo = {'laststamp': time.time()}
            PlayerData.setWithdraw(userId, withdrawinfo)

            # 发送提现成功受理的tip
            tip = cls.getConf('withdraw_accept_tip')
            cls.sendPopTip(userId, tip)
            pkmessage.sendPrivate(9999, userId, 0, tip)

            response = cls.makeResponse(userId)
            response.setResult('money', act_money)
            return response
        else:
            tip = cls.getConf('withdraw_failed_tip')
            cls.sendPopTip(userId, tip)
            pkmessage.sendPrivate(9999, userId, 0, tip)

            return cls.makeResponse(userId, resp_code, resp_msg, True)
Esempio n. 32
0
def _sendReward(gameId, activityId, quizResult):
    if not quizResult in ('l', 'm', 'r'):
        ftlog.warn('hotfix_match_quiz._sendReward BadQuizResult gameId=', gameId,
                   'activityId=', activityId, 'quizResult=', quizResult)
        return
    
    actConf = _getActivityConf(activityId)
    if not actConf:
        ftlog.warn('hotfix_match_quiz._sendReward NotActConf gameId=', gameId,
                   'activityId=', activityId, 'quizResult=', quizResult)
        return
    
    serverConf = actConf.get('server_config')
    if not serverConf:
        ftlog.warn('hotfix_match_quiz._sendReward NotActServerConf gameId=', gameId,
                   'activityId=', activityId, 'quizResult=', quizResult)
        return
    
    oddsMap = {
        'l':serverConf['leftOdds'],
        'm':serverConf['middleOdds'],
        'r':serverConf['rightOdds'],
    }
    
    odds = oddsMap.get(quizResult)
    gameId = int(serverConf['gameId'])
    intActId = int(serverConf['intActId'])
    chipAssetId = 'user:chip' #serverConf['chipAssetId']
    
    ftlog.info('hotfix_match_quiz._sendReward sending... gameId=', gameId,
               'activityId=', activityId,
               'quizResult=', quizResult,
               'intActId=', intActId,
               'chipAssetId=', chipAssetId,
               'odds=', odds,
               'oddsMap=', oddsMap)
    
    totalBets = {'l':0, 'm':0, 'r':0}
    totalReward = 0
    needTotalReward = 0
    userIds = _getActUsers(gameId, activityId)
    
    for userId in userIds:
#         class UserQuizStatus(object):
#     def __init__(self, userId):
#         self._userId = userId
#         self._betMap = {}
#         self._totalBet = 0
        status = activity_match_quiz.loadUserQuizStatus(gameId, userId, activityId)
        if not status:
            ftlog.error('hotfix_match_quiz._sendReward NotUserStatus gameId=', gameId,
                        'activityId=', activityId,
                        'quizResult=', quizResult,
                        'intActId=', intActId,
                        'chipAssetId=', chipAssetId,
                        'odds=', odds,
                        'oddsMap=', oddsMap,
                        'userId=', userId,
                        'status=', None)
            status = UserQuizStatus(userId)
            
        betAmount = status.getBet(quizResult, 0)
        
        totalBets['l'] += status.getBet('l', 0)
        totalBets['m'] += status.getBet('m', 0)
        totalBets['r'] += status.getBet('r', 0)
        
        quizResultTitleMap = {'l':serverConf['leftTitle']+'获胜', 'm':'平局', 'r':serverConf['rightTitle']+'获胜'}
        
        if betAmount > 0:
            rewardCount = int(math.ceil(betAmount * odds))
            needTotalReward += rewardCount
            addState = 2
            if _setAlreadySentReward(gameId, activityId, userId):
                try:
                    # 给用户发奖
                    addOk = user_remote.addAssets(gameId, userId, [{'itemId':chipAssetId, 'count':rewardCount}],
                                                  'ACTIVITY_CONSUME', intActId)
                    
                    msg = '恭喜您在%s活动%sVS%s场次押注%s金币猜中%s,赔率为%s,获得%s金币奖励。' % (actConf['name'],
                                                                                serverConf['leftTitle'],
                                                                               serverConf['rightTitle'],
                                                                               int(betAmount),
                                                                               quizResultTitleMap[quizResult],
                                                                               odds,
                                                                               rewardCount)
                    pkmessage.sendPrivate(HALL_GAMEID, userId, 0, msg)
                except:
                    ftlog.error('hotfix_match_quiz._sendReward RewardUser gameId=', gameId,
                                'activityId=', activityId,
                                'quizResult=', quizResult,
                                'intActId=', intActId,
                                'chipAssetId=', chipAssetId,
                                'odds=', odds,
                                'oddsMap=', oddsMap,
                                'userId=', userId,
                                'rewardCount=', rewardCount,
                                'status=', status.toDict())
                    addOk = False
                addState = 1 if addOk else 0
                if addOk:
                    totalReward += rewardCount

            ftlog.info('hotfix_match_quiz._sendReward RewardUser gameId=', gameId,
                       'activityId=', activityId,
                       'quizResult=', quizResult,
                       'intActId=', intActId,
                       'chipAssetId=', chipAssetId,
                       'odds=', odds,
                       'oddsMap=', oddsMap,
                       'userId=', userId,
                       'rewardCount=', rewardCount,
                       'addState=', addState,
                       'status=', status.toDict())
        else:
            ftlog.info('hotfix_match_quiz._sendReward NotRewardUser gameId=', gameId,
                       'activityId=', activityId,
                       'quizResult=', quizResult,
                       'intActId=', intActId,
                       'chipAssetId=', chipAssetId,
                       'odds=', odds,
                       'oddsMap=', oddsMap,
                       'userId=', userId,
                       'status=', status.toDict())

    ftlog.info('hotfix_match_quiz._sendReward sent gameId=', gameId,
               'activityId=', activityId,
               'quizResult=', quizResult,
               'intActId=', intActId,
               'chipAssetId=', chipAssetId,
               'odds=', odds,
               'oddsMap=', oddsMap,
               'totalBets=', totalBets,
               'totalReward=', totalReward,
               'needTotalReward=', needTotalReward)
    return {'actId':activityId, 'intActId':intActId,
            'chipAssetId':chipAssetId, 'quizResult':quizResult,
            'totalBets':totalBets,
            'totalReward':totalReward,
            'odds':odds,
            'oddsMap':oddsMap,
            'needTotalReward':needTotalReward,
            }
Esempio n. 33
0
def sendPrivateMessage(userId, msg):
    """ 发送个人消息
    """
    if not isinstance(msg, unicode):
        msg = unicode(msg)
    message.sendPrivate(9999, userId, 0, msg)
Esempio n. 34
0
    def sendRewardToUser(self, userId, countChipLeft, countChipRight,
                         resultState, activityGameId, activityId, issueNumber):
        ftlog.debug('BetGuess.sendRewardToUser', 'userId=', userId)

        userModel = ActivityUserModel.loadModel(userId, activityGameId,
                                                activityId)
        userModelItem = userModel.findItemByIssueNumber(issueNumber)

        # 若玩家没有下注的记录,但是有记录的userid,此处可能存在问题
        if not userModelItem:
            ftlog.warn(
                'BetGuess.sendRewardToUser: userModel issueNumber not found',
                'userId=', userId, 'activityGameId', activityGameId,
                'activityId', activityId, 'issueNumber', issueNumber)
            return 0

        # 已经发送过了
        if userModelItem.isPrizeSent:
            ftlog.warn('BetGuess.sendRewardToUser: user issueNumber has sent',
                       'userId=', userId, 'activityGameId', activityGameId,
                       'activityId', activityId, 'issueNumber', issueNumber)
            return 0

        # 若未发奖,则返回0
        if resultState == ActivityModel.RESULT_STATE_NONE:
            return 0

        # 单期的配置
        issueConf = copy.deepcopy(
            self.issueCalculator.getCurrentIssueConf(issueNumber))
        ftlog.debug('BetGuess.sendRewardToUser:issueConf=', issueConf)
        if not issueConf:
            return 0

        # 抽水比例
        bankerPumping = issueConf.get('bankerPumping', 0)
        # 奖池金额
        betPoolChip = int(
            (countChipLeft + countChipRight) * (1 - bankerPumping))
        # 左赔率
        leftBetOdds = betPoolChip / countChipLeft if countChipLeft > 0 else 0
        # 右赔率
        rightBetOdds = betPoolChip / countChipRight if countChipRight > 0 else 0

        prizeNumber = 0  # 本期活动,赢取金额
        issueWinSideName = None  # 本期活动,胜利一侧名称
        issueFinalOdds = 0  # 本期活动,胜利一侧最终赔率
        issueWinBetNumber = 0  # 本期活动,胜利一侧下注额
        if resultState == ActivityModel.RESULT_STATE_LEFT:
            prizeNumber = int(userModelItem.leftBetValue * leftBetOdds)
            issueWinSideName = issueConf['leftSide']['displayName']
            issueFinalOdds = leftBetOdds
            issueWinBetNumber = userModelItem.leftBetValue
        elif resultState == ActivityModel.RESULT_STATE_RIGHT:
            prizeNumber = int(userModelItem.rightBetValue * rightBetOdds)
            issueWinSideName = issueConf['rightSide']['displayName']
            issueFinalOdds = rightBetOdds
            issueWinBetNumber = userModelItem.rightBetValue

        # 发放金币奖励
        if prizeNumber <= 0:
            # 记录是否发奖
            userModelItem.isPrizeSent = True
            userModel.save()
            return prizeNumber

        clientId = sessiondata.getClientId(userId)
        trueDelta, _ = userchip.incrChip(userId, activityGameId, prizeNumber,
                                         daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                                         'ACT_BETGUESS_CHIP', 0, clientId)
        datachangenotify.sendDataChangeNotify(activityGameId, userId, 'chip')
        ftlog.debug('BetGuess.sendRewardToUser:'******'userId=', userId,
                    'trueDelta=', trueDelta)
        if trueDelta != prizeNumber:
            return 0

        # 发送玩家系统邮件
        mail = Tool.dictGet(self._clientConf, 'config.server.mail')
        if mail:
            issueDatetime = Tool.datetimeFromString(issueNumber)
            mailMessage = strutil.replaceParams(
                mail, {
                    'issueMonth': issueDatetime.month,
                    'issueDay': issueDatetime.day,
                    'issueLeftSideName': issueConf['leftSide']['displayName'],
                    'issueRightSideName':
                    issueConf['rightSide']['displayName'],
                    'issueWinBetNumber': issueWinBetNumber,
                    'issueWinSideName': issueWinSideName,
                    'issueFinalOdds': float(issueFinalOdds * 100) / 100,
                    'issuePrizeChipNumber': prizeNumber
                })
            pkmessage.sendPrivate(9999, userId, 0, mailMessage)

        # 记录是否发奖
        userModelItem.isPrizeSent = True
        userModel.save()

        ftlog.info('BetGuess.sendRewardToUser:'******'userId=', userId,
                   'activityGameId=', activityGameId, 'activityId=',
                   activityId, 'issueNumber=', issueNumber, 'prizeNumber=',
                   prizeNumber, 'resultState=', resultState)

        return prizeNumber
Esempio n. 35
0
    def handleEvent(cls, event):
        try:
            gameId = 6
            userId = event.userId
            conf = dizhuconf.getActivityConf("dashi_send")

            # 检查日期在活动日期内
            if not cls.dateCheck(gameId, userId, conf):
                cls.removeDashiItems(gameId, userId, conf)
                return

            # 检查用户当前在地主游戏中
            if not cls.gameCheck(userId, gameId):
                return

            # 获得大师分段位
            dashi_score = gamedata.getGameAttr(userId, gameId,
                                               'skillscore') or 1
            dashi_level = skillscore.get_skill_level(dashi_score)

            # 获取配置中大师分的段位限制
            dashi_level_limit = conf.get("dashi_level", 1)

            if dashi_level < dashi_level_limit:
                return

            # 如果已经发送过大师登陆礼包,则不发送
            attrname = cls.getFlagAttr(conf.get('start_date', '2015-01-01'))
            is_send = gamedata.getGameAttr(userId, gameId, attrname)
            if is_send:
                return

            # 道具生成时间
            timestamp = pktimestamp.getCurrentTimestamp()

            # 要发送的道具列表
            items = conf.get("item_send", [])
            for item in items:
                contentItem = TYContentItem.decodeFromDict(item)
                userAssets = hallitem.itemSystem.loadUserAssets(userId)
                assetKind, _, _ = userAssets.addAsset(gameId,
                                                      contentItem.assetKindId,
                                                      contentItem.count,
                                                      timestamp,
                                                      'DIZHU_DASHI_SEND', 0)

            # 发送邮箱信息
            mail_message = conf.get("mail", "")
            if mail_message:
                pkmessage.sendPrivate(9999, userId, 0, mail_message)

            # 通知用户道具和消息存在改变
            if assetKind.keyForChangeNotify:
                datachangenotify.sendDataChangeNotify(
                    gameId, userId, [assetKind.keyForChangeNotify, 'message'])

            # 成功发送大师登陆礼包,记录下来,避免重复发送
            gamedata.setGameAttr(userId, gameId, attrname, 1)

            ftlog.debug('dashisend dashi_level=', dashi_level,
                        'dashi_level_limit=', dashi_level_limit, 'userId=',
                        userId)

        except:
            ftlog.exception()