Пример #1
0
	def parseResponse(self):
		dontHaveMeatpastePattern = PatternManager.getOrCompilePattern('noMeatpaste')
		itemsDontMeatpastePattern = PatternManager.getOrCompilePattern('itemsDontMeatpaste')
		dontHaveItemsPattern = PatternManager.getOrCompilePattern('dontHaveItemsMeatpaste')
		
		# Check for errors.
		if dontHaveMeatpastePattern.search(self.responseText):
			raise NotEnoughItemsError("Unable to combine items. You don't have any meatpaste.")
		elif itemsDontMeatpastePattern.search(self.responseText):
			raise InvalidRecipeError("Unable to combine items. The submitted ingredients do not meatpaste together.")
		elif dontHaveItemsPattern.search(self.responseText):
			raise NotEnoughItemsError("Unable to combine items. You don't have all of the items you are trying to meatpaste.")
			
		# Find the items attached to the message.
		singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
		match = singleItemPattern.search(self.responseText)
		if match:
			descId = int(match.group(1))
			item = ItemDatabase.getItemFromDescId(descId, self.session)
			item["quantity"] = 1
		else:
			multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
			match = multiItemPattern.search(self.responseText)
			if match:
				descId = int(match.group(1))
				item = ItemDatabase.getItemFromDescId(descId, self.session)
				quantity = int(match.group(2).replace(',', ''))
				item["quantity"] = quantity
			else:
				raise RequestError("Unknown error.")
		
		self.responseData["items"] = item
Пример #2
0
    def parseResponse(self):
        noWokAccess = PatternManager.getOrCompilePattern('noWokAccess')
        itemsDontMakeFoodPattern = PatternManager.getOrCompilePattern('dontHaveItemsForWok')
        dontHaveSkillPattern = PatternManager.getOrCompilePattern('dontHaveSkillForWok')
        dontHaveAdventuresPattern = PatternManager.getOrCompilePattern('dontHaveAdventuresForWok')
        # Check for errors.
        if noWokAccess.search(self.responseText):
            raise Error.Error("Unable to use the Wok of Ages. I can't get to the Wok!", Error.RECIPE_NOT_FOUND)
        elif dontHaveSkillPattern.search(self.responseText):
            raise Error.Error("Unable to use the Wok of Ages. I am not skilled enough.", Error.SKILL_NOT_FOUND)
        elif itemsDontMakeFoodPattern.search(self.responseText):
            raise Error.Error("Unable to use the Wok of Ages. Invalid ingredients.", Error.ITEM_NOT_FOUND)
        elif dontHaveAdventuresPattern.search(self.responseText):
            raise Error.Error("Unable to use the Wok of Agles. I don't have enough adventures.", Error.NOT_ENOUGH_ADVENTURES)

        # Find the items attached to the message.
        singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
        match = singleItemPattern.search(self.responseText)
        if match:
            descId = int(match.group(1))
            item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
            item["quantity"] = 1
        else:
            multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
            match = multiItemPattern.search(self.responseText)
            if match:
                descId = int(match.group(1))
                item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
                quantity = int(match.group(2).replace(',', ''))
                item["quantity"] = quantity
            else:
                raise Error.Error("Unknown error.", Error.REQUEST_GENERIC)

        self.responseData["wok"] = item
Пример #3
0
 def runTest(self):
     s = TestData.data["session"]
     
     item = ItemDatabase.getItemFromName("olive")
     r = ItemDescriptionRequest(s, item["descId"])
     itemData = r.doRequest()
     self.assertEquals(itemData["isCookingIngredient"], True)
     self.assertEquals(itemData["isCocktailcraftingIngredient"], True)
     self.assertEquals(itemData["image"], "olive.gif")
     self.assertEquals(itemData["autosell"], 35)
     self.assertEquals(itemData["type"], "food")
     
     item = ItemDatabase.getItemFromName("furry fur")
     r = ItemDescriptionRequest(s, item["descId"])
     itemData = r.doRequest()
     self.assertEquals(itemData["isMeatsmithingComponent"], True)
     self.assertEquals(itemData["image"], "furfur.gif")
     self.assertEquals(itemData["autosell"], 129)
     
     item = ItemDatabase.getItemFromName("baconstone")
     r = ItemDescriptionRequest(s, item["descId"])
     itemData = r.doRequest()
     self.assertEquals(itemData["isJewelrymakingComponent"], True)
     self.assertEquals(itemData["image"], "baconstone.gif")
     self.assertEquals(itemData["autosell"], 500)
     
     # Test a haiku item -- these description pages are formatted differently.
     r = ItemDescriptionRequest(s, 435365663)
     itemData = r.doRequest()
     self.assertEquals(itemData["name"], "little round pebble")
     self.assertEquals(itemData["autosell"], 45)
     self.assertEquals(itemData["type"], "off-hand item")
Пример #4
0
	def parseResponse(self):
		cantPulverizePattern = PatternManager.getOrCompilePattern('cantPulverizeItem')
		if cantPulverizePattern.search(self.responseText) != None:
			item = ItemDatabase.getItemFromId(self.itemId, self.session)
			raise UnableToPulverizeItemError("'%s' is not an item that can be pulverized." % item["name"])
		
		notEnoughItemsPattern = PatternManager.getOrCompilePattern('notEnoughItems')
		if notEnoughItemsPattern.search(self.responseText) != None:
			item = ItemDatabase.getItemFromId(self.itemId, self.session)
			if self.quantity == 1:
				itemStr = item["name"]
			else:
				itemStr = item["plural"]
			raise NotEnoughItemsError("You do not have %s %s" % (self.quantity % itemStr))
			
		items = []
		
		singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
		for match in singleItemPattern.finditer(self.responseText):
			descId = int(match.group(1))
			item = ItemDatabase.getItemFromDescId(descId, self.session)
			item["quantity"] = 1
			items.append(item)
		
		multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
		for match in multiItemPattern.finditer(self.responseText):
			descId = int(match.group(1))
			quantity = int(match.group(2).replace(',', ''))
			item = ItemDatabase.getItemFromDescId(descId, self.session)
			item["quantity"] = quantity
			items.append(item)
		
		self.responseData["results"] = items
Пример #5
0
    def parseResponse(self):
        cantPulverizePattern = PatternManager.getOrCompilePattern('cantPulverizeItem')
        if cantPulverizePattern.search(self.responseText) != None:
            item = ItemDatabase.getOrDiscoverItemFromId(self.itemId, self.session)
            raise Error.Error("'%s' is not an item that can be pulverized." % item["name"], Error.WRONG_KIND_OF_ITEM)

        notEnoughItemsPattern = PatternManager.getOrCompilePattern('notEnoughItems')
        if notEnoughItemsPattern.search(self.responseText) != None:
            item = ItemDatabase.getOrDiscoverItemFromId(self.itemId, self.session)
            if self.quantity == 1:
                itemStr = item["name"]
            else:
                itemStr = item["plural"]
            raise Error.Error("You do not have %s (%s)." % (itemStr, self.quantity), Error.ITEM_NOT_FOUND)

        items = []

        singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
        for match in singleItemPattern.finditer(self.responseText):
            descId = int(match.group(1))
            item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
            item["quantity"] = 1
            items.append(item)

        multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
        for match in multiItemPattern.finditer(self.responseText):
            descId = int(match.group(1))
            quantity = int(match.group(2).replace(',', ''))
            item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
            item["quantity"] = quantity
            items.append(item)

        self.responseData["results"] = items
Пример #6
0
def preInitializeItemDatabase(context, **kwargs):
    f = None
    try:
        f = open(_path, "r")
    except IOError:
        pass
    except TypeError:
    	pass

    if f != None:
        line = f.readline()
        while len(line) > 0:
            line = line.strip(" \r\n")
            if len(line) > 0 and line[0] != '#':
                arr = line.split('\t')
                itemId = int(arr[0])
                descId = int(arr[1])
                name = arr[2]
                image = arr[3]
                autosell = int(arr[4])
                item = {"id":itemId, "descId":descId, "name":name, "autosell":autosell, "image":image}
                ItemDatabase.addItem(item)
            line = f.readline()
        f.close()

    return FilterManager.FINISHED
Пример #7
0
    def parseResponse(self):
        itemsDontMakeCocktailPattern = PatternManager.getOrCompilePattern('itemsDontMakeCocktail')
        dontHaveSkillPattern = PatternManager.getOrCompilePattern('dontHaveSkillToMixCocktail')
        dontHaveItemsPattern = PatternManager.getOrCompilePattern('dontHaveItemsForThatCocktail')
        dontHaveAdventuresPattern = PatternManager.getOrCompilePattern('dontHaveAdventuresToMixCocktail')

        # Check for errors.
        if itemsDontMakeCocktailPattern.search(self.responseText):
            raise Error.Error("Unable to make cocktail. The submitted ingredients do not mix together.", Error.RECIPE_NOT_FOUND)
        elif dontHaveSkillPattern.search(self.responseText):
            raise Error.Error("Unable to make cocktail. We are not skilled enough.", Error.SKILL_NOT_FOUND)
        elif dontHaveItemsPattern.search(self.responseText):
            raise Error.Error("Unable to make cocktail. You don't have all of the items you are trying to mix.", Error.ITEM_NOT_FOUND)
        elif dontHaveAdventuresPattern.search(self.responseText):
            raise Error.Error("Unable to mix drink(s). We don't have enough adventures.", Error.NOT_ENOUGH_ADVENTURES)

        # Find the items attached to the message.
        singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
        match = singleItemPattern.search(self.responseText)
        if match:
            descId = int(match.group(1))
            item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
            item["quantity"] = 1
        else:
            multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
            match = multiItemPattern.search(self.responseText)
            if match:
                descId = int(match.group(1))
                item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
                quantity = int(match.group(2).replace(',', ''))
                item["quantity"] = quantity
            else:
                raise Error.Error("Unknown error.", Error.REQUEST_GENERIC)

        self.responseData["booze"] = item
