Exemplo n.º 1
0
 def parseResponse(self):
     ignorePattern = PatternManager.getOrCompilePattern("traderIgnoringUs")
     if ignorePattern.search(self.responseText):
         raise Error.Error("That player has you on his/her ignore list.", Error.USER_IS_IGNORING)
     
     roninPattern = PatternManager.getOrCompilePattern("traderIsInRoninHC")
     if roninPattern.search(self.responseText):
         raise Error.Error("That player is in Ronin or HC and cannot receive trade offers.", Error.USER_IN_HARDCORE_RONIN)
     
     itemsPattern = PatternManager.getOrCompilePattern("traderHasNotEnoughItems")
     if itemsPattern.search(self.responseText):
         raise Error.Error("You don't have enough of one or more of the items you're trying to trade.", Error.NOT_ENOUGH_ITEMS)
     
     meatPattern = PatternManager.getOrCompilePattern("traderHasNotEnoughMeat")
     if meatPattern.search(self.responseText):
         raise Error.Error("You don't have as much meat as you're trying to trade.", Error.NOT_ENOUGH_MEAT)
     
     chatBannedPattern = PatternManager.getOrCompilePattern("traderBannedFromChat")
     if chatBannedPattern.search(self.responseText):
         raise Error.Error("You are banned from chat and consequently cannot trade.", Error.BANNED_FROM_CHAT)
     
     successPattern = PatternManager.getOrCompilePattern("tradeSentSuccessfully")
     if successPattern.search(self.responseText):
         Report.trace("request", "Trade offer sent successfully.")
     else:
         raise Error.Error("Other error sending trade offer.", Error.ERROR)
Exemplo n.º 2
0
    def parseResponse(self):
        # Check for errors.
        effectRemovedPattern = PatternManager.getOrCompilePattern(
            'effectRemoved')
        if effectRemovedPattern.search(self.responseText):
            return

        youDontHaveThatEffectPattern = PatternManager.getOrCompilePattern(
            'youDontHaveThatEffect')
        if youDontHaveThatEffectPattern.search(self.responseText):
            raise Error.Error(
                "Unable to remove effect. The user does not have that effect.",
                Error.EFFECT_NOT_FOUND)

        youDontHaveSGEEAPattern = PatternManager.getOrCompilePattern(
            'youDontHaveSGEEA')
        if youDontHaveSGEEAPattern.search(self.responseText):
            raise Error.Error(
                "Unable to remove effect. You do not have a soft green echo eyedrop antidote.",
                Error.ITEM_NOT_FOUND)

        Report.error("request",
                     "Unknown error occurred when trying to remove an effect")
        Report.error("request", self.responseText)
        raise Error.Error(
            "Unknown error occurred when trying to remove an effect.",
            Error.REQUEST_FATAL)
Exemplo n.º 3
0
    def parseResponse(self):
        noMeatPattern = PatternManager.getOrCompilePattern(
            'traderHasNotEnoughMeat')
        if noMeatPattern.search(self.responseText):
            raise Error.Error(
                "You don't have as much meat as you're promising.",
                Error.NOT_ENOUGH_MEAT)

        noItemsPattern = PatternManager.getOrCompilePattern(
            'traderHasNotEnoughItems')
        if noItemsPattern.search(self.responseText):
            raise Error.Error(
                "You don't have as many items as you're promising.",
                Error.NOT_ENOUGH_ITEMS)

        #Not testing for an offer being cancelled due to a bug in KoL - space reserved

        successPattern = PatternManager.getOrCompilePattern(
            'tradeResponseSentSuccessfully')
        if successPattern.search(self.responseText):
            Report.trace(
                "request", "Response to trade " +
                str(self.requestData['whichoffer']) + ' sent successfully.')
        else:
            raise Error.Error(
                "Unknown error sending response to trade " +
                str(self.requestData['whichoffer']), Error.REQUEST_GENERIC)
