コード例 #1
0
ファイル: signbot.py プロジェクト: Cairnarvon/SignBot
    def __change_avatar(self, potion, pname, pid):
        try:
            # Find the IDs of the hard-shruggable effects we're under
            url = 'http://www.kingdomofloathing.com/charpane.php'
            pane = self.__session.opener.open(url, {}).text
            effects = [int(e) for e in re.findall('return hardshrug\((\d+),',
                                                  pane)]

            # Uneffect all active avatar potions
            for effect in avatar_potions.values():
                if effect in effects:
                    UneffectRequest(self.__session, effect).doRequest()
                    self.log("Uneffected ID #{}.".format(effect))

            # Use the new one and inform the person
            UseItemRequest(self.__session, potion).doRequest()
            self.log("Used avatar potion #{}.".format(potion))
            self.__chat_say(pname, pid, "Look at me!")
        except Error:
            try:
                self.__send_kmail(pname, pid,
                    "I couldn't use that avatar potion so I'm returning it.",
                    potion)
            except:
                self.__chat_say(pname, pid,
                    "I couldn't use that avatar potion and I couldn't return "
                    "it to you. Sorry.")
コード例 #2
0
ファイル: HealingModule.py プロジェクト: psudopixel/cwbot-ndy
    def heal(self, hint, args, status):
        currentVal = status[args['type']]
        n = 1
        if self._seen > 10:
            self.parent.debugLog("Using estimate for multi-use")
            maxPotential = self._itemMaxHealPoints
            n = int(max(1, math.floor(hint / maxPotential)))
        with InventoryLock.lock:
            invMan = self.parent.inventoryManager
            invMan.refreshInventory()
            inv = invMan.inventory()
            qtyInInventory = inv.get(self.id, 0)
            if qtyInInventory == 0:
                if self.buyFrom is None:
                    self.parent.log("Out of item {}".format(self.id))
                    return
            if qtyInInventory < n:
                if self.buyFrom is not None:
                    if self.buyFrom.lower() == "mall":
                        try:
                            buyFromMall(self.parent.session, self.id,
                                        n - qtyInInventory, 0, self.parent.log)
                        except kol.Error.Error:
                            pass
                    else:
                        r1 = StoreRequest(self.parent.session,
                                          self.buyFrom,
                                          self.id,
                                          quantity=(n - qtyInInventory))
                        tryRequest(r1, nothrow=True, numTries=1)
                    invMan.refreshInventory()
                    inv = invMan.inventory()
                    qtyInInventory = inv.get(self.id, 0)
                    if qtyInInventory == 0:
                        self.parent.log("Couldn't buy item {}".format(self.id))
                        return
            r2 = UseItemRequest(self.parent.session, self.id)
            try:
                toUse = min(n, qtyInInventory)
                for _ in range(toUse):
                    tryRequest(r2, numTries=1)

                # update "best seen value"
                if toUse == 1:
                    status = self.parent.hpMpStatus()
                    newVal = status[args['type']]
                    if (newVal != status['max' + args['type']]
                            and newVal > currentVal):
                        self._seen += 1
                        self._itemMaxHealPoints = max(self._itemMaxHealPoints,
                                                      newVal - currentVal)
                        self.parent.log(
                            "New estimate for {}: heals {} {}".format(
                                self, self._itemMaxHealPoints, args['type']))
            except kol.Error.Error:
                self.parent.log("Failed to use item {}".format(self.id))
コード例 #3
0
    def openAllGiftPackages(self):
        giftPackages = {}

        # Get a list of all gift packages in our inventory.
        r = InventoryRequest(self.session, which=3)
        responseData = r.doRequest()
        items = responseData["items"]
        for item in items:
            if "type" in item and item["type"] == "gift package":
                giftPackages[item["id"]] = item["quantity"]

        # Open all of the gift packages.
        for itemId, quantity in giftPackages.iteritems():
            for i in range(quantity):
                r = UseItemRequest(self.session, itemId)
                r.doRequest()
コード例 #4
0
    def openAllGiftPackages(self):
        with self.__lock:
            Report.trace("kmail", "Opening gift package(s).")
            giftPackages = {}

            # Get a list of all gift packages in our inventory.
            r = InventoryRequest(self.session)
            responseData = tryRequest(r)
            items = responseData["items"]
            for item in items:
                if "type" in item and item["type"] == "gift package":
                    giftPackages[item["id"]] = item["quantity"]

            # Open all of the gift packages.
            for itemId, quantity in giftPackages.iteritems():
                for _i in range(quantity):
                    r = UseItemRequest(self.session, itemId)
                    tryRequest(r)