Пример #8
0
    def parseResponse(self):
        wrongProfessionPattern = PatternManager.getOrCompilePattern('wrongStillProfession')
        invalidItemPattern = PatternManager.getOrCompilePattern('invalidStillItem')
        ItemNotFoundPattern = PatternManager.getOrCompilePattern('stillItemNotFound')
        maxLimitPattern = PatternManager.getOrCompilePattern('stillMaxLimit')

        if wrongProfessionPattern.search(self.responseText):
            raise Error.Error("You aren't a Disco Bandit or Accordion Thief.", Error.USER_IS_WRONG_PROFESSION)
        if invalidItemPattern.search(self.responseText):
            raise Error.Error("You can\'t improve that item.", Error.INVALID_ITEM)
        if ItemNotFoundPattern.search(self.responseText):
            raise Error.Error("Not enough of that item.", Error.ITEM_NOT_FOUND)
        if maxLimitPattern.search(self.responseText):
            raise Error.Error("Still can\'t be used anymore today.", Error.LIMIT_REACHED)

        # Find the items attached to the message.
        singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
        match = singleItemPattern.search(self.responseText)
        if match:
            descId = int(match.group(1))
            item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
            item["quantity"] = 1
        else:
            multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
            match = multiItemPattern.search(self.responseText)
            if match:
                descId = int(match.group(1))
                item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
                quantity = int(match.group(2).replace(',', ''))
                item["quantity"] = quantity
            else:
                print self.responseText
                raise Error.Error("Unknown error.", Error.REQUEST_GENERIC)

        self.responseData["item"] = item
Пример #9
0
	def parseResponse(self):
		noMeatForPastePattern = PatternManager.getOrCompilePattern('noMeatForMeatpasting')
		
		# Check for errors.
		if noMeatForPastePattern.search(self.responseText):
			raise NotEnoughMeatError("Unable to make the requested item. You don't have enough meat")

		# Find the items attached to the message.
		singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
		match = singleItemPattern.search(self.responseText)
		if match:
			descId = int(match.group(1))
			item = ItemDatabase.getItemFromDescId(descId, self.session)
			item["quantity"] = 1
		else:
			multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
			match = multiItemPattern.search(self.responseText)
			if match:
				descId = int(match.group(1))
				item = ItemDatabase.getItemFromDescId(descId, self.session)
				quantity = int(match.group(2).replace(',', ''))
				item["quantity"] = quantity
			else:
				raise RequestError("Unknown error.")
		
		self.responseData["items"] = item
Пример #10
0
def preInitializeItemDatabase(context, **kwargs):
    f = None
    try:
        f = open(_path, "r")
    except IOError:
        pass

    if f != None:
        line = f.readline()
        while len(line) > 0:
            line = line.strip(" \r\n")
            if len(line) > 0 and line[0] != '#':
                arr = line.split('\t')
                itemId = int(arr[0])
                descId = int(arr[1])
                name = arr[2]
                image = arr[3]
                autosell = int(arr[4])
                item = {
                    "id": itemId,
                    "descId": descId,
                    "name": name,
                    "autosell": autosell,
                    "image": image
                }
                ItemDatabase.addItem(item)
            line = f.readline()
        f.close()

    return FilterManager.FINISHED
Пример #11
0
    def parseResponse(self):
        itemsDontMakeCocktailPattern = PatternManager.getOrCompilePattern('itemsDontMakeCocktail')
        dontHaveSkillPattern = PatternManager.getOrCompilePattern('dontHaveSkillToMixCocktail')
        dontHaveItemsPattern = PatternManager.getOrCompilePattern('dontHaveItemsForThatCocktail')
        dontHaveAdventuresPattern = PatternManager.getOrCompilePattern('dontHaveAdventuresToMixCocktail')

        # Check for errors.
        if itemsDontMakeCocktailPattern.search(self.responseText):
            raise InvalidRecipeError("Unable to make cocktail. The submitted ingredients do not mix together.")
        elif dontHaveSkillPattern.search(self.responseText):
            raise SkillMissingError("Unable to make cocktail. We are not skilled enough.")
        elif dontHaveItemsPattern.search(self.responseText):
            raise NotEnoughItemsError("Unable to make cocktail. You don't have all of the items you are trying to mix.")
        elif dontHaveAdventuresPattern.search(self.responseText):
            raise NotEnoughAdventuresLeftError("Unable to mix drink(s). We don't have enough adventures.")

        # Find the items attached to the message.
        singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
        match = singleItemPattern.search(self.responseText)
        if match:
            descId = int(match.group(1))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = 1
        else:
            multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
            match = multiItemPattern.search(self.responseText)
            if match:
                descId = int(match.group(1))
                item = ItemDatabase.getItemFromDescId(descId, self.session)
                quantity = int(match.group(2).replace(',', ''))
                item["quantity"] = quantity
            else:
                raise RequestError("Unknown error.")

        self.responseData["booze"] = item
Пример #12
0
    def parseResponse(self):
        itemsDontMakeFoodPattern = PatternManager.getOrCompilePattern(
            'itemsDontCook')
        dontHaveSkillPattern = PatternManager.getOrCompilePattern(
            'dontHaveSkillToCook')
        dontHaveItemsPattern = PatternManager.getOrCompilePattern(
            'dontHaveItemsForCook')
        dontHaveAdventuresPattern = PatternManager.getOrCompilePattern(
            'dontHaveAdventuresToCook')
        chefExplosionPattern = PatternManager.getOrCompilePattern(
            'chefExplosion')
        # Check for errors.
        if itemsDontMakeFoodPattern.search(self.responseText):
            raise Error.Error(
                "Unable to make food. The submitted ingredients do not cook together.",
                Error.RECIPE_NOT_FOUND)
        elif dontHaveSkillPattern.search(self.responseText):
            raise Error.Error(
                "Unable to make food. We are not skilled enough.",
                Error.SKILL_NOT_FOUND)
        elif dontHaveItemsPattern.search(self.responseText):
            raise Error.Error(
                "Unable to make food. You don't have all of the items you are trying to cook.",
                Error.ITEM_NOT_FOUND)
        elif dontHaveAdventuresPattern.search(self.responseText):
            raise Error.Error(
                "Unable to cook food(s). We don't have enough adventures.",
                Error.NOT_ENOUGH_ADVENTURES)

        # Find the items attached to the message.
        singleItemPattern = PatternManager.getOrCompilePattern(
            'acquireSingleItem')
        match = singleItemPattern.search(self.responseText)
        if match:
            descId = int(match.group(1))
            item = ItemDatabase.getOrDiscoverItemFromDescId(
                descId, self.session)
            item["quantity"] = 1
        else:
            multiItemPattern = PatternManager.getOrCompilePattern(
                'acquireMultipleItems')
            match = multiItemPattern.search(self.responseText)
            if match:
                descId = int(match.group(1))
                item = ItemDatabase.getOrDiscoverItemFromDescId(
                    descId, self.session)
                quantity = int(match.group(2).replace(',', ''))
                item["quantity"] = quantity
            else:
                raise Error.Error("Unknown error.", Error.REQUEST_GENERIC)

        # Check for an explosion
        if chefExplosionPattern.search(self.responseText):
            self.responseData["explosion"] = 1
            #TODO: Remove the items that came from the explosion

        self.responseData["food"] = item
Пример #13
0
def init(params=None):
	global _haltEvent
	
	# Create the event which can be used to halt all bots.
	_haltEvent = threading.Event()
	
	# Initialize the databases.
	ItemDatabase.init()
	SkillDatabase.init()
	
	# Force HTTP requests to timeout after 5 minutes.
	socket.setdefaulttimeout(300)
Пример #14
0
    def parseResponse(self):
        itemsDontMakeCocktailPattern = PatternManager.getOrCompilePattern(
            'itemsDontMakeCocktail')
        dontHaveSkillPattern = PatternManager.getOrCompilePattern(
            'dontHaveSkillToMixCocktail')
        dontHaveItemsPattern = PatternManager.getOrCompilePattern(
            'dontHaveItemsForThatCocktail')
        dontHaveAdventuresPattern = PatternManager.getOrCompilePattern(
            'dontHaveAdventuresToMixCocktail')

        # Check for errors.
        if itemsDontMakeCocktailPattern.search(self.responseText):
            raise Error.Error(
                "Unable to make cocktail. The submitted ingredients do not mix together.",
                Error.RECIPE_NOT_FOUND)
        elif dontHaveSkillPattern.search(self.responseText):
            raise Error.Error(
                "Unable to make cocktail. We are not skilled enough.",
                Error.SKILL_NOT_FOUND)
        elif dontHaveItemsPattern.search(self.responseText):
            raise Error.Error(
                "Unable to make cocktail. You don't have all of the items you are trying to mix.",
                Error.ITEM_NOT_FOUND)
        elif dontHaveAdventuresPattern.search(self.responseText):
            raise Error.Error(
                "Unable to mix drink(s). We don't have enough adventures.",
                Error.NOT_ENOUGH_ADVENTURES)

        # Find the items attached to the message.
        singleItemPattern = PatternManager.getOrCompilePattern(
            'acquireSingleItem')
        match = singleItemPattern.search(self.responseText)
        if match:
            descId = int(match.group(1))
            item = ItemDatabase.getOrDiscoverItemFromDescId(
                descId, self.session)
            item["quantity"] = 1
        else:
            multiItemPattern = PatternManager.getOrCompilePattern(
                'acquireMultipleItems')
            match = multiItemPattern.search(self.responseText)
            if match:
                descId = int(match.group(1))
                item = ItemDatabase.getOrDiscoverItemFromDescId(
                    descId, self.session)
                quantity = int(match.group(2).replace(',', ''))
                item["quantity"] = quantity
            else:
                raise Error.Error("Unknown error.", Error.REQUEST_GENERIC)

        self.responseData["booze"] = item