Exemplo n.º 4
0
 def parseResponse(self):
     successPattern = PatternManager.getOrCompilePattern(
         'tradeCancelledSuccessfully')
     if successPattern.search(self.responseText):
         Report.trace(
             'request',
             "Trade offer " + str(self.requestData['whichoffer']) +
             " cancelled successfully.")
     else:
         raise Error.Error(
             "Unknown error declining trade offer for trade " +
             str(self.requestData['whichoffer']), Error.REQUEST_GENERIC)
Exemplo n.º 5
0
 def parseResponse(self):
     # First parse for errors
     notEnoughPattern = PatternManager.getOrCompilePattern("dontHaveEnoughOfItem")
     if notEnoughPattern.search(self.responseText):
         raise Error.Error("You don't have that many of that item.", Error.ITEM_NOT_FOUND)
     
     dontHaveItemPattern = PatternManager.getOrCompilePattern("dontHaveThatItem")
     if dontHaveItemPattern.search(self.responseText):
         raise Error.Error("You don't have that item.", Error.ITEM_NOT_FOUND)
         
     # Check if responseText matches the success pattern. If not, raise error.
     itemAddedSuccessfully = PatternManager.getOrCompilePattern("itemAddedSuccessfully")
     if itemAddedSuccessfully.search(self.responseText):
          Report.trace('request', 'Item appears to have been added')
     else:
         raise Error.Error("Something went wrong with the adding.", Error.ITEM_NOT_FOUND)
Exemplo n.º 6
0
    def parseResponse(self):
        # First parse for errors
        notEnoughPattern = PatternManager.getOrCompilePattern(
            "dontHaveThatManyInStore")
        if notEnoughPattern.search(self.responseText):
            raise Error.Error("You either don't have that item, or not enough",
                              Error.ITEM_NOT_FOUND)

        # Check if responseText matches the success pattern. If not, raise error.
        itemTakenSuccessfully = PatternManager.getOrCompilePattern(
            "itemTakenSuccessfully")
        if itemTakenSuccessfully.search(self.responseText):
            Report.trace('request', 'Item appears to have been taken')
        else:
            raise Error.Error(
                "Something went wrong with the taking of the item.",
                Error.ITEM_NOT_FOUND)
Exemplo n.º 7
0
def discoverMissingItems(session):
    from pykollib.request.InventoryRequest import InventoryRequest
    from pykollib.request.ItemInformationRequest import ItemInformationRequest
    invRequest = InventoryRequest(session)
    invRequest.ignoreItemDatabase = True
    invData = invRequest.doRequest()
    for item in invData["items"]:
        if item["id"] not in __itemsById:
            try:
                itemRequest = ItemInformationRequest(session, item["id"])
                itemData = itemRequest.doRequest()
                item = itemData["item"]
                addItem(item)
                Report.trace("itemdatabase",
                             "Discovered new item: %s" % item["name"])

                context = {"item": item}
                FilterManager.executeFiltersForEvent("discoveredNewItem",
                                                     context,
                                                     session=session,
                                                     item=item)
            except:
                pass
Exemplo n.º 8
0
    def parseResponse(self):
        hardcoreRoninPattern = PatternManager.getOrCompilePattern(
            'userInHardcoreRonin')
        ignoringPattern = PatternManager.getOrCompilePattern('userIgnoringUs')
        notEnoughItemsPattern = PatternManager.getOrCompilePattern(
            'notEnoughItemsToSend')
        sentMessagePattern = PatternManager.getOrCompilePattern('messageSent')
        trendyPattern = PatternManager.getOrCompilePattern(
            'kmailNotSentUserTrendy')
        ignoringUserPattern = PatternManager.getOrCompilePattern(
            'weAreIgnoringUser')

        if hardcoreRoninPattern.search(self.responseText):
            raise Error.Error(
                "Unable to send items or meat. User is in hardcore or ronin.",
                Error.USER_IN_HARDCORE_RONIN)
        elif ignoringPattern.search(self.responseText):
            raise Error.Error("Unable to send message. User is ignoring us.",
                              Error.USER_IS_IGNORING)
        elif notEnoughItemsPattern.search(self.responseText):
            raise Error.Error(
                "You don't have enough of one of the items you're trying to send.",
                Error.ITEM_NOT_FOUND)
        elif trendyPattern.search(self.responseText):
            raise Error.Error(
                "Unable to send items or meat. User is too trendy.",
                Error.USER_IN_HARDCORE_RONIN)
        elif ignoringUserPattern.search(self.responseText):
            raise Error.Error(
                "Unable to send message. We are ignoring the other player.",
                Error.USER_IS_IGNORING)
        elif sentMessagePattern.search(self.responseText) == None:
            Report.alert(
                "system",
                "Received unknown response when attempting to send a message.")
            Report.alert("system", self.responseText)
            raise Error.Error("Unknown error", Error.REQUEST_FATAL)