コード例 #5
0
 def __init__(self, parent, name, iData, config):
     """ Initialize the manager """
     self._playerDb = None
     self._numChanges = 0
     self._ready = False
     self._otherBots = None
     self._myFreq = None
     self._numPlayersForFreqChange = None
     self._freqChangeTimeout = None
     self._format, self._emoteFormat = None, None
     super(WalkieTalkieRepeater, self).__init__(parent, name, iData, config)
     self._invMan.refreshInventory()
     self._lastOutsiderCheck = 0
     self._changeFreqRequests = {}
     inventory = self._invMan.inventory()
     numTalkies = inventory.get(6846, 0)
     if numTalkies == 0:
         numUnusedTalkies = inventory.get(6845, 0)
         if numUnusedTalkies > 0:
             try:
                 r = UseItemRequest(self._s, 6845)
                 d = tryRequest(r)
                 numTalkies = 1
             except Error:
                 raise FatalError("Could not use unused walkie talkie.")
         else:
             raise FatalError("Cannot use WalkieTalkieRepeater with "
                              "no walkie talkie!")
     replies = self.sendChatMessage("/kenneth",
                                    None,
                                    waitForReply=True,
                                    raw=True)
     for reply in replies:
         txt = reply['text']
         freq = re.search(r"The frequency is (\d+.\d), Mr. Rather", txt)
         if freq:
             self._myFreq = freq.group(1)
             self._log.info("My walkie talkie frequency is {}".format(
                 freq.group(1)))
     if self._myFreq is None:
         raise RuntimeError("Could not determine walkie talkie frequency.")
     self._ready = True
コード例 #6
0
ファイル: HealingModule.py プロジェクト: psudopixel/cwbot-ndy
 def heal(self, hint, args, status):
     if self.type == 'tonic':
         rMp = GalaktikRequest(self.parent.session, False, hint)
         tryRequest(rMp)
         return
     elif self.type == 'nostrum':
         rHp = GalaktikRequest(self.parent.session, True, hint)
         tryRequest(rHp)
         return
     with InventoryLock.lock:
         n = int(max(1, math.floor(hint / 10.0)))
         invMan = self.parent.inventoryManager
         invMan.refreshInventory()
         inv = invMan.inventory()
         myQty = inv.get(232, 0)
         if myQty < n:
             rBuy = GalaktikBuyRequest(self.parent.session, 232, n - myQty)
             tryRequest(rBuy, nothrow=True)
         rUse = UseItemRequest(self.parent.session, 232)
         try:
             for _ in range(n):
                 tryRequest(rUse)
         except kol.Error.Error:
             pass