Пример #15
0
def init(params=None):
    global _haltEvent

    # Create the event which can be used to halt all bots.
    _haltEvent = threading.Event()

    # Initialize the databases.
    ItemDatabase.init()
    SkillDatabase.init()

    # Force HTTP requests to timeout after 5 minutes.
    socket.setdefaulttimeout(300)

    # Seed the pseudo-random number generator.
    random.seed()
Пример #16
0
 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)
Пример #17
0
    def parseResponse(self):
        response = {}
        
        bountyAvailablePattern = PatternManager.getOrCompilePattern('bountyAvailable')
        if bountyAvailablePattern.search(self.responseText):
            bountyAvailable = True
        else:
            bountyAvailable = False

        bountyChosenPattern = PatternManager.getOrCompilePattern('bountyChosen')
        bountyActivePattern1 = PatternManager.getOrCompilePattern('bountyActive1')
        bountyActivePattern2 = PatternManager.getOrCompilePattern('bountyActive2')
        
        if bountyChosenPattern.search(self.responseText) or \
            bountyActivePattern1.search(self.responseText) or \
            bountyActivePattern2.search(self.responseText):
                bountyActive = True
        else:
            bountyActive = False

        dailyBounties = []
        if bountyAvailable:
            bountyPattern = PatternManager.getOrCompilePattern('dailyBountyItem')
            for match in bountyPattern.finditer(self.responseText):
                itemId = int(match.group('itemid'))
                item = ItemDatabase.getItemFromId(itemId)
                dailyBounties.append(item)
        
        response['bountyAvailable'] = bountyAvailable
        response['bountyActive'] = bountyActive
        response['dailyBounties'] = dailyBounties
        
        self.responseData = response
Пример #18
0
	def parseResponse(self):
		"""
		Searches managestore.php for item name, quantity, price, limit, and ID.
		Returns the items with the usual keys in the item data base along with:

			quantity -- The number of the item in your mall store.
			   price -- The price of the item in your mall store.
			   limit -- The limit on the item in your mall store.
		"""
		storeInventoryPattern = PatternManager.getOrCompilePattern('storeInventory')

		items = []
		for match in storeInventoryPattern.finditer(self.responseText):
			name = match.group(1)
			if match.group(2) == None:
				quantity = 1
			else:
				quantity = int(match.group(2))
			price = int(match.group(3).replace(',',''))
			if match.group(4) == '<font size=1>(unlimited)</font>&nbsp;&nbsp;':
				limit = 0
			else:
				limit = int(match.group(4))
			itemID = int(match.group(5))
			item = ItemDatabase.getOrDiscoverItemFromId(itemID, self.session)
			item["quantity"] = quantity
			item["price"] = price
			item["limit"] = limit
			items.append(item)

		self.responseData["items"] = items
Пример #19
0
    def parseResponse(self):
        """
		Searches managestore.php for item name, quantity, price, limit, and ID.
		Returns the items with the usual keys in the item data base along with:

			quantity -- The number of the item in your mall store.
			   price -- The price of the item in your mall store.
			   limit -- The limit on the item in your mall store.
		"""
        storeInventoryPattern = PatternManager.getOrCompilePattern(
            'storeInventory')

        items = []
        for match in storeInventoryPattern.finditer(self.responseText):
            name = match.group(1)
            if match.group(2) == None:
                quantity = 1
            else:
                quantity = int(match.group(2))
            price = int(match.group(3).replace(',', ''))
            if match.group(4) == '<font size=1>(unlimited)</font>&nbsp;&nbsp;':
                limit = 0
            else:
                limit = int(match.group(4))
            itemID = int(match.group(5))
            item = ItemDatabase.getOrDiscoverItemFromId(itemID, self.session)
            item["quantity"] = quantity
            item["price"] = price
            item["limit"] = limit
            items.append(item)

        self.responseData["items"] = items
Пример #20
0
 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
Пример #21
0
    def parseResponse(self):
        """
        Searches backoffice.php for item name, quantity, price, limit, and ID.
        Returns the items with the usual keys in the item data base along with:

            quantity -- The number of the item in your mall store.
               price -- The price of the item in your mall store.
               limit -- The limit on the item in your mall store.
            cheapest -- The cheapest in mall. This includes limited items, use at own risk.
             orderId -- Item order in your store. 0 is the first listed and so on.
             
        RegExp match notes: Group 3,6,9, and 11 are garbage HTML data.
        """
        storeInventoryPattern = PatternManager.getOrCompilePattern('storeInventory')

        items = []
        for match in storeInventoryPattern.finditer(self.responseText):
            descId = match.group(1)
            orderId = match.group(2)
            name = match.group(4)
            quantity = match.group(5)
            itemID = int(match.group(7))
            item = ItemDatabase.getOrDiscoverItemFromId(itemID, self.session)
            price = match.group(8)
            limit = int(match.group(10))
            cheapest = int(match.group(12))
            
            item["orderId"] = orderId
            item["quantity"] = quantity
            item["price"] = price
            item["limit"] = limit
            item["cheapest"] = cheapest
            items.append(item)

        self.responseData["items"] = items
    def parseResponse(self):
        item = ItemDatabase.getOrDiscoverItemFromId(int(self.itemId), self.session)
        mallPricesUnlimitedPattern = PatternManager.getOrCompilePattern('mallPricesUnlimited')

        for match in mallPricesUnlimitedPattern.finditer(self.responseText):
            unlimited = []
            price = {"price" : match.group(1).replace(",", ""), "count" : match.group(2).replace(",", "")}
            unlimited.append(price)
            price = {"price" : match.group(3).replace(",", ""), "count" : match.group(4).replace(",", "")}
            unlimited.append(price)       
            price = {"price" : match.group(5).replace(",", ""), "count" : match.group(6).replace(",", "")}
            unlimited.append(price)        
            price = {"price" : match.group(7).replace(",", ""), "count" : match.group(8).replace(",", "")}
            unlimited.append(price)             
            
            item["unlimited"] = unlimited

        mallPricesLimitedPattern = PatternManager.getOrCompilePattern('mallPricesLimited')

        for match in mallPricesLimitedPattern.finditer(self.responseText):            
            limited = []
            print 
            price = {"price" : match.group(1).replace(",", ""), "limit" : match.group(2).replace(",", ""), "count" : match.group(3).replace(",", "")}
            limited.append(price)
            price = {"price" : match.group(4).replace(",", ""), "limit" : match.group(5).replace(",", ""), "count" : match.group(6).replace(",", "")}
            limited.append(price)
            price = {"price" : match.group(7).replace(",", ""), "limit" : match.group(8).replace(",", ""), "count" : match.group(9).replace(",", "")}
            limited.append(price)
            
            item["limited"] = limited

        self.responseData["item"] = item
Пример #23
0
    def parseResponse(self):
        itemsDontMakeCocktailPattern = PatternManager.getOrCompilePattern(
            'itemsDontMakeCocktail')
        dontHaveSkillPattern = PatternManager.getOrCompilePattern(
            'dontHaveSkillToMixCocktail')
        dontHaveItemsPattern = PatternManager.getOrCompilePattern(
            'dontHaveItemsForThatCocktail')
        dontHaveAdventuresPattern = PatternManager.getOrCompilePattern(
            'dontHaveAdventuresToMixCocktail')

        # Check for errors.
        if itemsDontMakeCocktailPattern.search(self.responseText):
            raise InvalidRecipeError(
                "Unable to make cocktail. The submitted ingredients do not mix together."
            )
        elif dontHaveSkillPattern.search(self.responseText):
            raise SkillMissingError(
                "Unable to make cocktail. We are not skilled enough.")
        elif dontHaveItemsPattern.search(self.responseText):
            raise NotEnoughItemsError(
                "Unable to make cocktail. You don't have all of the items you are trying to mix."
            )
        elif dontHaveAdventuresPattern.search(self.responseText):
            raise NotEnoughAdventuresLeftError(
                "Unable to mix drink(s). We don't have enough adventures.")

        # Find the items attached to the message.
        singleItemPattern = PatternManager.getOrCompilePattern(
            'acquireSingleItem')
        match = singleItemPattern.search(self.responseText)
        if match:
            descId = int(match.group(1))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = 1
        else:
            multiItemPattern = PatternManager.getOrCompilePattern(
                'acquireMultipleItems')
            match = multiItemPattern.search(self.responseText)
            if match:
                descId = int(match.group(1))
                item = ItemDatabase.getItemFromDescId(descId, self.session)
                quantity = int(match.group(2).replace(',', ''))
                item["quantity"] = quantity
            else:
                raise RequestError("Unknown error.")

        self.responseData["booze"] = item
Пример #24
0
def preInitializeItemDatabase(context, **kwargs):
    db = MySQLDatabaseManager.getDatabase("system")
    c = db.cursor()
    c.execute("SELECT * FROM item")
    row = c.fetchone()
    while row != None:
        item = {}
        item["id"] = row["item_id"]
        item["descId"] = row["desc_id"]
        item["name"] = row["name"]
        item["image"] = row["image"]
        item["autosell"] = row["autosell"]
        item["type"] = row["type"]
        ItemDatabase.addItem(item)
        row = c.fetchone()
    c.close()
    context["returnCode"] = FilterManager.FINISHED