Exemplo n.º 9
0
    def doRequest(self):
        """
        Performs the request. This method will ensure that nightly maintenance 
        is not occurring.  In addition, this method will throw a NOT_LOGGED_IN 
        error if the session thinks it is logged in when it actually isn't. 
        """

        Report.debug("request", "Requesting {0}".format(self.url))

        self.response = self.session.opener.open(self.url, self.requestData)
        self.responseText = self.response.text

        Report.debug("request", "Received response: {0}".format(self.url))
        Report.debug("request", "Response Text: {0}".format(self.responseText))

        if self.response.url.find("/maint.php") >= 0:
            self.session.isConnected = False
            raise Error.Error("Nightly maintenance in progress.",
                              Error.NIGHTLY_MAINTENANCE)

        if self.response.url.find("/login.php") >= 0:
            if self.session.isConnected:
                self.session.isConnected = False
                raise Error.Error("You are no longer connected to the server.",
                                  Error.NOT_LOGGED_IN)

        # Allow for classes that extend GenericRequest to parse all of the data someone
        # would need from the response and then to place this data in self.responseData.
        self.responseData = {}
        if self.skipParseResponse == False and hasattr(self, "parseResponse"):
            self.parseResponse()
            if len(self.responseData) > 0:
                Report.debug(
                    "request",
                    "Parsed response data: {0}".format(self.responseData))

        return self.responseData
Exemplo n.º 10
0
def init():
    """
    Initializes the QkillDatabase. This method should be called before the
    database is ever accessed as it ensures that the database is populated
    with all of the data it needs.
    """
    global __isInitialized
    if __isInitialized == True:
        return

    Report.trace("questdatabase", "Initializing the quest database.")
    returnCode = FilterManager.executeFiltersForEvent(
        "preInitializeQuestDatabase")
    if returnCode == FilterManager.FINISHED:
        Report.trace("questdatabase", "Quest database initialized.")
        __isInitialized = True
        return

    for quest in Quests.quests:
        addQuest(quest)

    FilterManager.executeFiltersForEvent("postInitializeQuestDatabase")
    __isInitialized = True
    Report.trace("questdatabase", "Quest database initialized.")
Exemplo n.º 11
0
def init():
    """
    Initializes the SkillDatabase. This method should be called before the
    database is ever accessed as it ensures that the database is populated
    with all of the data it needs.
    """
    global __isInitialized
    if __isInitialized == True:
        return

    Report.trace("skilldatabase", "Initializing the skill database.")
    returnCode = FilterManager.executeFiltersForEvent(
        "preInitializeSkillDatabase")
    if returnCode == FilterManager.FINISHED:
        Report.trace("skilldatabase", "Skill database initialized.")
        __isInitialized = True
        return

    for skill in Skills.skills:
        addSkill(skill)

    FilterManager.executeFiltersForEvent("postInitializeSkillDatabase")
    __isInitialized = True
    Report.trace("skilldatabase", "Skill database initialized.")
Exemplo n.º 12
0
def init():
    """
    Initializes the ItemDatabase. This method should be called before the
    database is ever accessed as it ensures that the database is populated
    with all of the data it needs.
    """
    global __isInitialized
    if __isInitialized == True:
        return

    Report.trace("itemdatabase", "Initializing the item database.")
    returnCode = FilterManager.executeFiltersForEvent(
        "preInitializeItemDatabase")
    if returnCode == FilterManager.FINISHED:
        Report.trace("itemdatabase", "Item database initialized.")
        __isInitialized = True
        return

    for item in Items.items:
        addItem(item)

    FilterManager.executeFiltersForEvent("postInitializeItemDatabase")
    __isInitialized = True
    Report.trace("itemdatabase", "Item database initialized.")
