def botProcessChat(context, **kwargs): returnCode = FilterManager.CONTINUE chat = kwargs["chat"] if chat["type"] == "private": if BotUtils.canUserPerformAction(chat["userId"], "execute", kwargs["bot"]): doAction = False executeAll = False wordList = chat["text"].split() if len(wordList) > 0: if wordList[0].lower() == "execute": doAction = True elif wordList[0].lower() == "executeall": doAction = True executeAll = True if doAction: returnCode = FilterManager.FINISHED del wordList[0] command = " ".join(wordList) if executeAll: for bot in BotManager._bots: if bot.session != None and bot.session.isConnected and hasattr(bot.session, "chatManager"): try: bot.sendChatMessage(command) except AttributeError, inst: Report.error("chat", "Could not execute command: %s" % command, inst) else: kwargs["bot"].sendChatMessage(command)
def parseResponse(self): items = [] itemMatchPattern = PatternManager.getOrCompilePattern('mallItemSearchResult') itemDetailsPattern = PatternManager.getOrCompilePattern('mallItemSearchDetails') for itemMatch in itemMatchPattern.finditer(self.responseText): matchText = itemMatch.group(1) match = itemDetailsPattern.search(matchText) itemId = int(match.group('itemId')) try: item = ItemDatabase.getItemFromId(itemId) item["price"] = int(match.group('price').replace(',', '')) item["storeId"] = int(match.group('storeId')) item["storeName"] = match.group('storeName').replace('<br>', ' ') 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: %s" % itemId, inst) else: raise inst
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 DontHaveEffectError( "Unable to remove effect. The user does not have that effect.") youDontHaveSGEEAPattern = PatternManager.getOrCompilePattern( 'youDontHaveSGEEA') if youDontHaveSGEEAPattern.search(self.responseText): raise NotEnoughItemsError( "Unable to remove effect. You do not have a soft green echo eyedrop antidote." ) Report.error("request", "Unknown error occurred when trying to remove an effect") Report.error("request", self.responseText) raise RequestError( "Unknown error occurred when trying to remove an effect.")
def parseResponse(self): items = [] itemMatchPattern = PatternManager.getOrCompilePattern( 'mallItemSearchResult') itemDetailsPattern = PatternManager.getOrCompilePattern( 'mallItemSearchDetails') for itemMatch in itemMatchPattern.finditer(self.responseText): matchText = itemMatch.group(1) match = itemDetailsPattern.search(matchText) itemId = int(match.group('itemId')) try: item = ItemDatabase.getItemFromId(itemId, self.session) item["price"] = int(match.group('price').replace(',', '')) item["storeId"] = int(match.group('storeId')) item["storeName"] = match.group('storeName').replace( '<br>', ' ') 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 ItemNotFoundError, inst: Report.info( "itemdatabase", "Unrecognized item found in mall search: %s" % itemId, inst)
def discoverMissingItems(session): global __isLoaded if not __isLoaded: loadItemsFromFile() newInformation = False from kol.request.InventoryRequest import InventoryRequest from kol.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) newInformation = True except: pass if newInformation or not __isLoaded: saveItemsToFile() __isLoaded = True
def do_GET(self): if not self.path.count('/newchatmessages.php?') and not self.path.count('/submitnewchat.php?'): Report.debug("relay", "GET: %s" % self.path) relayServer = self.server.relayServer # Check to see if we should terminate the RelayServer. if self.path == '/terminate': relayServer.haltEvent.set() self.wfile.write('Server Stopping...') return # Redirect empty URL to main.html. if self.path == '/': self.path = '/main.html' # Execute the server request. dReq = DynamicRequest(relayServer.session, self.path[1:]) dReq.doRequest() # The following line is for the sake of some js scripts (mainly chat). page = dReq.responseText.replace("window.location.hostname", 'window.location.hostname+":"+window.location.port') # Add server shutdown in compact mode. if self.path == '/topmenu.php': page = page.replace('<option value="logout.php">Log Out</option>','<option value="terminate">Stop Server</option>') self.wfile.write(page)
def discoverMissingItems(session): global __isLoaded if not __isLoaded: loadItemsFromFile() newInformation = False from kol.request.InventoryRequest import InventoryRequest from kol.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) newInformation = True except: pass if newInformation or not __isLoaded: saveItemsToFile() __isLoaded = True
def getItemFromId(itemId, session=None): "Returns information about an item given its ID." global __dbChanged if not __isInitialized: init() try: return __itemsById[itemId].copy() except KeyError: try: if session is None: raise KeyError() from kol.request.ItemInformationRequest import ItemInformationRequest r = ItemInformationRequest(session, itemId) result = r.doRequest() item = result["item"] addItem(item) Report.trace("itemdatabase", "Discovered new item: %s" % item["name"]) context = {"item": item} FilterManager.executeFiltersForEvent("discoveredNewItem", context, session=session, item=item) __dbChanged = True return item except (KeyError, Error.Error): raise Error.Error("Item ID %s is unknown." % itemId, Error.ITEM_NOT_FOUND)
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)
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)
def uneffect(bot, id): r = UneffectRequest(bot.session, id) try: r.doRequest() resp = "Effect successfully removed!" except Error: resp = "Unable to remove effect for unknown reason." Report.info("bot", resp)
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)
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)
def doRequest(self): """ Performs the request. This method will ensure that nightly maintenance is not occuring. In addition, this method will throw a NOT_LOGGED_IN error if the session thinks it is logged in when it actually isn't. All specific KoL requests should inherit from this class. """ Report.debug("request", "Requesting %s" % self.url) self.response = self.session.opener.open(self.url, self.requestData) self.responseText = self.response.text Report.debug("request", "Received response: %s" % self.url) Report.debug("request", "Response Text: %s" % 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: %s" % self.responseData) return self.responseData
def parseResponse(self): # Get the timestamp we should send to the server next time we make a request. lastSeenPattern = PatternManager.getOrCompilePattern("chatLastSeen") match = lastSeenPattern.search(self.responseText) self.responseData["lastSeen"] = match.group(1) # Parse the chat messages. text = self.responseText[:self.responseText.find('<!--lastseen')] self.responseData["chatMessages"] = ChatUtils.parseMessages(self.responseText, True) # Trace out unknown messages. for chat in self.responseData["chatMessages"]: if chat["type"] == "unknown": Report.trace("chat", "Unable to parse chat message: %s" % chat)
def doRequest(self): """ Performs the request. This method will ensure that nightly maintenance is not occuring. In addition, this method will throw a NotLoggedInError if the session thinks it is logged in when it actually isn't. All specific KoL requests should inherit from this class. """ Report.debug("request", "Requesting %s" % self.url) self.response = self.session.opener.open(self.url, urllib.urlencode(self.requestData)) self.responseText = self.response.read() Report.debug("request", "Received response: %s" % self.url) Report.debug("request", "Response Text: %s" % self.responseText) if self.response.geturl().find("/maint.php") >= 0: self.session.isConnected = False raise NightlyMaintenanceError("Nightly maintenance in progress.") if self.response.geturl().find("/login.php") >= 0: if self.session.isConnected: self.session.isConnected = False raise NotLoggedInError("You are no longer connected to the server.") # 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 "parseResponse" in self.__class__.__dict__: self.parseResponse() if len(self.responseData) > 0: Report.debug("request", "Parsed response data: %s" % self.responseData) return self.responseData
def botProcessKmail(context, **kwargs): returnCode = FilterManager.CONTINUE message = kwargs["kmail"] bot = kwargs["bot"] cmd = BotUtils.getKmailCommand(message) if cmd == "uneffect": arr = message["text"].split() items = message["items"] # Get the effect ID. if len(arr) < 2: raise Error.Error( "You must specify the ID of the effect to remove.", Error.BOT_REQUEST) try: effectId = int(arr[1]) except ValueError: raise Error.Error("Unable to remove effect. Invalid effect ID.", Error.BOT_REQUEST) # Ensure the user sent a SGEEA. if len(items) != 1: raise Error.Error("Please include just a SGEEA in your kmail.", Error.BOT_REQUEST) sgeea = ItemDatabase.getItemFromName( "soft green echo eyedrop antidote") if items[0]["id"] != sgeea["id"] or items[0]["quantity"] != 1: raise Error.Error( "Please include just a single SGEEA in your kmail.", Error.BOT_REQUEST) # Perform the request. m = {} m["userId"] = message["userId"] Report.info("bot", "Attempting to remove effect %s..." % effectId) r = UneffectRequest(bot.session, effectId) try: r.doRequest() m["text"] = "Effect successfully removed!" except Error.Error, inst: if inst.code == Error.EFFECT_NOT_FOUND: m["text"] = "I do not currently have that effect." m["items"] = items else: m["text"] = "Unable to remove effect for unknown reason." m["items"] = items bot.sendKmail(m) returnCode = FilterManager.FINISHED
def parseResponse(self): # Get the timestamp we should send to the server next time we make a request. lastSeenPattern = PatternManager.getOrCompilePattern("chatLastSeen") match = lastSeenPattern.search(self.responseText) self.responseData["lastSeen"] = match.group(1) # Parse the chat messages. text = self.responseText[:self.responseText.find('<!--lastseen')] self.responseData["chatMessages"] = ChatUtils.parseMessages( self.responseText, True) # Trace out unknown messages. for chat in self.responseData["chatMessages"]: if chat["type"] == "unknown": Report.trace("chat", "Unable to parse chat message: %s" % chat)
def run(self): Report.trace('relay', 'Starting RelayServer on port %s...' % self.port) started = False numTries = 0 while not started: try: server = HTTPServer(('', self.port), RelayRequestHandler) started = True except socket.error, inst: numTries += 1 if numTries == 10: raise inst Report.trace('relay', 'Could not listen on port %s. Trying %s instead.' % (self.port, self.port + 1)) self.port += 1
def couldNotFindItem(context, **kwargs): if "session" not in kwargs: return session = kwargs["session"] item = None r = ClosetContentsRequest(session) r.skipParseResponse = True r.doRequest() if "descId" in kwargs: descId = kwargs["descId"] pattern = re.compile("<option value='([0-9]+)' descid='%s'>([^<>]*) \([0-9]+\)<\/option>" % descId) match = pattern.search(r.responseText) if match: item = {"id":int(match.group(1)), "descId":descId, "name":match.group(2)} else: raise ItemNotFoundError("Could not find item associated with description ID '%s'." % descId) elif "itemId" in kwargs: itemId = kwargs["itemId"] pattern = re.compile("<option value='%s' descid='([0-9]+)'>([^<>]*) \([0-9]+\)<\/option>" % itemId) match = pattern.search(r.responseText) if match: item = {"id":itemId, "descId":int(match.group(1)), "name":match.group(2)} else: raise ItemNotFoundError("Could not find item associated with ID '%s'." % itemId) elif "itemName" in kwargs: itemName = kwargs["itemName"] pattern = re.compile("<option value='([0-9]+)' descid='([0-9]+)'>%s \([0-9]+\)<\/option>" % itemName) match = pattern.search(r.responseText) if match: item = {"id":int(match.group(1)), "descId":int(match.group(2)), "name":itemName} else: raise ItemNotFoundError("Could not find item with name '%s'." % itemName) if item != None: r = ItemDescriptionRequest(session, item["descId"]) itemInfo = r.doRequest() for k,v in itemInfo.iteritems(): item[k] = v Report.trace("itemdatabase", "Discovered new item: %s" % item) context["item"] = item FilterManager.executeFiltersForEvent("discoveredNewItem", session=session, item=item)
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)
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)
def parseResponse(self): hardcoreRoninPattern = PatternManager.getOrCompilePattern('userInHardcoreRonin') ignoringPattern = PatternManager.getOrCompilePattern('userIgnoringUs') notEnoughItemsPattern = PatternManager.getOrCompilePattern('notEnoughItemsToSend') sentMessagePattern = PatternManager.getOrCompilePattern('messageSent') 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 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)
def parseResponse(self): hardcoreRoninPattern = PatternManager.getOrCompilePattern('userInHardcoreRonin') ignoringPattern = PatternManager.getOrCompilePattern('userIgnoringUs') notEnoughItemsPattern = PatternManager.getOrCompilePattern('notEnoughItemsToSend') sentMessagePattern = PatternManager.getOrCompilePattern('messageSent') if hardcoreRoninPattern.search(self.responseText): raise UserInHardcoreRoninError("Unable to send items or meat. User is in hardcore or ronin.") elif ignoringPattern.search(self.responseText): raise UserIsIgnoringError("Unable to send message. User is ignoring us.") elif notEnoughItemsPattern.search(self.responseText): raise NotEnoughItemsError("You don't have enough of one of the items you're trying to send.") elif sentMessagePattern.search(self.responseText) == None: Report.alert("system", "Received unknown response when attempting to send a message.") Report.alert("system", self.responseText) raise RequestError("Unknown error")
class RelayServer(threading.Thread): """ This class acts as a relay server, allowing users to use a browser to communicate with the KoL servers even if they are already logged in via a script or bot. It works much like the KoLmafia relay browser system by listening to a port on the local machine. Any traffic sent to that port will be relayed to the KoL servers. Eventually, the response will be sent back on the same socket. Note that if the port is already in use, this class will try again with the next highest port number. It will do this a total of 10 times before finally giving up and raising a socket.error exception. """ def __init__(self, session, port=8557): super(RelayServer, self).__init__() self.session = session self.port = port self.haltEvent = threading.Event() def run(self): Report.trace('relay', 'Starting RelayServer on port %s...' % self.port) started = False numTries = 0 while not started: try: server = HTTPServer(('', self.port), RelayRequestHandler) started = True except socket.error, inst: numTries += 1 if numTries == 10: raise inst Report.trace( 'relay', 'Could not listen on port %s. Trying %s instead.' % (self.port, self.port + 1)) self.port += 1 server.relayServer = self Report.trace('relay', 'RelayServer started.') # Handle requests for as long as we can. while (not self.haltEvent.isSet()): server.handle_request() # Shut down the RelayServer. Report.trace('relay', 'Shutting down RelayServer.') server.socket.close()
def handleClanChat(context, **kwargs): chat = kwargs["chat"] bot = kwargs["bot"] globalState = bot.states["global"] # Do nothing if the bot is squelched. if DataUtils.getBoolean(globalState, "isSquelched", False): return FilterManager.CONTINUE # Do nothing if the text is prefixed by PRIVATE: lowerText = chat["text"].lower() if lowerText.find("private:") == 0: return FilterManager.CONTINUE # Do nothing for broadcasted messages. if chat["userName"] == "System Message": return FilterManager.CONTINUE # Construct the message to send to the other bots. msg = None if "chatBroadcastDelimiters" in bot.params: chars = bot.params["chatBroadcastDelimiters"] if chat["type"] == "normal": msg = "%s%s%s %s" % (chars[0], chat["userName"], chars[1], chat["text"]) elif chat["type"] == "emote": msg = "/me %s%s%s %s" % (chars[0], chat["userName"], chars[1], chat["text"]) else: if chat["type"] == "normal": msg = "[%s] %s" % (chat["userName"], chat["text"]) elif chat["type"] == "emote": msg = "/me [%s] %s" % (chat["userName"], chat["text"]) # Send the message to the other bots. if msg != None: thisBot = kwargs["bot"] for bot in BotManager._bots: if bot.id != thisBot.id: if bot.session != None and bot.session.isConnected and hasattr( bot.session, "chatManager"): try: bot.sendChatMessage(msg) except AttributeError, inst: Report.error("chat", "Could not broadcast message.", inst)
def runBots(): if len(_bots) > 1: Report.includeThreadName = True for bot in _bots: bot.start() try: while _haltEvent.isSet() == False: time.sleep(15) except KeyboardInterrupt: _haltEvent.set() Report.info("bot", "Shutting down.") for bot in _bots: bot.join()
def openAllGiftPackages(self): Report.trace("kmail", "Opening gift package(s).") giftPackages = {} # Get a list of all gift packages in our inventory. r = InventoryRequest(self.session) responseData = r.doRequest() items = responseData["items"] for item in items: if "type" in item and item["type"] == "gift package": giftPackages[item["id"]] = item["quantity"] # Open all of the gift packages. for itemId,quantity in giftPackages.iteritems(): for i in range(quantity): r = UseItemRequest(self.session, itemId) r.doRequest()
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)
def openAllGiftPackages(self): Report.trace("kmail", "Opening gift package(s).") giftPackages = {} # Get a list of all gift packages in our inventory. r = InventoryRequest(self.session, which=3) responseData = r.doRequest() items = responseData["items"] for item in items: if "type" in item and item["type"] == "gift package": giftPackages[item["id"]] = item["quantity"] # Open all of the gift packages. for itemId,quantity in giftPackages.iteritems(): for i in range(quantity): r = UseItemRequest(self.session, itemId) r.doRequest()
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 DontHaveEffectError("Unable to remove effect. The user does not have that effect.") youDontHaveSGEEAPattern = PatternManager.getOrCompilePattern("youDontHaveSGEEA") if youDontHaveSGEEAPattern.search(self.responseText): raise NotEnoughItemsError("Unable to remove effect. You do not have a soft green echo eyedrop antidote.") Report.error("request", "Unknown error occurred when trying to remove an effect") Report.error("request", self.responseText) raise RequestError("Unknown error occurred when trying to remove an effect.")
def do_POST(self): Report.debug("relay", "POST: %s" % self.path) relayServer = self.server.relayServer # Parse out the POST parameters. headers = str(self.headers).split('\n') length = 0 for x in headers: if x.split(':')[0].lower() == 'content-length': length = int(x.split(':')[1].strip()) payload = self.rfile.read(length) # Execute the server request. dReq = DynamicRequest(relayServer.session, self.path[1:], payload) dReq.doRequest() self.wfile.write(dReq.responseText)
def handleClanChat(context, **kwargs): chat = kwargs["chat"] bot = kwargs["bot"] globalState = bot.states["global"] # Do nothing if the text is prefixed by PRIVATE: lowerText = chat["text"].lower() if lowerText.find("private:") == 0 or lowerText[0:2] == "p:": return FilterManager.CONTINUE if DataUtils.getBoolean(kwargs["bot"].params, "doWork:doLogChat", False): HogDatabase.logChat(chat["userId"], chat["userName"], bot.params["userClan"], chat["text"]) # Do nothing if the bot is squelched. if DataUtils.getBoolean(globalState, "isSquelched", False): return FilterManager.CONTINUE # Do nothing for broadcasted messages. if chat["userName"] == "System Message": return FilterManager.CONTINUE # Construct the message to send to the other bots. msg = None if "chatBroadcastDelimiters" in bot.params: chars = bot.params["chatBroadcastDelimiters"] if chat["type"] == "normal": msg = "%s%s%s %s" % (chars[0], chat["userName"], chars[1], chat["text"]) elif chat["type"] == "emote": msg = "/me %s%s%s %s" % (chars[0], chat["userName"], chars[1], chat["text"]) else: if chat["type"] == "normal": msg = "[%s] %s" % (chat["userName"], chat["text"]) elif chat["type"] == "emote": msg = "/me [%s] %s" % (chat["userName"], chat["text"]) # Send the message to the other bots. if msg != None: thisBot = kwargs["bot"] for bot in BotManager._bots: if bot.id != thisBot.id: if bot.session != None and bot.session.isConnected and hasattr(bot.session, "chatManager"): try: bot.sendChatMessage(msg) except AttributeError, inst: Report.error("chat", "Could not broadcast message.", inst)
def saveItemsToFile(): global __dbChanged if not __dbChanged: return try: f = open(discoveryFile, 'wb') pickle.dump(__discoveryDate, f) pickle.dump(__itemsById, f) pickle.dump(__itemsByDescId, f) pickle.dump(__itemsByName, f) f.close() Report.trace("itemdatabase", "Wrote %d items to file." % len(__itemsById)) __dbChanged = False except: Report.trace("itemdatabase", "Error opening %s for writing" % (discoveryFile)) deleteItemCache()
def run(self): Report.trace('relay', 'Starting RelayServer on port %s...' % self.port) started = False numTries = 0 while not started: try: server = HTTPServer(('', self.port), RelayRequestHandler) started = True except socket.error, inst: numTries += 1 if numTries == 10: raise inst Report.trace( 'relay', 'Could not listen on port %s. Trying %s instead.' % (self.port, self.port + 1)) self.port += 1
def runBots(): if len(_bots) > 1: Report.setIncludeThreadName(True) FilterManager.executeFiltersForEvent("runBots") for bot in _bots: bot.start() try: while _haltEvent.isSet() == False: time.sleep(15) except KeyboardInterrupt: _haltEvent.set() Report.info("bot", "Shutting down.") for bot in _bots: bot.join()
def botProcessKmail(context, **kwargs): returnCode = FilterManager.CONTINUE message = kwargs["kmail"] bot = kwargs["bot"] cmd = BotUtils.getKmailCommand(message) if cmd == "uneffect": arr = message["text"].split() items = message["items"] # Get the effect ID. if len(arr) < 2: raise Error.Error("You must specify the ID of the effect to remove.", Error.BOT_REQUEST) try: effectId = int(arr[1]) except ValueError: raise Error.Error("Unable to remove effect. Invalid effect ID.", Error.BOT_REQUEST) # Ensure the user sent a SGEEA. if len(items) != 1: raise Error.Error("Please include just a SGEEA in your kmail.", Error.BOT_REQUEST) sgeea = ItemDatabase.getItemFromName("soft green echo eyedrop antidote") if items[0]["id"] != sgeea["id"] or items[0]["quantity"] != 1: raise Error.Error("Please include just a single SGEEA in your kmail.", Error.BOT_REQUEST) # Perform the request. m = {} m["userId"] = message["userId"] Report.info("bot", "Attempting to remove effect %s..." % effectId) r = UneffectRequest(bot.session, effectId) try: r.doRequest() m["text"] = "Effect successfully removed!" except Error.Error, inst: if inst.code == Error.EFFECT_NOT_FOUND: m["text"] = "I do not currently have that effect." m["items"] = items else: m["text"] = "Unable to remove effect for unknown reason." m["items"] = items bot.sendKmail(m) returnCode = FilterManager.FINISHED
def parseStashActivity(self, clanLog): results = {} match = STASH_PATTERN.search(clanLog) if match: rows = match.group("rows").split("<br>") for row in rows: row = row.strip() if len(row) > 0: data = self.parseStashActivityRow(row) category = data["category"] if not category in results: results[category] = [] results[category].append(data) del data["category"] else: Report.info("bot", "Stash activity not found in clan activity log") return results
def doRequest(self): """ Performs the request. This method will ensure that nightly maintenance is not occuring. 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 %s" % self.url) self.response = self.session.opener.opener.post(self.url, self.requestData, stream=True) responseStr = StringIO() try: for chunk in self.response.iter_content(self.chunkSize): responseStr.write(chunk) s = responseStr.getvalue() matched = True for regex in self.regexList: if not regex.search(s): matched = False break if matched: break self.responseText = responseStr.getvalue() responseStr.close() finally: self.response.close() Report.debug("request", "Received response: %s" % self.url) Report.debug("request", "Response Text: %s" % 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: %s" % self.responseData) return self.responseData
def doRequest(self): """ Performs the request. This method will ensure that nightly maintenance is not occuring. In addition, this method will throw a NOT_LOGGED_IN error if the session thinks it is logged in when it actually isn't. All specific KoL requests should inherit from this class. """ if self.get: Report.debug("request", "Requesting %s via GET".format(self.url)) self.response = self.session.opener.get(self.url, self.requestData) else: Report.debug("request", "Requesting %s via POST".format(self.url)) self.response = self.session.opener.open(self.url, self.requestData) self.responseText = self.response.text Report.debug("request", "Received response: %s" % self.url) Report.debug("request", "Response Text: %s" % 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: %s" % self.responseData) return self.responseData
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 __dbChanged __dbChanged = False loadItemsFromFile() 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.")
def loadItemsFromFile(): global __dbChanged try: f = open(discoveryFile, 'rb') global __itemsById, __itemsByDescId, __itemsByName, __discoveryDate __discoveryDate = pickle.load(f) if __discoveryDate is None or (datetime.datetime.now() - __discoveryDate) < datetime.timedelta( days=14): __itemsById = pickle.load(f) __itemsByDescId = pickle.load(f) __itemsByName = pickle.load(f) else: Report.trace("itemdatabase", "Item cache expired") __discoveryDate = datetime.datetime.now() __dbChanged = True __itemsById = {} __itemsByDescId = {} __itemsByName = {} saveItemsToFile() f.close() Report.trace("itemdatabase", "Loaded %d items from file." % len(__itemsById)) except: Report.trace("itemdatabase", "Error opening %s for loading" % (discoveryFile)) __discoveryDate = datetime.datetime.now() __dbChanged = True __itemsById = {} __itemsByDescId = {} __itemsByName = {} deleteItemCache()
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 _badPlayerId.search(self.responseText): raise Error.Error("Cannot send Kmail. Bad userId.", Error.INVALID_USER) 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)
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)
def parseResponse(self): weakSkillPattern = PatternManager.getOrCompilePattern('skillTooWeak') badSkillPattern = PatternManager.getOrCompilePattern('skillNotTrainable') poorSkillPattern = PatternManager.getOrCompilePattern('skillTooPoor') haveSkillPattern = PatternManager.getOrCompilePattern('skillHaveAlready') if weakSkillPattern.search(self.responseText): raise InvalidActionError("You aren't a high enough level to train that skill") if badSkillPattern.search(self.responseText): raise SkillMissingError("You cannot train that skill at the Guild Hall") if poorSkillPattern.search(self.responseText): raise NotEnoughMeatError("You cannot afford to train that skill") if haveSkillPattern.search(self.responseText): raise RequestError("You already know that skill") skillLearnedPattern = PatternManager.getOrCompilePattern('skillLearned') match = skillLearnedPattern.search(self.responseText) if match: try: skill = SkillDatabase.getSkillFromName(match.group(1)) self.responseData["skill"] = skill except SkillNotFoundError, inst: Report.error("bot", inst.message, inst)
def whois(bot, name): Report.trace('bot', 'Whois: ' + name) response = bot.sendChatMessage('/whois ' + name) responsetext = ''.join(x['text'] for x in response) match = re.search(r'<a[^>]*showplayer.php[^>]*><b[^>]*>([A-Za-z0-9_ ]+) \(#([0-9]+)\)</b></a>', responsetext) if match: player_name = match.group(1) player_id = match.group(2) Report.trace('bot', 'Whois resolved: Name: ' + str(player_name)) Report.trace('bot', 'Whois resolved: ID: ' + str(player_id)) return player_name, player_id elif 'Unknown Player: ' in responsetext: raise Error.Error("That player could not be found.", Error.USER_NOT_FOUND) else: Report.warning('bot', 'Unable to parse /whois response: ' + repr(responsetext)) raise Error.Error("Unable to parse /whois response.", Error.REQUEST_GENERIC)
def parseResponse(self): hardcoreRoninPattern = PatternManager.getOrCompilePattern( 'userInHardcoreRonin') ignoringPattern = PatternManager.getOrCompilePattern('userIgnoringUs') notEnoughItemsPattern = PatternManager.getOrCompilePattern( 'notEnoughItemsToSend') sentMessagePattern = PatternManager.getOrCompilePattern('messageSent') if hardcoreRoninPattern.search(self.responseText): raise UserInHardcoreRoninError( "Unable to send items or meat. User is in hardcore or ronin.") elif ignoringPattern.search(self.responseText): raise UserIsIgnoringError( "Unable to send message. User is ignoring us.") elif notEnoughItemsPattern.search(self.responseText): raise NotEnoughItemsError( "You don't have enough of one of the items you're trying to send." ) elif sentMessagePattern.search(self.responseText) == None: Report.alert( "system", "Received unknown response when attempting to send a message.") Report.alert("system", self.responseText) raise RequestError("Unknown error")
def run(self): Report.trace('relay', 'Starting RelayServer on port %s...' % self.port) server = HTTPServer(('', 8557), RelayRequestHandler) server.relayServer = self Report.trace('relay', 'RelayServer started.') # Launch the relay server URL in a browser window. url = 'http://localhost:%s/main.html' % self.port sysname = os.uname()[0] if sysname == "darwin": os.spawnlp(os.P_NOWAIT, "open", "open", url) else: os.startfile(url) # Handle requests for as long as we can. while (not self.haltEvent.isSet()): server.handle_request() # Shut down the RelayServer. Report.trace('relay', 'Shutting down RelayServer.') server.socket.close()
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.") cxt = FilterManager.executeFiltersForEvent("preInitializeSkillDatabase") if "returnCode" in cxt and cxt["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.")
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.")
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.")
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 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(' ', '').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
def deleteItemCache(): try: Report.trace("itemdatabase", "Deleted item cache" % (discoveryFile)) os.remove(discoveryFile) except: pass
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