Пример #25
0
def preInitializeItemDatabase(context, **kwargs):
    db = MySQLDatabaseManager.getDatabase("system")
    c = db.cursor()
    c.execute("SELECT * FROM item")
    row = c.fetchone()
    while row != None:
        item = {}
        item["id"] = row["item_id"]
        item["descId"] = row["desc_id"]
        item["name"] = row["name"]
        item["image"] = row["image"]
        item["autosell"] = row["autosell"]
        item["type"] = row["type"]
        ItemDatabase.addItem(item)
        row = c.fetchone()
    c.close()
    return FilterManager.FINISHED
Пример #26
0
def parseItemsReceived(text, session):
    items = []

    singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
    for match in singleItemPattern.finditer(text):
        descId = int(match.group(1))
        item = ItemDatabase.getOrDiscoverItemFromDescId(descId, session)
        item["quantity"] = 1
        items.append(item)

    multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
    for match in multiItemPattern.finditer(text):
        descId = int(match.group(1))
        quantity = int(match.group(2).replace(',', ''))
        item = ItemDatabase.getOrDiscoverItemFromDescId(descId, session)
        item["quantity"] = quantity
        items.append(item)

    return items
Пример #27
0
    def parseResponse(self):
        items = []

        singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
        for match in singleItemPattern.finditer(self.responseText):
            descId = int(match.group(1))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = 1
            items.append(item)

        multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
        for match in multiItemPattern.finditer(self.responseText):
            descId = int(match.group(1))
            quantity = int(match.group(2).replace(',', ''))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = quantity
            items.append(item)

        self.responseData["results"] = items
Пример #28
0
    def parseResponse(self):
        items = []

        singleItemPattern = PatternManager.getOrCompilePattern('inventorySingleItem')
        for match in singleItemPattern.finditer(self.responseText):
            descId = int(match.group(1))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = 1
            items.append(item)

        multipleItemsPattern = PatternManager.getOrCompilePattern('inventoryMultipleItems')
        for match in multipleItemsPattern.finditer(self.responseText):
            descId = int(match.group(1))
            quantity = int(match.group(3))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = quantity
            items.append(item)

        self.responseData["items"] = items
Пример #29
0
	def parseResponse(self):
		notEnoughMeatPattern = PatternManager.getOrCompilePattern('noMeatForStore')
		meatSpentPattern = PatternManager.getOrCompilePattern('meatSpent')
		invalidStorePattern = PatternManager.getOrCompilePattern('invalidStore')
		notSoldPattern = PatternManager.getOrCompilePattern('notSoldHere')
		singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
		multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
		
		# Check for errors.
		if invalidStorePattern.search(self.responseText):
			raise NotAStoreError("The store you tried to visit doesn't exist.")
		if notSoldPattern.search(self.responseText):
			raise NotEnoughItemsError("The store doesn't carry that item.")
		if notEnoughMeatPattern.search(self.responseText):
			raise NotEnoughMeatError("You do not have enough meat to purchase the item(s).")
		
		response={}
		
		# Find out how much meat was spent
		match = meatSpentPattern.search(self.responseText)
		if match:
				meatSpent = int(match.group(1).replace(',', ''))
				response["meatSpent"] = meatSpent
		
		# Find items recieved, if any.
		items = []
		for match in singleItemPattern.finditer(self.responseText):
			descId = int(match.group(1))
			item = ItemDatabase.getItemFromDescId(descId, self.session)
			item["quantity"] = 1
			items.append(item)
		for match in multiItemPattern.finditer(self.responseText):
			descId = int(match.group(1))
			quantity = int(match.group(2).replace(',', ''))
			item = ItemDatabase.getItemFromDescId(descId, self.session)
			item["quantity"] = quantity
			items.append(item)
		if len(items) > 0:
			response["item"] = items
		
		self.responseData = response
Пример #30
0
    def parseResponse(self):
        items = []

        singleItemPattern = PatternManager.getOrCompilePattern(
            'inventorySingleItem')
        for match in singleItemPattern.finditer(self.responseText):
            descId = int(match.group(1))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = 1
            items.append(item)

        multipleItemsPattern = PatternManager.getOrCompilePattern(
            'inventoryMultipleItems')
        for match in multipleItemsPattern.finditer(self.responseText):
            descId = int(match.group(1))
            quantity = int(match.group(3))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = quantity
            items.append(item)

        self.responseData["items"] = items
Пример #31
0
def mergeItems():
	ItemDatabase.init()
	for i in range(len(_items)):
		item = _items[i]
		try:
			savedItem = ItemDatabase.getItemFromId(item["id"])
			
			for k,v in item.iteritems():
				if k != "enchantments" and k != "type":
					savedItem[k] = v
			if "enchantments" in item and len(item["enchantments"]) > 0:
				if "enchantments" not in savedItem:
					savedItem["enchantments"] = {}
				for k,v in item["enchantments"].iteritems():
					savedItem["enchantments"][k] = v
			_items[i] = savedItem
		except ItemNotFoundError:
			r = ItemDescriptionRequest(_session, item["descId"])
			itemInfo = r.doRequest()
			for k,v in itemInfo.iteritems():
				item[k] = v
Пример #32
0
    def parseResponse(self):
        items = []

        singleItemPattern = PatternManager.getOrCompilePattern(
            'acquireSingleItem')
        for match in singleItemPattern.finditer(self.responseText):
            descId = int(match.group(1))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = 1
            items.append(item)

        multiItemPattern = PatternManager.getOrCompilePattern(
            'acquireMultipleItems')
        for match in multiItemPattern.finditer(self.responseText):
            descId = int(match.group(1))
            quantity = int(match.group(2).replace(',', ''))
            item = ItemDatabase.getItemFromDescId(descId, self.session)
            item["quantity"] = quantity
            items.append(item)

        self.responseData["results"] = items
Пример #33
0
def mergeItems():
    ItemDatabase.init()
    for i in range(len(_items)):
        item = _items[i]
        try:
            savedItem = ItemDatabase.getItemFromId(item["id"])

            for k,v in item.iteritems():
                if k != "enchantments" and k != "type":
                    savedItem[k] = v
            if "enchantments" in item and len(item["enchantments"]) > 0:
                if "enchantments" not in savedItem:
                    savedItem["enchantments"] = {}
                for k,v in item["enchantments"].iteritems():
                    savedItem["enchantments"][k] = v
            _items[i] = savedItem
        except ItemNotFoundError:
            r = ItemDescriptionRequest(_session, item["descId"])
            itemInfo = r.doRequest()
            for k,v in itemInfo.iteritems():
                item[k] = v
Пример #34
0
    def parseResponse(self):
        itemsDontMakeFoodPattern = PatternManager.getOrCompilePattern('itemsDontCook')
        dontHaveSkillPattern = PatternManager.getOrCompilePattern('dontHaveSkillToCook')
        dontHaveItemsPattern = PatternManager.getOrCompilePattern('dontHaveItemsForCook')
        dontHaveAdventuresPattern = PatternManager.getOrCompilePattern('dontHaveAdventuresToCook')
        chefExplosionPattern = PatternManager.getOrCompilePattern('chefExplosion')
        # Check for errors.
        if itemsDontMakeFoodPattern.search(self.responseText):
            raise Error.Error("Unable to make food. The submitted ingredients do not cook together.", Error.RECIPE_NOT_FOUND)
        elif dontHaveSkillPattern.search(self.responseText):
            raise Error.Error("Unable to make food. We are not skilled enough.", Error.SKILL_NOT_FOUND)
        elif dontHaveItemsPattern.search(self.responseText):
            raise Error.Error("Unable to make food. You don't have all of the items you are trying to cook.", Error.ITEM_NOT_FOUND)
        elif dontHaveAdventuresPattern.search(self.responseText):
            raise Error.Error("Unable to cook food(s). We don't have enough adventures.", Error.NOT_ENOUGH_ADVENTURES)

        # Find the items attached to the message.
        singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
        match = singleItemPattern.search(self.responseText)
        if match:
            descId = int(match.group(1))
            item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
            item["quantity"] = 1
        else:
            multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
            match = multiItemPattern.search(self.responseText)
            if match:
                descId = int(match.group(1))
                item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
                quantity = int(match.group(2).replace(',', ''))
                item["quantity"] = quantity
            else:
                raise Error.Error("Unknown error.", Error.REQUEST_GENERIC)

        # Check for an explosion
        if chefExplosionPattern.search(self.responseText):
            self.responseData["explosion"] = 1
            #TODO: Remove the items that came from the explosion

        self.responseData["food"] = item
Пример #35
0
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
Пример #36
0
def mergeItems():
    ItemDatabase.init()
    for i in range(len(_items)):
        item = _items[i]
        try:
            savedItem = ItemDatabase.getItemFromId(item["id"])

            for k,v in item.iteritems():
                if k != "enchantments" and k != "type":
                    savedItem[k] = v
            if "enchantments" in item and len(item["enchantments"]) > 0:
                if "enchantments" not in savedItem:
                    savedItem["enchantments"] = {}
                for k,v in item["enchantments"].iteritems():
                    savedItem["enchantments"][k] = v
            _items[i] = savedItem
        except Error.Error, inst:
            if inst.code == Error.ITEM_NOT_FOUND:
                r = ItemDescriptionRequest(_session, item["descId"])
                itemInfo = r.doRequest()
                for k,v in itemInfo.iteritems():
                    item[k] = v
            else:
                raise inst