Exemplo n.º 13
0
 def parseResponse(self):
     """
     Returns a dict in which 'results' references an array of dicts.  If the 
     search included items only, each dict would have the following item keys:
         descId (always)
         id (always)
         image (always)
         name (always)
     and sometime, depending on the kind of item,
         adventuresGained
         autosell
         drunkenness
         fullness
         isBounty
         isCandy
         isCombatReusable
         isCombatUsable
         isMultiUsable
         isReusable
         isSphere
         isUsable
         isUsableOnOthers
         isZappable
         moxieGained
         muscleGained
         mysticalityGained
         npcPrice
         npcStoreId
         numPackageItems
         plural
         power
         quality
         requiredMoxie
         requiredMuscle
         requiredMysticality
         spleen
         type
     If the search included shops, the dicts would have the following
     additional keys:
         hitLimit (if the item's limit has been hit by the session character)
         limit (if the item is limited per day)
         price
         quantity
         storeId
         storeName
     """
     items = []
     itemMatchPattern = self.getPattern('mallItemSearchResult')
     itemDetailsPattern = self.getPattern('mallItemSearchDetails')
     itemHeaderPattern = self.getPattern('mallItemHeader')
     if self.justItems:
         for itemMatch in itemHeaderPattern.finditer(self.responseText):
             itemId = int(itemMatch.group(1))
             try:
                 item = ItemDatabase.getItemFromId(itemId)
                 items.append(item)
             except Error.Error, inst:
                 if inst.code == Error.ITEM_NOT_FOUND:
                     Report.info(
                         "itemdatabase",
                         "Unrecognized item found in mall search: {0}".
                         format(itemId), inst)
                 else:
                     raise inst