コード例 #7
0
ファイル: main.py プロジェクト: KevZho/buffbot
def doStuff():
	logging.debug("doStuff()")
	s = Session()
	try:
		c1 = cookielib.Cookie(None, "PHPSESSID", memcache.get("PHPSESSID"), None, False, memcache.get("domain0"), True, False, memcache.get("path0"), True, False, None, False, None, False, None, False)
		jar = cookielib.CookieJar()
		jar.set_cookie(c1)
		c2 = cookielib.Cookie(None, "appserver", memcache.get("appserver"), None, False, memcache.get("domain1"), True, False, memcache.get("path1"), True, False, None, False, None, False, None, False)
		jar.set_cookie(c2)
		s.cj = jar

		s.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(s.cj))
		s.isConnected = memcache.get("isConnected")
		s.userId = memcache.get("userId")
		s.userName = memcache.get("userName")
		s.userPasswordHash = memcache.get("userPasswordHash")
		s.serverURL = memcache.get("serverURL")
		s.pwd = memcache.get("pwd")
		s.rollover = memcache.get("rollover")
	except:
		logging.error("some memcache keys were deleted")

	m = None
	messages = None

	try:
		m = GetMessagesRequest(s)
		messages = m.doRequest()
	except:
		logging.warn("Not logged in, logging in")
		memcache.flush_all()
		s = Session()
		s.login(Data.USERNAME, Data.PASSWORD)

		memcache.add(key="isConnected", value=bool(s.isConnected))
		memcache.add(key="userId", value=int(s.userId))
		memcache.add(key="userName", value=str(s.userName))
		memcache.add(key="userPasswordHash", value=str(s.userPasswordHash))
		memcache.add(key="serverURL", value=str(s.serverURL))
		memcache.add(key="pwd", value=str(s.pwd))
		memcache.add(key="rollover", value=int(s.rollover))

		i = 0
		for cookie in s.cj:
			logging.info("%s=%s" % (cookie.name, cookie.value))
			memcache.add(key=cookie.name,value=str(cookie.value))
			memcache.add(key="domain%d" % i, value=str(cookie.domain))
			memcache.add(key="path%d" % i, value=str(cookie.path))
			i += 1

		m = GetMessagesRequest(s)
		messages = m.doRequest()

	for kmail in messages["kmails"]:
		logging.info("%s sent kmail with text %s" % (kmail["userName"], kmail["text"]))

		msg = kmail["text"].split("\n")
		totalMP = 0
		totalCost = 0
		buffsCast = []

		for randomBuff in msg:
			specialCase = False
			specialUID = None
			info = randomBuff.split(" ")
			buff = ""
			duration = 0

			if not info[0].isdigit():
				if info[0] == Data.secretKey:
					specialCase = True
					specialUID = int(info[1])
				else:
					logging.info("No duration set")
					buff = " ".join(info)
					logging.info("Need to interpret %s" % buff)
					duration = 50
			else:
				logging.info("Duration set for %d" % int(info[0]))
				buff = " ".join(info)[len(info[0]) + 1:]
				logging.info("Need to interpret %s" % buff)

				duration = int(info[0]) if int(info[0]) < Data.MAXLENGTH else Data.MAXLENGTH

			if specialCase:
				if len(info) >= 3:
					if not info[2].isdigit():
						logging.info("No duration set")
						buff = " ".join(info)[len(info[0]) + len(info[1]) + 2:]
						logging.info("Need to interpret %s" % buff)
						duration = 50
					else:
						logging.info("Duration set for %d" % int(info[2]))
						buff = " ".join(info)[len(info[0]) + len(info[1]) + len(info[2]) + 3:]
						logging.info("Need to interpret %s" % buff)

						duration = int(info[2]) if int(info[2]) < Data.MAXLENGTH else Data.MAXLENGTH

			theBuff = None
			for key in Data.buffs.keys():
				if buff.lower() in key.lower():
					theBuff = Data.buffs[key]
					logging.info("keyword '{0}' matched for {1}".format(buff, key))

			if theBuff is not None and buff != "":
				shouldBuff = True
				c = CharpaneRequest(s)
				charData = c.doRequest()

				currentMP = charData["currentMP"]
				timesNeeded = int(math.ceil(float(duration)/float(Data.ACCORDION_DURATION)))

				logging.info("Current: MP: {0}, meat: {1}".format(currentMP, charData["meat"]))
				logging.info("Current MP: {0}, Need: {1}".format(currentMP, (theBuff["mp"] - Data.MPCOSTREDUCTION) * timesNeeded))

				if "once" not in theBuff:
					while currentMP < (theBuff["mp"] - Data.MPCOSTREDUCTION) * timesNeeded < charData["maxMP"]:
						if currentMP > (theBuff["mp"] - Data.MPCOSTREDUCTION) * timesNeeded:
							logging.error("Should not be here!")
							break
						if charData["meat"] > 94:
							logging.warn("Out of MP. Buying mystery juice")
							store = StoreRequest(s, 2, 518)
							try:
								store.doRequest()
							except:
								logging.error("dc'ed from server")
								s = Session()
								memcache.flush_all()
								s.login(Data.USERNAME, Data.PASSWORD)
								store.doRequest()
								memcache.add(key="isConnected", value=bool(s.isConnected))
								memcache.add(key="userId", value=int(s.userId))
								memcache.add(key="userName", value=str(s.userName))
								memcache.add(key="userPasswordHash", value=str(s.userPasswordHash))
								memcache.add(key="serverURL", value=str(s.serverURL))
								memcache.add(key="pwd", value=str(s.pwd))
								memcache.add(key="rollover", value=int(s.rollover))
								i = 0
								for cookie in s.cj:
									logging.info("%s=%s" % (cookie.name, cookie.value))
									memcache.add(key=cookie.name,value=str(cookie.value))
									memcache.add(key="domain%d" % i, value=str(cookie.domain))
									memcache.add(key="path%d" % i, value=str(cookie.path))
									i += 1

							u = UseItemRequest(s, 518)
							u.doRequest()
							totalCost += 95
							currentMP = c.doRequest()["currentMP"]
						else:
							logging.error("No meat or MP, stopping")
							shouldBuff = False
							break
				else:
					while currentMP < (theBuff["mp"] - Data.MPCOSTREDUCTION) < charData["maxMP"]:
						if currentMP > (theBuff["mp"] - Data.MPCOSTREDUCTION):
							logging.error("Should not be here!")
							break
						if charData["meat"] > 94:
							logging.warn("Out of MP. Buying mystery juice")
							store = StoreRequest(s, 2, 518)
							try:
								store.doRequest()
							except:
								logging.error("dc'ed from server")
								s = Session()
								memcache.flush_all()
								s.login(Data.USERNAME, Data.PASSWORD)
								store.doRequest()
								memcache.add(key="isConnected", value=bool(s.isConnected))
								memcache.add(key="userId", value=int(s.userId))
								memcache.add(key="userName", value=str(s.userName))
								memcache.add(key="userPasswordHash", value=str(s.userPasswordHash))
								memcache.add(key="serverURL", value=str(s.serverURL))
								memcache.add(key="pwd", value=str(s.pwd))
								memcache.add(key="rollover", value=int(s.rollover))
								i = 0
								for cookie in s.cj:
									logging.info("%s=%s" % (cookie.name, cookie.value))
									memcache.add(key=cookie.name,value=str(cookie.value))
									memcache.add(key="domain%d" % i, value=str(cookie.domain))
									memcache.add(key="path%d" % i, value=str(cookie.path))
									i += 1

							u = UseItemRequest(s, 518)
							u.doRequest()
							totalCost += 95
							currentMP = c.doRequest()["currentMP"]
						else:
							logging.error("No meat or MP, stopping")
							shouldBuff = False
							break

				if shouldBuff and theBuff["available"] and (theBuff["mp"] - Data.MPCOSTREDUCTION) * timesNeeded < charData["maxMP"]:
					if not specialCase:
						skill = UseSkillRequest(s, theBuff["id"], 1, kmail["userId"]) if "once" in theBuff else UseSkillRequest(s, theBuff["id"], timesNeeded, kmail["userId"])

						logging.info("Buffing %s with %s" % (kmail["userName"], getSkillFromId(theBuff["id"])["name"]))

						try:
							skill.doRequest()
							totalMP += (theBuff["mp"] - Data.MPCOSTREDUCTION) * timesNeeded
							buffsCast.append(theBuff["id"])
						except:
							logging.fatal("Casting error for KMail request.")
					else:
						skill = UseSkillRequest(s, theBuff["id"], 1, specialUID) if "once" in theBuff else UseSkillRequest(s, theBuff["id"], timesNeeded, specialUID)

						logging.info("Buffing %s with %s" % (specialUID, getSkillFromId(theBuff["id"])["name"]))

						try:
							skill.doRequest()
							totalMP += (theBuff["mp"] - Data.MPCOSTREDUCTION) * timesNeeded
							buffsCast.append(theBuff["id"])
						except:
							logging.fatal("Casting error for web interface request.")
			else:
				logging.warn("No buff found matching %s" % buff)

		msg = None
		if not specialCase:
			msg = {
				"userId": kmail["userId"],
				"text": "Thanks for using BuffBot!\nTotal MP used: {0}\nTotal meat spent on magical mystery juice: {1}".format(totalMP, totalCost)
			}
		else:
			msg = {
				"userId": specialUID,
				"text": "Thanks for using BuffBot!\nTotal MP used: {0}\nTotal meat spent on magical mystery juice: {1}".format(totalMP, totalCost)
			}

		for someBuff in buffsCast:
			msg["text"] += "\nGave buff: %s" % getSkillFromId(someBuff)["name"]

		if len(buffsCast) > 0:
			send = SendMessageRequest(s, msg)
			send.doRequest()
			logging.info("KMail sent")
		else:
			if not specialCase:
				msg = {
					"userId": kmail["userId"],
					"text": "Thanks for using BuffBot!\nEither one of two things happened:\n1. BuffBot ran out of meat and MP, so it couldn't complete your request. Please send some meat next time for some magical mystery juice if this is the case.\n2. BuffBot did not know how to interpret your input. If this is the case, please refer to http://rubuffbot.appspot.com/faq/ for information on how to use BuffBot."
				}
			else:
				msg = {
					"userId": specialUID,
					"text": "Thanks for using BuffBot!\nEither one of two things happened:\n1. BuffBot ran out of meat and MP, so it couldn't complete your request. Please send some meat next time for some magical mystery juice if this is the case.\n2. BuffBot did not know how to interpret your input. If this is the case, please refer to http://rubuffbot.appspot.com/faq/ for information on how to use BuffBot."
				}
			send = SendMessageRequest(s, msg)
			send.doRequest()

		d = DeleteMessagesRequest(s, [kmail["id"]])
		d.doRequest()
		logging.info("KMail deleted")

		c = CharpaneRequest(s)
		charData = c.doRequest()
		logging.info("Final MP and Meat: {0}, {1}".format(charData["currentMP"], charData["meat"]))