Пример #37
0
    def parseResponse(self):
        super(InventoryRequest, self).parseResponse()

        items = []
        for itemId, quantity in self.jsonData.iteritems():
            if self.ignoreItemDatabase:
                item = {}
                item["id"] = int(itemId)
                item["quantity"] = int(quantity)
                items.append(item)
            else:
                item = ItemDatabase.getOrDiscoverItemFromId(int(itemId), self.session)
                item["quantity"] = int(quantity)
            items.append(item)

        self.responseData["items"] = items
Пример #38
0
    def parseResponse(self):
        super(InventoryRequest, self).parseResponse()

        items = []
        for itemId, quantity in self.jsonData.iteritems():
            if self.ignoreItemDatabase:
                item = {}
                item["id"] = int(itemId)
                item["quantity"] = int(quantity)
                items.append(item)
            else:
                item = ItemDatabase.getOrDiscoverItemFromId(
                    int(itemId), self.session)
                item["quantity"] = int(quantity)
            items.append(item)

        self.responseData["items"] = items
Пример #39
0
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
Пример #40
0
    def parseResponse(self):
        menuItemPattern = PatternManager.getOrCompilePattern("menuItem")
        cannotGoPattern = PatternManager.getOrCompilePattern("userShouldNotBeHere")

        if cannotGoPattern.search(self.responseText):
            raise Error.Error("You cannot reach that cafe.", Error.INVALID_LOCATION)

        items = []
        for match in menuItemPattern.finditer(self.responseText):
            descId = match.group(2)
            if descId.isdigit():
                descId = int(descId)
            item = ItemDatabase.getItemFromDescId(descId)
            items.append(item)

        if len(items) == 0:
            raise Error.Error("Retrieved an Empty Menu", Error.REQUEST_GENERIC)

        self.responseData["menu"] = items
Пример #41
0
	def parseResponse(self):
		menuItemPattern = PatternManager.getOrCompilePattern('menuItem')
		cannotGoPattern = PatternManager.getOrCompilePattern('userShouldNotBeHere')
		
		if cannotGoPattern.search(self.responseText):
			raise UserShouldNotBeHereError("You cannot reach that cafe")
		
		items = []
		for match in menuItemPattern.finditer(self.responseText):
			descId = match.group(2)
			if descId.isdigit():
				descId = int(descId)
				
			item = ItemDatabase.getItemFromDescId(descId, session=self.session)
			items.append(item)
		
		if len(items) == 0:
			raise RequestError("Retrieved an Empty Menu")
		
		self.responseData["menu"] = items
Пример #42
0
    def parseResponse(self):
        menuItemPattern = PatternManager.getOrCompilePattern('menuItem')
        cannotGoPattern = PatternManager.getOrCompilePattern('userShouldNotBeHere')

        if cannotGoPattern.search(self.responseText):
            raise UserShouldNotBeHereError("You cannot reach that cafe")

        items = []
        for match in menuItemPattern.finditer(self.responseText):
            descId = match.group(2)
            if descId.isdigit():
                descId = int(descId)

            item = ItemDatabase.getItemFromDescId(descId, session=self.session)
            items.append(item)

        if len(items) == 0:
            raise RequestError("Retrieved an Empty Menu")

        self.responseData["menu"] = items
Пример #43
0
    def parseResponse(self):
        menuItemPattern = PatternManager.getOrCompilePattern('menuItem')
        cannotGoPattern = PatternManager.getOrCompilePattern(
            'userShouldNotBeHere')

        if cannotGoPattern.search(self.responseText):
            raise Error.Error("You cannot reach that cafe.",
                              Error.INVALID_LOCATION)

        items = []
        for match in menuItemPattern.finditer(self.responseText):
            descId = match.group(2)
            if descId.isdigit():
                descId = int(descId)
            item = ItemDatabase.getItemFromDescId(descId)
            items.append(item)

        if len(items) == 0:
            raise Error.Error("Retrieved an Empty Menu", Error.REQUEST_GENERIC)

        self.responseData["menu"] = items
Пример #44
0
    def parseResponse(self):
        response = {}

        bountyAvailablePattern = PatternManager.getOrCompilePattern(
            'bountyAvailable')
        if bountyAvailablePattern.search(self.responseText):
            bountyAvailable = True
        else:
            bountyAvailable = False

        bountyChosenPattern = PatternManager.getOrCompilePattern(
            'bountyChosen')
        bountyActivePattern1 = PatternManager.getOrCompilePattern(
            'bountyActive1')
        bountyActivePattern2 = PatternManager.getOrCompilePattern(
            'bountyActive2')

        if bountyChosenPattern.search(self.responseText) or \
            bountyActivePattern1.search(self.responseText) or \
            bountyActivePattern2.search(self.responseText):
            bountyActive = True
        else:
            bountyActive = False

        dailyBounties = []
        if bountyAvailable:
            bountyPattern = PatternManager.getOrCompilePattern(
                'dailyBountyItem')
            for match in bountyPattern.finditer(self.responseText):
                itemId = int(match.group('itemid'))
                item = ItemDatabase.getItemFromId(itemId)
                dailyBounties.append(item)

        response['bountyAvailable'] = bountyAvailable
        response['bountyActive'] = bountyActive
        response['dailyBounties'] = dailyBounties

        self.responseData = response
Пример #45
0
    def parseResponse(self):
        """
        Searches backoffice.php for item name, quantity, price, limit, and ID.
        Returns the items with the usual keys in the item data base along with:

            quantity -- The number of the item in your mall store.
               price -- The price of the item in your mall store.
               limit -- The limit on the item in your mall store.
            cheapest -- The cheapest in mall. This includes limited items, use at own risk.
             orderId -- Item order in your store. 0 is the first listed and so on.
             
        RegExp match notes: Group 3,6,9, and 11 are garbage HTML data.
        """
        storeInventoryPattern = PatternManager.getOrCompilePattern(
            'storeInventory')

        items = []
        for match in storeInventoryPattern.finditer(self.responseText):
            descId = match.group(1)
            orderId = match.group(2)
            name = match.group(4)
            quantity = match.group(5)
            itemID = int(match.group(7))
            item = ItemDatabase.getOrDiscoverItemFromId(itemID, self.session)
            price = match.group(8)
            limit = int(match.group(10))
            cheapest = int(match.group(12))

            item["orderId"] = orderId
            item["quantity"] = quantity
            item["price"] = price
            item["limit"] = limit
            item["cheapest"] = cheapest
            items.append(item)

        self.responseData["items"] = items
Пример #46
0
 def parseResponse(self):
     # Check for items first
     items = []
     itemsAcquiredPattern = PatternManager.getOrCompilePattern("acquireItemFromItemUse")
     for match in itemsAcquiredPattern.finditer(self.responseText):
         itemID = int(match.group(1))
         item = ItemDatabase.getOrDiscoverItemFromId(itemID, self.session)
         items.append(item)
     if len(items):
         self.responseData["items"] = items
     
     # Check for meat gained
     gainMeatPattern = PatternManager.getOrCompilePattern("gainMeat")
     for match in gainMeatPattern.finditer(self.responseText):
         self.responseData["meat"] = match.group(1)
     
     # Check if we don't have the item
     notEnoughPattern = PatternManager.getOrCompilePattern("notEnoughItems")
     notEnoughMatch = notEnoughPattern.search(self.responseText)    
     if notEnoughMatch:
         raise Error.Error("You don't appear to have that item")
     
     if not len(self.responseData):
         print self.responseText