Exemplo n.º 14
0
             item["storeId"] = int(match.group('storeId'))
             storeName = match.group('storeName').replace('<br>', ' ')
             item['storeName'] = self.HTML_PARSER.unescape(storeName)
             item["quantity"] = int(
                 match.group('quantity').replace(',', ''))
             limit = match.group('limit').replace(',', '')
             if len(limit) > 0:
                 limit = int(limit)
                 item["limit"] = limit
             if matchText.find('limited"') >= 0:
                 item["hitLimit"] = True
             items.append(item)
         except Error.Error, inst:
             if inst.code == Error.ITEM_NOT_FOUND:
                 Report.info(
                     "itemdatabase",
                     "Unrecognized item found in mall search: {0}".
                     format(itemId), inst)
             else:
                 raise inst
 nextlink = self.searchNamedPattern('nextLink')
 if nextlink is not None:
     # There's more.  We have to collect the info from subsequent pages.
     nextRequest = MallItemSearchRequest(
         session=self.session,
         searchQuery=self.searchQuery,
         category=self.category,
         noLimits=self.noLimits,
         maxPrice=self.maxPrice,
         numResults=self.numResults,
         sortBy=self.sortBy,
         sortResultsBy=self.sortResultsBy,
Exemplo n.º 15
0
def parseChatMessages(text, isIncoming):
    """
    This function parses chats passed to it. The chats are assumed to come from a GetChatMessagesRequest.
    Returns a list of chats, each of which is a dictionary possibly containing the following keys:
        "type" : What kind of chat this is.  Current possible values are
            "channel"
            "listen"
            "listen:start"
            "listen:stop"
            "normal"
            "emote"
            "private"
            "system message"
            "mod warning"
            "mod announcement"
            "notification:kmail"
            "notification:carnival"
            "unknown"
        "currentChannel" : The current channel as indicated when sending a /c, /s, or /l request
        "otherChannels" : The other channels being listened to as indicated by a /l request
        "description" : The description of the current channel as indicated when sending a /c or /s request
        "channel" : The channel this chat message was posted from
        "userId" : The user id number of the user sending this chat message
        "userName" : The user name of the user sending this chat message
        "text" : The text of the current chat message
        "isMultiline" : A flag indicating whether this is a multiline message such as a haiku or a message from the Gothy Effect
    """
    
    # Prepare the patterns.
    htmlCommentPattern = PatternManager.getOrCompilePattern("htmlComment")
    htmlTagPattern = PatternManager.getOrCompilePattern("htmlTag")
    channelPattern = PatternManager.getOrCompilePattern("chatChannel")
    chatPattern = PatternManager.getOrCompilePattern("chatMessage")
    emotePattern = PatternManager.getOrCompilePattern("chatEmote")
    privateChatPattern = PatternManager.getOrCompilePattern("privateChat")
    newKmailPattern = PatternManager.getOrCompilePattern("chatNewKmailNotification")
    linkPattern = PatternManager.getOrCompilePattern("chatLink")
    chatWhoPattern = PatternManager.getOrCompilePattern("chatWhoResponse")
    linkedPlayerPattern = PatternManager.getOrCompilePattern("chatLinkedPlayer")
    multiLinePattern = PatternManager.getOrCompilePattern("chatMultiLineStart")
    multiEmotePattern = PatternManager.getOrCompilePattern("chatMultiLineEmote")
    playerLoggedOnPattern = PatternManager.getOrCompilePattern("chatPlayerLoggedOn")
    playerLoggedOffPattern = PatternManager.getOrCompilePattern("chatPlayerLoggedOff")
    newCarnivalPattern = PatternManager.getOrCompilePattern("chatCarnival")

    # Get the chat messages.
    chats = []

    # Check for responses to outgoing chat commands.
    if isIncoming == False:
        outPrivatePattern = PatternManager.getOrCompilePattern("outgoingPrivate")
        chatNewChannelPattern = PatternManager.getOrCompilePattern("newChatChannel")
        chatListenPattern = PatternManager.getOrCompilePattern("chatListenResponse")
        chatListenStartPattern = PatternManager.getOrCompilePattern("chatStartListen")
        chatListenStopPattern = PatternManager.getOrCompilePattern("chatStopListen")

        # See if it is an outgoing private message
        match = outPrivatePattern.search(text)
        if match:
            chat = {}
            chat["type"] = "private"
            chat["userName"] = match.group(2)
            chat["userId"] = int(match.group(1))
            chat["text"] = match.group(3).strip()
            text = text[:match.start()] + text[match.end():]
            chats.append(chat)

        # See if the user changed chat channels through /c or /s
        match = chatNewChannelPattern.search(text)
        if match:
            chat = {}
            chat["type"] = "channel"
            chat["currentChannel"] = match.group(1)
            chat["description"] = match.group(2).replace('<br>','')
            text = text[:match.start()] + text[match.end():]
            chats.append(chat)

        # See if it is a /l response
        match = chatListenPattern.search(text)
        if match:
            chat = {}
            listen = match.group()
            currentPattern = PatternManager.getOrCompilePattern("chatListenCurrent")
            otherPattern = PatternManager.getOrCompilePattern("chatListenOthers")
            chat["type"] = "listen"
            chat["currentChannel"] = currentPattern.search(listen).group(1)
            other = []
            for channel in otherPattern.finditer(listen):
                other.append(channel.group(1))
            chat["otherChannels"] = other
            text = text[:match.start()] + text[match.end():]
            chats.append(chat)

        # See if it is a /l <channel> response to start listening to a channel
        match = chatListenStartPattern.search(text)
        if match:
            chat = {}
            chat["type"] = "listen:start"
            chat["channel"] = match.group(1)
            text = text[:match.start()] + text[match.end():]
            chats.append(chat)
        
        # See if it is a /l <channel> response to stop listening to a channel
        match = chatListenStopPattern.search(text)
        if match:
            chat = {}
            chat["type"] = "listen:stop"
            chat["channel"] = match.group(1)
            text = text[:match.start()] + text[match.end():]
            chats.append(chat)

    lines = text.split("<br>")

    for line in lines:
        line = htmlCommentPattern.sub('', line)
        line = line.strip()
        if len(line) == 0:
            continue

        # Mod Announcements and Mod Warnings leave leading </font> tags at the beginning of the next message
        # This method will remove them and also skip the line if that is all there is
        if line[:7] == "</font>":
            if len(line) == 7:
                continue
            else:
                line = line[7:].strip()

        # System Announcements leave leading </b></font> tags at the beginning of the next message
        # This method will remove them and also skip the line if that is all there is
        if line[:11] == "</b></font>":
            if len(line) == 11:
                continue
            else:
                line = line[11:].strip()

        chat = {}
        parsedChat = False

        # See if this message was posted to a different channel.
        match = channelPattern.search(line)
        if match:
            chat["channel"] = match.group(1)
            line = line[len(match.group(0)):]

        # See if this was a normal chat message.
        if parsedChat == False:
            match = chatPattern.search(line)
            if match:
                chat["type"] = "normal"
                chat["userId"] = int(match.group(1))
                chat["userName"] = match.group(2)

                # Check for special announcements
                if chat["userId"] == -1 or chat["userName"] == "System Message":
                    chat["type"] = "system message"
                elif chat["userName"] == "Mod Warning":
                    chat["type"] = "mod warning"
                elif chat["userName"] == "Mod Announcement":
                    chat["type"] = "mod announcement"

                chat["text"] = match.group(3).strip()
                parsedChat = True

        # See if this was an emote.
        if parsedChat == False:
            match = emotePattern.search(line)
            if match:
                chat["type"] = "emote"
                chat["userId"] = int(match.group(1))
                chat["userName"] = match.group(2)
                chat["text"] = match.group(3).strip()
                parsedChat = True

        if isIncoming == True:
            # See if a user logged in.
            if parsedChat == False:
                match = playerLoggedOnPattern.search(line)
                if match:
                    chat["type"] = "logonNotification"
                    chat["userId"] = int(match.group(1))
                    chat["userName"] = match.group(2)
                    parsedChat = True

            # See if a user logged out.
            if parsedChat == False:
                match = playerLoggedOffPattern.search(line)
                if match:
                    chat["type"] = "logoffNotification"
                    chat["userId"] = int(match.group(1))
                    chat["userName"] = match.group(2)
                    parsedChat = True

            # See if this was a private message.
            if parsedChat == False:
                match = privateChatPattern.search(line)
                if match:
                    chat["type"] = "private"
                    chat["userId"] = int(match.group(1))
                    chat["userName"] = match.group(2)
                    chat["text"] = match.group(3).strip()
                    parsedChat = True

            # See if this is a new kmail notification.
            if parsedChat == False:
                match = newKmailPattern.search(line)
                if match:
                    chat["type"] = "notification:kmail"
                    chat["userId"] = int(match.group(1))
                    chat["userName"] = match.group(2)
                    parsedChat = True

            # See if this is the start of a multi-line message (Gothy or Haiku)
            if parsedChat == False:
                match = multiLinePattern.search(line)
                if match:
                    chat["type"] = "normal"
                    chat["userId"] = int(match.group(1))
                    chat["userName"] = match.group(2)
                    chat["isMultiline"] = True
                    chat["text"] = ""
                    parsedChat = True

            #See if this is a carnival notification
            if parsedChat == False:
                match = newCarnivalPattern.search(line)
                if match:
                    chat["type"] = "notification:carnival"
                    chat["userName"] = match.group(2)
                    chat["userId"] = int(match.group(1))
                    parsedChat = True

            # See if this is the start of a multi-line emote (Gothy or Haiku)
            # I've seen a Haiku emote, don't know if Gothy will trigger for it
            if parsedChat == False:
                match = multiEmotePattern.search(line)
                if match:
                    chat["type"] = "emote"
                    chat["userId"] = int(match.group(1))
                    chat["userName"] = match.group(2)
                    chat["isMultiline"] = True
                    chat["text"] = ""
                    parsedChat = True

        else:
            # See if this is a /who response.
            if parsedChat == False:
                if chatWhoPattern.search(line):
                    chat["type"] = "who"
                    chat["users"] = []
                    chatWhoPersonPattern = PatternManager.getOrCompilePattern("chatWhoPerson")
                    for match in chatWhoPersonPattern.finditer(line):
                        userClass = match.group(1)
                        userId = match.group(2)
                        userName = match.group(3)
                        userInfo = {"userId" : userId, "userName" : userName}
                        if userClass == "afk":
                            userInfo["isAway"] = True
                        chat["users"].append(userInfo)
                    parsedChat = True

        if parsedChat and "text" in chat:
            chat["text"] = cleanChatText(chat["text"])

        # Handle unrecognized chat messages.
        if parsedChat == False:
            # If the last chat was flagged as starting a multiline
            if len(chats) > 0 and "isMultiline" in chats[-1]:
                if chats[-1]["isMultiline"] == True:
                    if len(chats[-1]["text"]) > 0:
                        chats[-1]["text"] += "\n"
                    line = line.replace('<Br>','\n')
                    cleanLine = cleanChatText(line)
                    cleanLine = cleanLine.replace('&nbsp;','').strip()

                    chats[-1]["text"] += cleanLine

                    continue

            # If the last chat was flagged as a System or Mod Announcement, skip past the trailing tags
            elif len(chats) > 0:
                if "type" in chats[-1] and chats[-1]["type"] in ["system message", "mod warning", "mod announcement"]:
                    if line == "</b></font>":
                        continue

            # Any other case we aren't prepared to handle
            Report.error("bot", "Unknown message.  ResponseText = %s" % text)
            chat["type"] = "unknown"
            chat["text"] = StringUtils.htmlEntityDecode(line)

        chats.append(chat)

    return chats
Exemplo n.º 16
0
    def parseResponse(self):
        entries = []
        entryPattern = PatternManager.getOrCompilePattern('clanLogEntry')
        for entryMatch in entryPattern.finditer(self.responseText):
            entry = {}
            date = entryMatch.group('date')
            entry['date'] = datetime.strptime(date, "%m/%d/%y, %I:%M%p")
            entry['userId'] = int(entryMatch.group('userId'))
            entry['userName'] = entryMatch.group('userName')
            action = entryMatch.group('action')
            foundAction = False
            
            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogFax')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_FAX
                    entry['monster'] = match.group('monsterName')

            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogAttack')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_ATTACK
                    entry['clanName'] = match.group('clanName')

            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogWhitelistAdd')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_WHITELISTED_PLAYER
                    entry['targetUserName'] = match.group('userName')
                    entry['targetUserId'] = int(match.group('userId'))

            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogPlayerJoinedAnotherClan')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_JOINED_ANOTHER_CLAN

            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogPlayerJoinedClanWhitelist')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_WHITELISTED_IN

            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogStashItemAdd')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_STASH_ADD
                    entry['itemName'] = match.group('itemName')
                    entry['quantity'] = int(match.group('quantity').replace(',', ''))

            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogStashItemRemove')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_STASH_REMOVE
                    entry['itemName'] = match.group('itemName')
                    entry['quantity'] = int(match.group('quantity').replace(',', ''))

            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogMeatSpentArmy')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_MEAT_SPENT_ARMY
                    entry['meat'] = int(match.group('meat').replace(',', ''))

            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogChangedRank')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_CHANGED_RANK
                    entry['targetUserName'] = match.group('userName')
                    entry['targetUserId'] = int(match.group('userId'))

            if foundAction == False:
                pattern = PatternManager.getOrCompilePattern('clanLogChangedTitle')
                match = pattern.match(action)
                if match:
                    foundAction = True
                    entry['type'] = CLAN_LOG_CHANGED_RANK
                    entry['targetUserName'] = match.group('userName')
                    entry['targetUserId'] = int(match.group('userId'))
                    entry['clanTitle'] = match.group('clanTitle')

            if foundAction == False:
                Report.error("request", "Unknown clan log action: %s" % action)
                entry['type'] = CLAN_LOG_UNKNOWN
                entry['action'] = action

            entries.append(entry)

        self.responseData["entries"] = entries