Пример #47
0
def makeItRain():
    for term in searchTerms:
        m = MallItemSearchRequest(s, pad(term))
        res = m.doRequest()["results"][0]
        curResult = [res["price"], res["quantity"], res["id"]]
        result[term] = curResult
        print "Booze: {0}, price: {1}, quantity: {2}".format(
            res["name"], res["price"], res["quantity"])
        curRecipe = recipe[term]
        total = 0
        recipeData = []
        for ingredient in curRecipe:
            m = MallItemSearchRequest(s, pad(ingredient))
            searchData = m.doRequest()
            recipeData.append(searchData["results"][0])
            price = searchData["results"][0]["price"]
            total += price
        if res["price"] > total:
            print "{0} should be crafted for profit. {0} has a total ingredient cost of {1}, but is selling for {2}".format(
                term, total, res["price"])
            if "limit" in recipeData[0] or "limit" in recipeData[1]:
                if "limit" in recipeData[0] and "limit" not in recipeData[1]:
                    if min(recipeData[0]["quantity"],
                           recipeData[1]["quantity"]) > recipeData[0]["limit"]:
                        print "minimum is greater than limit, must limit how much we buy for {0}".format(
                            term)
                        quantityOfEach = min(int(meatLimit / total),
                                             recipeData[0]["limit"])
                        buyItem(
                            recipeData[0]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[0]["name"])["id"], quantityOfEach,
                            recipeData[0]["price"])
                        buyItem(
                            recipeData[1]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[1]["name"])["id"], quantityOfEach,
                            recipeData[1]["price"])
                        if res["storeId"] == myStoreId:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), res["price"],
                                quantityOfEach)
                        else:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), (res["price"] - underCut),
                                quantityOfEach)
                    else:
                        print "Minimum less than limit for {0}".format(term)
                        quantityOfEach = min(
                            int(meatLimit / total),
                            min(recipeData[0]["quantity"],
                                recipeData[1]["quantity"]))
                        buyItem(
                            recipeData[0]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[0]["name"])["id"], quantityOfEach,
                            recipeData[0]["price"])
                        buyItem(
                            recipeData[1]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[1]["name"])["id"], quantityOfEach,
                            recipeData[1]["price"])
                        if res["storeId"] == myStoreId:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), res["price"],
                                quantityOfEach)
                        else:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), (res["price"] - underCut),
                                quantityOfEach)
                elif "limit" in recipeData[1] and "limit" not in recipeData[0]:
                    if min(recipeData[0]["quantity"],
                           recipeData[1]["quantity"]) > recipeData[1]["limit"]:
                        print "minimum is greater than limit, must limit how much we buy for {0}".format(
                            term)
                        quantityOfEach = min(int(meatLimit / total),
                                             recipeData[1]["limit"])
                        buyItem(
                            recipeData[0]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[0]["name"])["id"], quantityOfEach,
                            recipeData[0]["price"])
                        buyItem(
                            recipeData[1]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[1]["name"])["id"], quantityOfEach,
                            recipeData[1]["price"])
                        if res["storeId"] == myStoreId:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), res["price"],
                                quantityOfEach)
                        else:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), (res["price"] - underCut),
                                quantityOfEach)
                    else:
                        print "Minimum less than limit for {0}".format(term)
                        quantityOfEach = min(
                            int(meatLimit / total),
                            min(recipeData[0]["quantity"],
                                recipeData[1]["quantity"]))
                        buyItem(
                            recipeData[0]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[0]["name"])["id"], quantityOfEach,
                            recipeData[0]["price"])
                        buyItem(
                            recipeData[1]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[1]["name"])["id"], quantityOfEach,
                            recipeData[1]["price"])
                        if res["storeId"] == myStoreId:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), res["price"],
                                quantityOfEach)
                        else:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), (res["price"] - underCut),
                                quantityOfEach)
                elif "limit" in recipeData[1] and "limit" in recipeData[0]:
                    if min(recipeData[0]["quantity"],
                           recipeData[1]["quantity"]) > min(
                               recipeData[1]["limit"], recipeData[0]["limit"]):
                        print "minimum is greater than limit, must limit how much we buy for {0}".format(
                            term)
                        quantityOfEach = min(
                            int(meatLimit / total),
                            min(recipeData[1]["limit"],
                                recipeData[0]["limit"]))
                        buyItem(
                            recipeData[0]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[0]["name"])["id"], quantityOfEach,
                            recipeData[0]["price"])
                        buyItem(
                            recipeData[1]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[1]["name"])["id"], quantityOfEach,
                            recipeData[1]["price"])
                        if res["storeId"] == myStoreId:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), res["price"],
                                quantityOfEach)
                        else:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), (res["price"] - underCut),
                                quantityOfEach)
                    else:
                        print "Minimum less than limit for {0}".format(term)
                        quantityOfEach = min(
                            int(meatLimit / total),
                            min(recipeData[0]["quantity"],
                                recipeData[1]["quantity"]))
                        buyItem(
                            recipeData[0]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[0]["name"])["id"], quantityOfEach,
                            recipeData[0]["price"])
                        buyItem(
                            recipeData[1]["storeId"],
                            ItemDatabase.getItemFromName(
                                recipeData[1]["name"])["id"], quantityOfEach,
                            recipeData[1]["price"])
                        if res["storeId"] == myStoreId:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), res["price"],
                                quantityOfEach)
                        else:
                            sellItem(
                                craftItem(
                                    ItemDatabase.getItemFromName(
                                        recipeData[0]["name"])["id"],
                                    ItemDatabase.getItemFromName(
                                        recipeData[1]["name"])["id"],
                                    quantityOfEach), (res["price"] - underCut),
                                quantityOfEach)
            else:
                print "Ingredients not limited for {0}".format(term)
                quantityOfEach = min(
                    int(meatLimit / total),
                    min(recipeData[0]["quantity"], recipeData[1]["quantity"]))
                buyItem(
                    recipeData[0]["storeId"],
                    ItemDatabase.getItemFromName(recipeData[0]["name"])["id"],
                    quantityOfEach, recipeData[0]["price"])
                buyItem(
                    recipeData[1]["storeId"],
                    ItemDatabase.getItemFromName(recipeData[1]["name"])["id"],
                    quantityOfEach, recipeData[1]["price"])
                if res["storeId"] == myStoreId:
                    sellItem(
                        craftItem(
                            ItemDatabase.getItemFromName(
                                recipeData[0]["name"])["id"],
                            ItemDatabase.getItemFromName(
                                recipeData[1]["name"])["id"], quantityOfEach),
                        res["price"], quantityOfEach)
                else:
                    sellItem(
                        craftItem(
                            ItemDatabase.getItemFromName(
                                recipeData[0]["name"])["id"],
                            ItemDatabase.getItemFromName(
                                recipeData[1]["name"])["id"], quantityOfEach),
                        (res["price"] - underCut), quantityOfEach)
        else:
            print "{0} should NOT be crafted for profit. {0} has a total ingredient cost of {1}, but is selling for {2}".format(
                term, total, res["price"])
    def parseResponse(self):
        """
        Parse each different kind of trade. Each trade offer or offer and response is represented as a dictionary with following keys:
        
        tradeID:        The ID of the trade.
        tradeType:      The type of the trade - OUTGOING, INCOMING, etc.
        playerID:       The ID of the other player involved in this trade.
        playerName:     The name of the other player involved in this trade.
        incomingitems:  An array of items being offered to you in the format of a dictionary with keys itemID, quantity, and itemName.
        outgoingitems:  An array of items being offered to the other player in the format of a dictionary with keys itemID, quantity, and itemName.
        incomingmeat:   The amount of meat being offered by the other player.
        outgoingmeat:   The amount of meat being offered to the other player.
        message:        The message or note attached to the trade.
        """
        outgoingResponsePattern = PatternManager.getOrCompilePattern(
            'tradePendingResponseOutgoing')
        incomingResponsePattern = PatternManager.getOrCompilePattern(
            'tradePendingResponseIncoming')
        outgoingPattern = PatternManager.getOrCompilePattern(
            'tradePendingOfferOutgoing')
        incomingPattern = PatternManager.getOrCompilePattern(
            'tradePendingOfferIncoming')
        messagePattern = PatternManager.getOrCompilePattern('tradeMessage')
        itemPattern = PatternManager.getOrCompilePattern('tradeItem')

        tradeoffers = []

        iters = [
            incomingPattern.finditer(self.responseText),
            outgoingPattern.finditer(self.responseText),
            incomingResponsePattern.finditer(self.responseText),
            outgoingResponsePattern.finditer(self.responseText)
        ]
        for matchset in iters:
            for trade in matchset:
                tradeType = iters.index(matchset) + 1
                tradeID = trade.group('tradeid')
                playerID = trade.group('playerid')
                playerName = trade.group('playername')
                try:
                    incomingitems = trade.group(
                        'incomingitems')  #To be formatted later
                except:
                    incomingitems = None
                try:
                    outgoingitems = trade.group(
                        'outgoingitems')  #To be formatted later
                except:
                    outgoingitems = None
                try:
                    incomingmeat = int(trade.group('incomingmeat'))
                except:
                    incomingmeat = None
                try:
                    outgoingmeat = int(trade.group('outgoingmeat'))
                except:
                    outgoingmeat = None
                message = trade.group('message')  #To be formatted later
                iitems = []
                if incomingitems != None:
                    for item in itemPattern.finditer(incomingitems):
                        iitems.append({
                            'itemID':
                            item.group(
                                ItemDatabase.getItemFromDescId(
                                    item.group('itemdescid'))),
                            'itemName':
                            item.group(item.group('itemname')),
                            'quantity':
                            item.group('quantity')
                        })
                oitems = []
                if outgoingitems != None:
                    for item in itemPattern.finditer(outgoingitems):
                        oitems.append({
                            'itemID':
                            item.group(
                                ItemDatabase.getItemFromDescId(
                                    item.group('itemdescid'))),
                            'itemName':
                            item.group(item.group('itemname')),
                            'quantity':
                            item.group('quantity')
                        })
                try:
                    message = messagePattern.search(message).group('message')
                except:
                    message = None
                tradeoffers.append({
                    'tradeID': tradeID,
                    'tradeType': tradeType,
                    'playerID': playerID,
                    'playerName': playerName,
                    'incomingitems': iitems,
                    'outgoingitems': oitems,
                    'incomingmeat': incomingmeat,
                    'outgoingmeat': outgoingmeat,
                    'message': message,
                })
        self.responseData['trades'] = tradeoffers
Пример #49
0
    def parseResponse(self):
        """
        Parses through the response and constructs an array of messages.
        Each message is represented as a dictionary with the following
        keys:

              id -- The integer identifier for the message.
          userId -- The ID of the user who sent or received this message.
        userName -- The name of the user who sent or received this message.
            date -- The date the message was sent as a datetime object.
            text -- The contents of the message.
           items -- An array of items attached to the message.
            meat -- The amount of meat sent with the message.
        """

        fullMessagePattern = PatternManager.getOrCompilePattern('fullMessage')
        whitespacePattern = PatternManager.getOrCompilePattern('whitespace')
        singleItemPattern = PatternManager.getOrCompilePattern('acquireSingleItem')
        multiItemPattern = PatternManager.getOrCompilePattern('acquireMultipleItems')
        meatPattern = PatternManager.getOrCompilePattern('gainMeat')
        brickPattern = PatternManager.getOrCompilePattern('brickMessage')
        coffeePattern = PatternManager.getOrCompilePattern('coffeeMessage')
        candyHeartPattern = PatternManager.getOrCompilePattern('candyHeartMessage')

        messages = []

        for message in fullMessagePattern.finditer(self.responseText):
            messageId = int(message.group(1))
            userId = int(message.group(2))
            userName = message.group(3).strip()

            dateStr = message.group(4).strip()
            try:
                date = datetime.strptime(dateStr, "%A, %B %d, %Y, %I:%M%p")
            except ValueError:
                date = dateStr

            rawText = message.group(5).strip()
            index = rawText.find('<center')
            if index >= 0:
                text = rawText[:index].strip()
            else:
                text = rawText.strip()

            # Get rid of extraneous spaces, tabs, or new lines.
            text = text.replace("\r\n", "\n")
            text = whitespacePattern.sub(' ', text)
            text = text.replace("<br />\n", "\n")
            text = text.replace("<br/>\n", "\n")
            text = text.replace("<br>\n", "\n")
            text = text.replace("\n<br />", "\n")
            text = text.replace("\n<br/>", "\n")
            text = text.replace("\n<br>", "\n")
            text = text.replace("<br />", "\n")
            text = text.replace("<br/>", "\n")
            text = text.replace("<br>", "\n")
            text = text.strip()

            # KoL encodes all of the HTML entities in the message. Let's decode them to get the real text.
            text = StringUtils.htmlEntityDecode(text)

            m = {"id":messageId, "userId":userId, "userName":userName, "date":date, "text":text}

            # Find the items attached to the message.
            items = []
            for match in singleItemPattern.finditer(rawText):
                descId = int(match.group(1))
                try:
                    item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
                    item["quantity"] = 1
                    items.append(item)
                except Error.Error as e:
                    if e.code == Error.ITEM_NOT_FOUND and self._allowUnknown:
                        items.append({'id': None, 
                                      'quantity': 1, 
                                      'descId': descId})
                    else:
                        raise
            for match in multiItemPattern.finditer(rawText):
                descId = int(match.group(1))
                quantity = int(match.group(2).replace(',', ''))
                try:
                    item = ItemDatabase.getOrDiscoverItemFromDescId(descId, self.session)
                    item["quantity"] = quantity
                    items.append(item)
                except Error.Error as e:
                    if e.code == Error.ITEM_NOT_FOUND and self._allowUnknown:
                        items.append({'id': None, 
                                      'quantity': quantity, 
                                      'descId': descId})
                    else:
                        raise
            m["items"] = items

            # Find how much meat was attached to the message.
            meat = 0
            meatMatch = meatPattern.search(rawText)
            if meatMatch:
                meat = int(meatMatch.group(1).replace(',', ''))
            m["meat"] = meat

            # Handle special messages.
            if brickPattern.search(rawText):
                m["messageType"] = "brick"
            elif coffeePattern.search(rawText):
                m["messageType"] = "coffeeCup"
            elif candyHeartPattern.search(rawText):
                m["messageType"] = "candyHeart"
            else:
                m["messageType"] = "normal"

            messages.append(m)

        self.responseData["kmails"] = messages
Пример #50
0
    def parseResponse(self):
        """
        Parses through the response and constructs an array of messages.
        Each message is represented as a dictionary with the following
        keys:

              id -- The integer identifier for the message.
          userId -- The ID of the user who sent or received this message.
        userName -- The name of the user who sent or received this message.
            date -- The date the message was sent as a datetime object.
            text -- The contents of the message.
           items -- An array of items attached to the message.
            meat -- The amount of meat sent with the message.
        """

        fullMessagePattern = PatternManager.getOrCompilePattern('fullMessage')
        whitespacePattern = PatternManager.getOrCompilePattern('whitespace')
        singleItemPattern = PatternManager.getOrCompilePattern(
            'acquireSingleItem')
        multiItemPattern = PatternManager.getOrCompilePattern(
            'acquireMultipleItems')
        meatPattern = PatternManager.getOrCompilePattern('gainMeat')
        brickPattern = PatternManager.getOrCompilePattern('brickMessage')
        coffeePattern = PatternManager.getOrCompilePattern('coffeeMessage')
        candyHeartPattern = PatternManager.getOrCompilePattern(
            'candyHeartMessage')

        _linkParser = re.compile(
            r'<a target=_blank href="([^"]*)"><font color=blue>\[link\]</font></a>'
        )

        messages = []

        for message in fullMessagePattern.finditer(self.responseText):
            messageId = int(message.group(1))
            userId = int(message.group(2))
            userName = message.group(3).strip()

            dateStr = message.group(4).strip()
            try:
                date = datetime.strptime(dateStr, "%A, %B %d, %Y, %I:%M%p")
            except ValueError:
                date = dateStr

            rawText = message.group(5).strip()
            index = rawText.find('<center')
            if index >= 0:
                text = rawText[:index].strip()
            else:
                text = rawText.strip()

            # Get rid of extraneous spaces, tabs, or new lines.
            text = text.replace("\r\n", "\n")
            text = whitespacePattern.sub(' ', text)
            text = text.replace("<br />\n", "\n")
            text = text.replace("<br/>\n", "\n")
            text = text.replace("<br>\n", "\n")
            text = text.replace("\n<br />", "\n")
            text = text.replace("\n<br/>", "\n")
            text = text.replace("\n<br>", "\n")
            text = text.replace("<br />", "\n")
            text = text.replace("<br/>", "\n")
            text = text.replace("<br>", "\n")
            text = text.strip()

            # parse links
            oldText, text = text, ""
            curPos = 0
            curMatch = _linkParser.search(oldText)
            while curMatch is not None and curPos <= len(oldText):
                toAdd = ""
                oldPos = curPos
                matchStart = curMatch.start()
                link = curMatch.group(1)
                if curPos < matchStart:
                    toAdd += oldText[curPos:matchStart]
                toAdd += link

                # remove the link text, which may have spaces
                curPos = curMatch.end()
                while link:
                    curChar = oldText[curPos]
                    if curChar in whitespace:
                        curPos += 1
                    elif curChar == link[0]:
                        link = link[1:]
                        curPos += 1
                    else:
                        # ran into a match error -- roll back everything
                        toAdd = oldText[oldPos:matchStart + 1]
                        curPos = matchStart + 1
                        break
                text += toAdd
                toAdd = ""
                curMatch = _linkParser.search(oldText, pos=curPos)
            text += oldText[curPos:]

            # KoL encodes all of the HTML entities in the message. Let's decode them to get the real text.
            text = StringUtils.htmlEntityDecode(text)

            m = {
                "id": messageId,
                "userId": userId,
                "userName": userName,
                "date": date,
                "text": text
            }

            # Find the items attached to the message.
            items = []
            for match in singleItemPattern.finditer(rawText):
                descId = int(match.group(1))
                try:
                    item = ItemDatabase.getOrDiscoverItemFromDescId(
                        descId, self.session)
                    item["quantity"] = 1
                    items.append(item)
                except Error.Error as e:
                    if e.code == Error.ITEM_NOT_FOUND and self._allowUnknown:
                        items.append({
                            'id': None,
                            'quantity': 1,
                            'descId': descId
                        })
                    else:
                        raise
            for match in multiItemPattern.finditer(rawText):
                descId = int(match.group(1))
                quantity = int(match.group(2).replace(',', ''))
                try:
                    item = ItemDatabase.getOrDiscoverItemFromDescId(
                        descId, self.session)
                    item["quantity"] = quantity
                    items.append(item)
                except Error.Error as e:
                    if e.code == Error.ITEM_NOT_FOUND and self._allowUnknown:
                        items.append({
                            'id': None,
                            'quantity': quantity,
                            'descId': descId
                        })
                    else:
                        raise
            m["items"] = items

            # Find how much meat was attached to the message.
            meat = 0
            meatMatch = meatPattern.search(rawText)
            if meatMatch:
                meat = int(meatMatch.group(1).replace(',', ''))
            m["meat"] = meat

            # Handle special messages.
            if brickPattern.search(rawText):
                m["messageType"] = "brick"
            elif coffeePattern.search(rawText):
                m["messageType"] = "coffeeCup"
            elif candyHeartPattern.search(rawText):
                m["messageType"] = "candyHeart"
            else:
                m["messageType"] = "normal"

            messages.append(m)

        self.responseData["kmails"] = messages
Пример #51
0
 def runTest(self):
     ItemDatabase.init()
Пример #52
0
any other action instead.

We'll skip reading your mail in this example, since it's no different.
"""

from kol.Session import Session
from kol.database import ItemDatabase
from kol.request.Item import PulverizeRequest, UseItemRequest
import kol.Error as Error

print "Logging into the KoL Servers..."
session = Session("username", "swordfish")

print "Using an old coin purse:"
try:
    item = ItemDatabase.getItemByName("old coin purse")
    use_request = UseItemRequest(session, item["id"])
    print "Got %s meat from old coin purse" % use_request.responseData["meat"]
except Error.Error, e:
    if e.code == Error.NOT_ENOUGH_ITEMS:
        print "Whoops!  You didn't have an old coin purse to use...", e.message
    else:
        #we can raise the error again to stop the script:
        raise e

print "Smashing a titanium assault umbrella:"
try:
    item = ItemDatabase.getItemByName("titanium assault umbrella")
    pulverize = PulverizeRequest(session, item["id"])
    print "After smashing the item you have received the following:"
    for result in pulverize.responseData["results"]:
Пример #53
0
    def parseResponse(self):
        hatPattern = PatternManager.getOrCompilePattern("currentHat")
        weaponPattern = PatternManager.getOrCompilePattern("currentWeapon")
        offhandPattern = PatternManager.getOrCompilePattern("currentOffhand")
        shirtPattern = PatternManager.getOrCompilePattern("currentShirt")
        pantsPattern = PatternManager.getOrCompilePattern("currentPants")
        accPattern = PatternManager.getOrCompilePattern("currentAcc")
        acc1Pattern = PatternManager.getOrCompilePattern("currentAcc1")
        acc2Pattern = PatternManager.getOrCompilePattern("currentAcc2")
        acc3Pattern = PatternManager.getOrCompilePattern("currentAcc3")
        familiarPattern = PatternManager.getOrCompilePattern("currentFam")

        hatText = hatPattern.search(self.responseText)
        if hatText:
            self.responseData["hat"] = ItemDatabase.getItemFromDescId(
                int(hatText.group(1)), self.session)

        weaponText = weaponPattern.search(self.responseText)
        if weaponText:
            self.responseData["weapon"] = ItemDatabase.getItemFromDescId(
                int(weaponText.group(1)), self.session)

        offhandText = offhandPattern.search(self.responseText)
        if offhandText:
            self.responseData["offhand"] = ItemDatabase.getItemFromDescId(
                int(offhandText.group(1)), self.session)

        shirtText = shirtPattern.search(self.responseText)
        if shirtText:
            self.responseData["shirt"] = ItemDatabase.getItemFromDescId(
                int(shirtText.group(1)), self.session)

        pantsText = pantsPattern.search(self.responseText)
        if pantsText:
            self.responseData["pants"] = ItemDatabase.getItemFromDescId(
                int(pantsText.group(1)), self.session)

        accessories = []
        accText = accPattern.search(self.responseText)
        if accText:
            for match in accPattern.finditer(self.responseText):
                item = ItemDatabase.getItemFromDescId(int(match.group(1)),
                                                      self.session)
                item["slot"] = 0
                accessories.append(item)
        else:
            acc1Text = acc1Pattern.search(self.responseText)
            if acc1Text:
                item = ItemDatabase.getItemFromDescId(int(acc1Text.group(1)),
                                                      self.session)
                item["slot"] = 1
                accessories.append(item)
            acc2Text = acc2Pattern.search(self.responseText)
            if acc2Text:
                item = ItemDatabase.getItemFromDescId(int(acc2Text.group(1)),
                                                      self.session)
                item["slot"] = 2
                accessories.append(item)
            acc3Text = acc3Pattern.search(self.responseText)
            if acc3Text:
                item = ItemDatabase.getItemFromDescId(int(acc3Text.group(1)),
                                                      self.session)
                item["slot"] = 3
                accessories.append(item)
        if len(accessories) > 0:
            self.responseData["acc"] = accessories

        famText = familiarPattern.search(self.responseText)
        if famText:
            self.responseData["familiar"] = ItemDatabase.getItemFromDescId(
                int(famText.group(1)), self.session)
Пример #54
0
    def parseResponse(self):
        """
        Parses through the response and constructs an array of messages.
        Each message is represented as a dictionary with the following
        keys:

              id -- The integer identifier for the message.
          userId -- The ID of the user who sent or received this message.
        userName -- The name of the user who sent or received this message.
            date -- The date the message was sent as a datetime object.
            text -- The contents of the message.
           items -- An array of items attached to the message.
            meat -- The amount of meat sent with the message.
        """

        fullMessagePattern = PatternManager.getOrCompilePattern('fullMessage')
        whitespacePattern = PatternManager.getOrCompilePattern('whitespace')
        singleItemPattern = PatternManager.getOrCompilePattern(
            'acquireSingleItem')
        multiItemPattern = PatternManager.getOrCompilePattern(
            'acquireMultipleItems')
        meatPattern = PatternManager.getOrCompilePattern('gainMeat')
        brickPattern = PatternManager.getOrCompilePattern('brickMessage')
        coffeePattern = PatternManager.getOrCompilePattern('coffeeMessage')
        candyHeartPattern = PatternManager.getOrCompilePattern(
            'candyHeartMessage')

        messages = []

        for message in fullMessagePattern.finditer(self.responseText):
            messageId = int(message.group(1))
            userId = int(message.group(2))
            userName = message.group(3).strip()

            dateStr = message.group(4).strip()
            try:
                date = datetime.strptime(dateStr, "%A, %B %d, %Y, %I:%M%p")
            except ValueError:
                date = dateStr

            rawText = message.group(5).strip()
            index = rawText.find('<center')
            if index >= 0:
                text = rawText[:index].strip()
            else:
                text = rawText.strip()

            # Get rid of extraneous spaces, tabs, or new lines.
            text = text.replace("\r\n", "\n")
            text = whitespacePattern.sub(' ', text)
            text = text.replace("<br />\n", "\n")
            text = text.replace("<br/>\n", "\n")
            text = text.replace("<br>\n", "\n")
            text = text.replace("\n<br />", "\n")
            text = text.replace("\n<br/>", "\n")
            text = text.replace("\n<br>", "\n")
            text = text.replace("<br />", "\n")
            text = text.replace("<br/>", "\n")
            text = text.replace("<br>", "\n")
            text = text.strip()

            # KoL encodes all of the HTML entities in the message. Let's decode them to get the real text.
            text = StringUtils.htmlEntityDecode(text)

            m = {
                "id": messageId,
                "userId": userId,
                "userName": userName,
                "date": date,
                "text": text
            }

            # Find the items attached to the message.
            items = []
            for match in singleItemPattern.finditer(rawText):
                descId = int(match.group(1))
                try:
                    item = ItemDatabase.getOrDiscoverItemFromDescId(
                        descId, self.session)
                    item["quantity"] = 1
                    items.append(item)
                except Error.Error as e:
                    if e.code == Error.ITEM_NOT_FOUND and self._allowUnknown:
                        items.append({
                            'id': None,
                            'quantity': 1,
                            'descId': descId
                        })
                    else:
                        raise
            for match in multiItemPattern.finditer(rawText):
                descId = int(match.group(1))
                quantity = int(match.group(2).replace(',', ''))
                try:
                    item = ItemDatabase.getOrDiscoverItemFromDescId(
                        descId, self.session)
                    item["quantity"] = quantity
                    items.append(item)
                except Error.Error as e:
                    if e.code == Error.ITEM_NOT_FOUND and self._allowUnknown:
                        items.append({
                            'id': None,
                            'quantity': quantity,
                            'descId': descId
                        })
                    else:
                        raise
            m["items"] = items

            # Find how much meat was attached to the message.
            meat = 0
            meatMatch = meatPattern.search(rawText)
            if meatMatch:
                meat = int(meatMatch.group(1).replace(',', ''))
            m["meat"] = meat

            # Handle special messages.
            if brickPattern.search(rawText):
                m["messageType"] = "brick"
            elif coffeePattern.search(rawText):
                m["messageType"] = "coffeeCup"
            elif candyHeartPattern.search(rawText):
                m["messageType"] = "candyHeart"
            else:
                m["messageType"] = "normal"

            messages.append(m)

        self.responseData["kmails"] = messages
Пример #55
0
	def parseResponse(self):
		hatPattern = PatternManager.getOrCompilePattern("currentHat")
		weaponPattern = PatternManager.getOrCompilePattern("currentWeapon")
		offhandPattern = PatternManager.getOrCompilePattern("currentOffhand")
		shirtPattern = PatternManager.getOrCompilePattern("currentShirt")
		pantsPattern = PatternManager.getOrCompilePattern("currentPants")
		accPattern = PatternManager.getOrCompilePattern("currentAcc")
		acc1Pattern = PatternManager.getOrCompilePattern("currentAcc1")
		acc2Pattern = PatternManager.getOrCompilePattern("currentAcc2")
		acc3Pattern = PatternManager.getOrCompilePattern("currentAcc3")
		familiarPattern = PatternManager.getOrCompilePattern("currentFam")
		
		hatText = hatPattern.search(self.responseText)
		if hatText:
			self.responseData["hat"] = ItemDatabase.getItemFromDescId(int(hatText.group(1)), self.session)

		weaponText = weaponPattern.search(self.responseText)
		if weaponText:
			self.responseData["weapon"] = ItemDatabase.getItemFromDescId(int(weaponText.group(1)), self.session)
		
		offhandText = offhandPattern.search(self.responseText)
		if offhandText:
			self.responseData["offhand"] = ItemDatabase.getItemFromDescId(int(offhandText.group(1)), self.session)
		
		shirtText = shirtPattern.search(self.responseText)
		if shirtText:
			self.responseData["shirt"] = ItemDatabase.getItemFromDescId(int(shirtText.group(1)), self.session)
		
		pantsText = pantsPattern.search(self.responseText)
		if pantsText:
			self.responseData["pants"] = ItemDatabase.getItemFromDescId(int(pantsText.group(1)), self.session)
		
		accessories = []
		accText = accPattern.search(self.responseText)
		if accText:
			for match in accPattern.finditer(self.responseText):
				item = ItemDatabase.getItemFromDescId(int(match.group(1)), self.session)
				item["slot"] = 0
				accessories.append(item)
		else:
			acc1Text = acc1Pattern.search(self.responseText)
			if acc1Text:
				item = ItemDatabase.getItemFromDescId(int(acc1Text.group(1)), self.session)
				item["slot"] = 1
				accessories.append(item)
			acc2Text = acc2Pattern.search(self.responseText)
			if acc2Text:
				item = ItemDatabase.getItemFromDescId(int(acc2Text.group(1)), self.session)
				item["slot"] = 2
				accessories.append(item)
			acc3Text = acc3Pattern.search(self.responseText)
			if acc3Text:
				item = ItemDatabase.getItemFromDescId(int(acc3Text.group(1)), self.session)
				item["slot"] = 3
				accessories.append(item)
		if len(accessories) > 0:
			self.responseData["acc"] = accessories
			
		famText = familiarPattern.search(self.responseText)
		if famText:
			self.responseData["familiar"] = ItemDatabase.getItemFromDescId(int(famText.group(1)), self.session)